feat: make each plugin an npm workspace built by a termix-plugin CLI

This commit is contained in:
LukeGus committed 2026-09-22 15:09:50 -05:00
1 parent 4758016f41
commit 5796186a1c
448 files changed
+3087 -2003

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
# Changelog
## 1.0.0
Bundled with Termix 2.9.0.
+22
View File
@@ -0,0 +1,22 @@
# Workspaces
Save and restore named tab/split layouts per user.
Bundled with Termix and enabled by default.
## Layout
manifest.json id, capabilities and what this plugin contributes
src/backend/ activate(ctx) / deactivate(), plus the routes
src/frontend/ the UI it registers
locales/en.json its strings (English only; the rest are translated)
tests/backend/ vitest, node
tests/frontend/ vitest, jsdom
## Commands
npm run build bundle into dist/
npm run test run this plugin's tests
npm run typecheck
See packages/plugin-sdk/ARCHITECTURE.md for the contract this follows.
-58
View File
@@ -1,58 +0,0 @@
/**
* Workspaces - first-party, in-process plugin.
*
* Unlike the other first-party plugins (see src/backend/plugins/first-party.ts),
* this one does not own a transport or touch the shared SSH pool -- its routes
* are plain per-user JSON CRUD against a single repository. It runs in-process
* anyway to keep its existing /workspaces URL and its existing dedicated table
* (user_workspaces, keyed by userId) rather than moving onto
* /plugin-api/workspaces/* and the generic key-value ctx.storage the worker
* tier would require, matching how network-topology was migrated in place
* rather than reworked around the worker ctx boundary.
*
* Like network-topology, this plugin does not get its own port -- it
* registers its Express router with the always-mounted /workspaces
* dispatcher in src/backend/database/routes/workspace-dispatch.ts.
*
* routes.ts is what used to be src/backend/database/routes/workspaces.ts,
* moved here and rewritten from `export default router` into
* startWorkspacesService()/stopWorkspacesService(), called from
* activate()/deactivate() below. The user_workspaces table and its
* repository stay in core (src/backend/database/db/schema.ts,
* src/backend/database/repositories/workspace-repository.ts) -- this
* plugin system has no owned-table migration mechanism of its own, and the
* table carries an FK into core's users table.
*/
import path from "node:path";
import { fileURLToPath } from "node:url";
/**
* Loads a module by its path relative to this file's own directory.
*
* The plugin ships beside dist/backend, so in a built server the compiled
* .js for routes.js sits right next to this .mjs. Under vitest/dev nothing
* imports this plugin directly (the loader loads in-process plugins with a
* plain dynamic import, no tsx loader involved), so the only layout that
* needs to resolve here is the built one.
*/
async function loadRelative(relativePath) {
const here = path.dirname(fileURLToPath(import.meta.url));
const target = path.join(here, `${relativePath}.js`);
return import(new URL(`file://${target.replace(/\\/g, "/")}`).href);
}
let routesModule = null;
export async function activate(ctx) {
routesModule = await loadRelative("routes");
routesModule.startWorkspacesService();
ctx.log.info("Workspaces router registered at /workspaces");
}
export async function deactivate() {
if (routesModule) {
routesModule.stopWorkspacesService();
routesModule = null;
}
}
+1
View File
@@ -0,0 +1 @@
{}
-2
View File
@@ -15,8 +15,6 @@
"api": "1"
},
"capabilities": ["db:own", "ui:surface"],
"backend": "backend/index.mjs",
"frontend": "frontend/index.mjs",
"locales": "locales",
"platforms": ["linux", "win32", "darwin"]
}
+15
View File
@@ -0,0 +1,15 @@
{
"name": "@termix-plugin/workspaces",
"private": true,
"version": "1.0.0",
"type": "module",
"scripts": {
"build": "termix-plugin build",
"test": "termix-plugin test",
"typecheck": "tsc -p tsconfig.json",
"validate": "termix-plugin validate"
},
"devDependencies": {
"@termix/plugin-sdk": "*"
}
}
+11
View File
@@ -0,0 +1,11 @@
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { startWorkspacesService, stopWorkspacesService } from "./routes.js";
export async function activate(ctx: PluginContext) {
startWorkspacesService();
ctx.log.info("Workspaces router registered at /workspaces");
}
export async function deactivate() {
stopWorkspacesService();
}
@@ -1,13 +1,13 @@
import type { AuthenticatedRequest } from "../../../src/types/index.js";
import type { AuthenticatedRequest } from "../../../../src/types/index.js";
import express, { type Request, type Response } from "express";
import { databaseLogger } from "../../../src/backend/utils/logger.js";
import { AuthManager } from "../../../src/backend/utils/auth-manager.js";
import { createCurrentWorkspaceRepository } from "../../../src/backend/database/repositories/factory.js";
import type { WorkspaceRecord } from "../../../src/backend/database/repositories/workspace-repository.js";
import { databaseLogger } from "../../../../src/backend/utils/logger.js";
import { AuthManager } from "../../../../src/backend/utils/auth-manager.js";
import { createCurrentWorkspaceRepository } from "../../../../src/backend/database/repositories/factory.js";
import type { WorkspaceRecord } from "../../../../src/backend/database/repositories/workspace-repository.js";
import {
registerWorkspacesRouter,
unregisterWorkspacesRouter,
} from "../../../src/backend/database/routes/workspace-dispatch.js";
} from "../../../../src/backend/database/routes/workspace-dispatch.js";
export const router = express.Router();
@@ -0,0 +1,204 @@
import { afterEach, describe, expect, it } from "vitest";
import { TestSqliteDatabase } from "../../../../../src/backend/tests/database/repositories/test-support.js";
import { WorkspaceRepository } from "../../../../../src/backend/database/repositories/workspace-repository.js";
describe("WorkspaceRepository", () => {
let adapter: TestSqliteDatabase | null = null;
afterEach(async () => {
if (adapter) {
await adapter.close();
adapter = null;
}
});
async function createRepository(
onWrite?: () => void | Promise<void>,
): Promise<WorkspaceRepository> {
adapter = new TestSqliteDatabase();
const context = await adapter.connect();
await adapter.exec(`
INSERT INTO users (id, username, password_hash)
VALUES ('user-1', 'alice', 'hash'), ('user-2', 'bob', 'hash');
`);
return new WorkspaceRepository(context, onWrite);
}
it("creates and lists manual workspaces scoped to the owning user", async () => {
const repo = await createRepository();
await repo.create("user-1", { name: "Prod Debugging", payload: "{}" });
await repo.create("user-2", { name: "Other user's", payload: "{}" });
const list = await repo.listByUser("user-1");
expect(list).toHaveLength(1);
expect(list[0]).toMatchObject({
userId: "user-1",
name: "Prod Debugging",
kind: "manual",
isDefault: false,
});
expect(list[0].syncId).toBeTruthy();
});
it("finds a workspace by id scoped to the owner", async () => {
const repo = await createRepository();
const created = await repo.create("user-1", {
name: "Test A",
payload: "{}",
});
expect(await repo.findById("user-1", created.id)).toMatchObject({
id: created.id,
});
expect(await repo.findById("user-2", created.id)).toBeNull();
});
it("upsertLastSession creates then updates a single row, never a second one", async () => {
const repo = await createRepository();
const first = await repo.upsertLastSession("user-1", '{"tabs":[]}');
expect(first.kind).toBe("last_session");
const second = await repo.upsertLastSession(
"user-1",
'{"tabs":[{"slotId":"a"}]}',
);
expect(second.id).toBe(first.id);
expect(second.payload).toBe('{"tabs":[{"slotId":"a"}]}');
const all = await repo.listByUser("user-1");
expect(all.filter((w) => w.kind === "last_session")).toHaveLength(1);
});
it("update renames/recolors a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", {
name: "Old Name",
payload: "{}",
});
const lastSession = await repo.upsertLastSession("user-1", "{}");
const updated = await repo.update("user-1", manual.id, {
name: "New Name",
color: "#fff",
});
expect(updated).toMatchObject({ name: "New Name", color: "#fff" });
const rejected = await repo.update("user-1", lastSession.id, {
name: "Should not work",
});
expect(rejected).toBeNull();
});
it("updateContent overwrites payload for a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", {
name: "Test A",
payload: "{}",
});
const lastSession = await repo.upsertLastSession("user-1", "{}");
const updated = await repo.updateContent(
"user-1",
manual.id,
'{"tabs":[1]}',
);
expect(updated?.payload).toBe('{"tabs":[1]}');
const rejected = await repo.updateContent(
"user-1",
lastSession.id,
'{"tabs":[2]}',
);
expect(rejected).toBeNull();
});
it("setDefault clears any prior default and rejects last_session", async () => {
const repo = await createRepository();
const a = await repo.create("user-1", { name: "A", payload: "{}" });
const b = await repo.create("user-1", { name: "B", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await repo.setDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(true);
await repo.setDefault("user-1", b.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(false);
expect((await repo.findById("user-1", b.id))?.isDefault).toBe(true);
const rejected = await repo.setDefault("user-1", lastSession.id);
expect(rejected).toBeNull();
});
it("unsetDefault clears isDefault on a manual workspace and rejects last_session", async () => {
const repo = await createRepository();
const a = await repo.create("user-1", { name: "A", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await repo.setDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(true);
await repo.unsetDefault("user-1", a.id);
expect((await repo.findById("user-1", a.id))?.isDefault).toBe(false);
const rejected = await repo.unsetDefault("user-1", lastSession.id);
expect(rejected).toBeNull();
});
it("touchLastUsed sets lastUsedAt", async () => {
const repo = await createRepository();
const workspace = await repo.create("user-1", {
name: "A",
payload: "{}",
});
expect(workspace.lastUsedAt).toBeNull();
await repo.touchLastUsed(
"user-1",
workspace.id,
"2026-08-11T00:00:00.000Z",
);
expect((await repo.findById("user-1", workspace.id))?.lastUsedAt).toBe(
"2026-08-11T00:00:00.000Z",
);
});
it("delete removes a manual workspace but rejects last_session", async () => {
const repo = await createRepository();
const manual = await repo.create("user-1", { name: "A", payload: "{}" });
const lastSession = await repo.upsertLastSession("user-1", "{}");
await expect(repo.delete("user-1", lastSession.id)).resolves.toBe(false);
await expect(repo.delete("user-1", manual.id)).resolves.toBe(true);
expect(await repo.findById("user-1", manual.id)).toBeNull();
});
it("triggers writes on create/update/delete", async () => {
let writeCount = 0;
const repo = await createRepository(() => {
writeCount += 1;
});
const created = await repo.create("user-1", {
name: "A",
payload: "{}",
});
await repo.update("user-1", created.id, { name: "B" });
await repo.delete("user-1", created.id);
expect(writeCount).toBe(3);
});
it("deleteByUserId removes every workspace owned by the user", async () => {
const repo = await createRepository();
await repo.create("user-1", { name: "A", payload: "{}" });
await repo.create("user-1", { name: "B", payload: "{}" });
await repo.create("user-2", { name: "C", payload: "{}" });
await expect(repo.deleteByUserId("user-1")).resolves.toBe(2);
expect(await repo.listByUser("user-1")).toHaveLength(0);
expect(await repo.listByUser("user-2")).toHaveLength(1);
});
});
@@ -0,0 +1,518 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { Request, Response, Router } from "express";
type WorkspaceRow = {
id: number;
userId: string;
name: string;
color: string | null;
icon: string | null;
kind: "manual" | "last_session";
isDefault: boolean;
payload: string;
syncId: string;
createdAt: string;
updatedAt: string;
lastUsedAt: string | null;
};
const state = vi.hoisted(() => ({
currentUserId: "user-1",
workspaces: new Map<number, WorkspaceRow>(),
nextId: 1,
}));
vi.mock("../../../../src/backend/database/db/index.js", () => ({ db: {} }));
vi.mock("../../../../src/backend/utils/logger.js", () => ({
databaseLogger: {
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
success: vi.fn(),
},
}));
vi.mock("../../../../src/backend/utils/auth-manager.js", () => ({
AuthManager: {
getInstance: () => ({
createAuthMiddleware:
() =>
(req: Record<string, unknown>, _res: unknown, next: () => void) => {
req.userId = state.currentUserId;
next();
},
createDataAccessMiddleware:
() => (_req: unknown, _res: unknown, next: () => void) =>
next(),
}),
},
}));
function findByIdForUser(userId: string, id: number): WorkspaceRow | null {
const row = state.workspaces.get(id);
return row && row.userId === userId ? row : null;
}
vi.mock("../../../../src/backend/database/repositories/factory.js", () => ({
createCurrentWorkspaceRepository: () => ({
listByUser: async (userId: string) =>
[...state.workspaces.values()].filter((w) => w.userId === userId),
findById: async (userId: string, id: number) => findByIdForUser(userId, id),
findLastSession: async (userId: string) =>
[...state.workspaces.values()].find(
(w) => w.userId === userId && w.kind === "last_session",
) ?? null,
upsertLastSession: async (userId: string, payload: string) => {
const existing = [...state.workspaces.values()].find(
(w) => w.userId === userId && w.kind === "last_session",
);
if (existing) {
existing.payload = payload;
existing.updatedAt = new Date().toISOString();
return existing;
}
const row: WorkspaceRow = {
id: state.nextId++,
userId,
name: "Last Session",
color: null,
icon: null,
kind: "last_session",
isDefault: false,
payload,
syncId: `sync-${state.nextId}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
lastUsedAt: null,
};
state.workspaces.set(row.id, row);
return row;
},
create: async (
userId: string,
input: {
name: string;
color?: string | null;
icon?: string | null;
payload: string;
},
) => {
const row: WorkspaceRow = {
id: state.nextId++,
userId,
name: input.name,
color: input.color ?? null,
icon: input.icon ?? null,
kind: "manual",
isDefault: false,
payload: input.payload,
syncId: `sync-${state.nextId}`,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
lastUsedAt: null,
};
state.workspaces.set(row.id, row);
return row;
},
update: async (
userId: string,
id: number,
input: { name?: string; color?: string | null; icon?: string | null },
) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
if (input.name !== undefined) row.name = input.name;
if (input.color !== undefined) row.color = input.color;
if (input.icon !== undefined) row.icon = input.icon;
return row;
},
updateContent: async (userId: string, id: number, payload: string) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
row.payload = payload;
return row;
},
setDefault: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
for (const w of state.workspaces.values()) {
if (w.userId === userId && w.kind === "manual") w.isDefault = false;
}
row.isDefault = true;
return row;
},
unsetDefault: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return null;
row.isDefault = false;
return row;
},
touchLastUsed: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (row) row.lastUsedAt = new Date().toISOString();
},
delete: async (userId: string, id: number) => {
const row = findByIdForUser(userId, id);
if (!row || row.kind !== "manual") return false;
state.workspaces.delete(id);
return true;
},
}),
}));
vi.mock(
"../../../../src/backend/database/routes/workspace-dispatch.js",
() => ({
registerWorkspacesRouter: vi.fn(),
unregisterWorkspacesRouter: vi.fn(),
}),
);
const { router } = await import("../../src/backend/routes.js");
function findLayer(method: string, path: string) {
const stack = (router as unknown as Router).stack as Array<{
route?: {
path: string;
methods: Record<string, boolean>;
stack: Array<{ handle: (req: Request, res: Response) => unknown }>;
};
}>;
const layer = stack.find(
(l) => l.route?.path === path && l.route?.methods[method],
);
if (!layer?.route) throw new Error(`No route for ${method} ${path}`);
return layer.route.stack[layer.route.stack.length - 1].handle;
}
function makeReqRes(overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
}) {
const req = {
userId: state.currentUserId,
body: overrides.body ?? {},
params: overrides.params ?? {},
headers: {},
} as unknown as Request;
const res = {
statusCode: 200,
jsonBody: null as unknown,
status(code: number) {
(this as unknown as { statusCode: number }).statusCode = code;
return this;
},
json(payload: unknown) {
(this as unknown as { jsonBody: unknown }).jsonBody = payload;
return this;
},
} as unknown as Response & { statusCode: number; jsonBody: unknown };
return { req, res };
}
async function invoke(
method: string,
path: string,
overrides: {
body?: Record<string, unknown>;
params?: Record<string, unknown>;
} = {},
) {
const handler = findLayer(method, path);
const { req, res } = makeReqRes(overrides);
await handler(req, res);
return res as unknown as {
statusCode: number;
jsonBody: Record<string, unknown> | null;
};
}
beforeEach(() => {
state.currentUserId = "user-1";
state.workspaces = new Map();
state.nextId = 1;
});
describe("GET /", () => {
it("returns the list with a computed tabCount", async () => {
await invoke("post", "/", {
body: {
name: "Test A",
payload: { version: 1, tabs: [{ slotId: "a" }, { slotId: "b" }] },
},
});
const res = await invoke("get", "/");
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toHaveLength(1);
expect(
(res.jsonBody as unknown as { tabCount: number }[])[0].tabCount,
).toBe(2);
});
});
describe("POST /", () => {
it("400s when name is missing", async () => {
const res = await invoke("post", "/", {
body: { payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(400);
});
it("400s when payload has no tabs array", async () => {
const res = await invoke("post", "/", {
body: { name: "Test A", payload: { version: 1 } },
});
expect(res.statusCode).toBe(400);
});
it("200s and creates a manual workspace", async () => {
const res = await invoke("post", "/", {
body: { name: "Test A", payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ name: "Test A", kind: "manual" });
});
});
describe("PATCH /:id", () => {
it("rejects renaming the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("patch", "/:id", {
params: { id: String(id) },
body: { name: "Nope" },
});
expect(res.statusCode).toBe(404);
});
it("renames a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "Old", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("patch", "/:id", {
params: { id: String(id) },
body: { name: "New" },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ name: "New" });
});
it("404s for a nonexistent id", async () => {
const res = await invoke("patch", "/:id", {
params: { id: "999" },
body: { name: "New" },
});
expect(res.statusCode).toBe(404);
});
});
describe("PUT /:id/content", () => {
it("updates payload for a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [{ slotId: "x" }] } },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ tabCount: 1 });
});
it("404s on wrong owner", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
state.currentUserId = "user-2";
const res = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [] } },
});
expect(res.statusCode).toBe(404);
});
});
describe("DELETE /:id", () => {
it("rejects deleting the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("delete", "/:id", { params: { id: String(id) } });
expect(res.statusCode).toBe(404);
});
it("404s for a nonexistent id", async () => {
const res = await invoke("delete", "/:id", { params: { id: "999" } });
expect(res.statusCode).toBe(404);
});
it("deletes a manual workspace", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("delete", "/:id", { params: { id: String(id) } });
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toEqual({ success: true });
});
});
describe("POST /:id/duplicate", () => {
it("produces a second independent row", async () => {
const created = await invoke("post", "/", {
body: {
name: "A",
payload: { version: 1, tabs: [{ slotId: "a" }] },
},
});
const id = (created.jsonBody as unknown as { id: number }).id;
const dup = await invoke("post", "/:id/duplicate", {
params: { id: String(id) },
body: { name: "A (copy)" },
});
expect(dup.statusCode).toBe(200);
expect(dup.jsonBody).toMatchObject({ name: "A (copy)", tabCount: 1 });
const updateOriginal = await invoke("put", "/:id/content", {
params: { id: String(id) },
body: { payload: { version: 1, tabs: [] } },
});
expect(updateOriginal.jsonBody).toMatchObject({ tabCount: 0 });
const dupId = (dup.jsonBody as unknown as { id: number }).id;
const refetched = await invoke("get", "/");
const dupRow = (
refetched.jsonBody as unknown as { id: number; tabCount: number }[]
).find((w) => w.id === dupId);
expect(dupRow?.tabCount).toBe(1);
});
});
describe("POST /:id/set-default", () => {
it("clears a previous default and sets the new one", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const b = await invoke("post", "/", {
body: { name: "B", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
const bId = (b.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const second = await invoke("post", "/:id/set-default", {
params: { id: String(bId) },
});
expect(second.jsonBody).toMatchObject({ isDefault: true });
const list = await invoke("get", "/");
const aRow = (
list.jsonBody as unknown as { id: number; isDefault: boolean }[]
).find((w) => w.id === aId);
expect(aRow?.isDefault).toBe(false);
});
it("is idempotent when re-called on an already-default row", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const again = await invoke("post", "/:id/set-default", {
params: { id: String(aId) },
});
expect(again.statusCode).toBe(200);
expect(again.jsonBody).toMatchObject({ isDefault: true });
});
});
describe("POST /:id/unset-default", () => {
it("clears isDefault on a manual workspace", async () => {
const a = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [] } },
});
const aId = (a.jsonBody as unknown as { id: number }).id;
await invoke("post", "/:id/set-default", { params: { id: String(aId) } });
const res = await invoke("post", "/:id/unset-default", {
params: { id: String(aId) },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({ isDefault: false });
});
it("rejects unsetting the last_session row", async () => {
const created = await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("post", "/:id/unset-default", {
params: { id: String(id) },
});
expect(res.statusCode).toBe(404);
});
});
describe("POST /:id/apply", () => {
it("touches lastUsedAt and returns the parsed payload", async () => {
const created = await invoke("post", "/", {
body: { name: "A", payload: { version: 1, tabs: [{ slotId: "a" }] } },
});
const id = (created.jsonBody as unknown as { id: number }).id;
const res = await invoke("post", "/:id/apply", {
params: { id: String(id) },
});
expect(res.statusCode).toBe(200);
expect(res.jsonBody).toMatchObject({
payload: { version: 1, tabs: [{ slotId: "a" }] },
});
expect(
(res.jsonBody as unknown as { lastUsedAt: string | null }).lastUsedAt,
).toBeTruthy();
});
});
describe("PUT /last-session and GET /last-session", () => {
it("returns null before any save", async () => {
const res = await invoke("get", "/last-session");
expect(res.jsonBody).toBeNull();
});
it("upserts idempotently - two calls produce one row", async () => {
await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [] } },
});
await invoke("put", "/last-session", {
body: { payload: { version: 1, tabs: [{ slotId: "a" }] } },
});
const list = await invoke("get", "/");
const lastSessionRows = (
list.jsonBody as unknown as { kind: string }[]
).filter((w) => w.kind === "last_session");
expect(lastSessionRows).toHaveLength(1);
const res = await invoke("get", "/last-session");
expect(res.jsonBody).toMatchObject({ tabCount: 1 });
});
});
@@ -0,0 +1,328 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
buildWorkspacePayload,
buildWorkspaceTabSnapshots,
remapSlotIds,
resolveWorkspaceTabTarget,
} from "../../src/frontend/workspaceUtils";
import type { Host, Tab, WorkspaceTabSnapshot } from "@/types/ui-types";
afterEach(() => vi.unstubAllGlobals());
function makeHost(overrides: Partial<Host> = {}): Host {
return {
id: "1",
name: "web-01",
username: "root",
ip: "10.0.0.1",
port: 22,
folder: "",
online: true,
cpu: null,
ram: null,
lastAccess: "2026-01-01T00:00:00.000Z",
authType: "password",
enableTerminal: true,
enableCommandHistory: true,
syncId: "sync-web-01",
...overrides,
} as Host;
}
function makeTab(overrides: Partial<Tab> = {}): Tab {
return {
id: "tab-1",
instanceId: "instance-1",
type: "terminal",
label: "web-01",
openedAt: 0,
...overrides,
} as Tab;
}
describe("buildWorkspaceTabSnapshots", () => {
it("falls back when randomUUID is unavailable", () => {
vi.stubGlobal("crypto", {});
const tabs = [makeTab({ id: "t1" }), makeTab({ id: "t2" })];
const { snapshots } = buildWorkspaceTabSnapshots(tabs);
expect(snapshots).toHaveLength(2);
expect(snapshots[0].slotId).toBeTruthy();
expect(snapshots[1].slotId).not.toBe(snapshots[0].slotId);
});
it("captures host-bound and singleton tabs with generated slot ids", () => {
let counter = 0;
const genSlotId = () => `slot-${counter++}`;
const host = makeHost();
const tabs: Tab[] = [
makeTab({ id: "t1", type: "terminal", host, label: "web-01" }),
makeTab({ id: "t2", type: "tunnel", label: "Tunnels" }),
];
const { snapshots, slotIdByTabId } = buildWorkspaceTabSnapshots(
tabs,
genSlotId,
);
expect(snapshots).toHaveLength(2);
expect(snapshots[0]).toMatchObject({
slotId: "slot-0",
type: "terminal",
hostSyncId: "sync-web-01",
hostNameSnapshot: "web-01",
});
expect(snapshots[1]).toMatchObject({
slotId: "slot-1",
type: "tunnel",
hostSyncId: null,
});
expect(slotIdByTabId.get("t1")).toBe("slot-0");
expect(slotIdByTabId.get("t2")).toBe("slot-1");
});
it("excludes rail-view pseudo tabs (host-manager, user-profile, admin-settings)", () => {
const tabs: Tab[] = [
makeTab({ id: "t1", type: "host-manager" }),
makeTab({ id: "t2", type: "user-profile" }),
makeTab({ id: "t3", type: "admin-settings" }),
makeTab({ id: "t4", type: "tunnel" }),
];
const { snapshots } = buildWorkspaceTabSnapshots(tabs);
expect(snapshots).toHaveLength(1);
expect(snapshots[0].type).toBe("tunnel");
});
it("excludes the dashboard tab - it's a permanent fallback, not a meaningful part of a saved arrangement", () => {
const tabs: Tab[] = [
makeTab({ id: "t1", type: "dashboard" }),
makeTab({ id: "t2", type: "terminal", host: makeHost() }),
];
const { snapshots } = buildWorkspaceTabSnapshots(tabs);
expect(snapshots).toHaveLength(1);
expect(snapshots[0].type).toBe("terminal");
});
it("captures serialConfig only for serial tabs", () => {
const tabs: Tab[] = [
makeTab({
id: "t1",
type: "serial",
serialConfig: {
path: "/dev/ttyUSB0",
baudRate: 9600,
dataBits: 8,
stopBits: 1,
parity: "none",
},
}),
makeTab({ id: "t2", type: "terminal", host: makeHost() }),
];
const { snapshots } = buildWorkspaceTabSnapshots(tabs);
expect(snapshots[0].serialConfig).toEqual({
path: "/dev/ttyUSB0",
baudRate: 9600,
dataBits: 8,
stopBits: 1,
parity: "none",
});
expect(snapshots[0].hostSyncId).toBeNull();
expect(snapshots[1].serialConfig).toBeUndefined();
});
});
describe("remapSlotIds", () => {
it("maps slot ids to live tab ids, preserving nulls and unresolved slots", () => {
const map = new Map([
["slot-a", "new-tab-1"],
["slot-b", "new-tab-2"],
]);
const result = remapSlotIds(
["slot-a", null, "slot-b", "slot-missing"],
map,
);
expect(result).toEqual(["new-tab-1", null, "new-tab-2", null]);
});
});
describe("resolveWorkspaceTabTarget", () => {
const hosts: Host[] = [makeHost({ id: "1", syncId: "sync-web-01" })];
it("resolves a serial snapshot with a config as 'serial'", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "serial",
label: "Serial",
serialConfig: {
path: "/dev/ttyUSB0",
baudRate: 9600,
dataBits: 8,
stopBits: 1,
parity: "none",
},
};
expect(resolveWorkspaceTabTarget(snapshot, hosts)).toEqual({
kind: "serial",
});
});
it("skips a serial snapshot missing its config", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "serial",
label: "Serial",
};
expect(resolveWorkspaceTabTarget(snapshot, hosts)).toEqual({
kind: "skip",
});
});
it("resolves a host-bound snapshot by matching syncId", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "terminal",
label: "web-01",
hostSyncId: "sync-web-01",
};
const result = resolveWorkspaceTabTarget(snapshot, hosts);
expect(result.kind).toBe("host");
expect((result as { host: Host }).host.syncId).toBe("sync-web-01");
});
it("skips a host-bound snapshot whose host no longer exists", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "terminal",
label: "deleted-host",
hostSyncId: "sync-gone",
hostNameSnapshot: "deleted-host",
};
expect(resolveWorkspaceTabTarget(snapshot, hosts)).toEqual({
kind: "skip",
});
});
it("resolves a hostless singleton type without a hostSyncId", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "tunnel",
label: "Tunnels",
};
expect(resolveWorkspaceTabTarget(snapshot, hosts)).toEqual({
kind: "singleton",
host: undefined,
});
});
it("resolves a singleton type WITH a resolved host as singleton+host (e.g. fleet-inventory)", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "fleet-inventory",
label: "Fleet",
hostSyncId: "sync-web-01",
};
const result = resolveWorkspaceTabTarget(snapshot, hosts);
expect(result.kind).toBe("singleton");
expect((result as { host?: Host }).host?.syncId).toBe("sync-web-01");
});
it("skips a non-singleton, non-serial type with no resolvable host", () => {
const snapshot: WorkspaceTabSnapshot = {
slotId: "s1",
type: "files",
label: "files",
};
expect(resolveWorkspaceTabTarget(snapshot, hosts)).toEqual({
kind: "skip",
});
});
});
describe("buildWorkspacePayload", () => {
it("builds a full payload including pane assignment remapped to slot ids", () => {
let counter = 0;
const genSlotId = () => `slot-${counter++}`;
const host = makeHost();
const tabs: Tab[] = [
makeTab({ id: "t1", type: "terminal", host }),
makeTab({ id: "t2", type: "files", host }),
];
const payload = buildWorkspacePayload({
tabs,
activeTabId: "t1",
splitMode: "2-way",
paneTabIds: ["t1", "t2", null, null, null, null],
rowSizes: [100],
rowColSizes: [[50, 50]],
genSlotId,
});
expect(payload.version).toBe(1);
expect(payload.activeSlotId).toBe("slot-0");
expect(payload.paneTabIds).toEqual([
"slot-0",
"slot-1",
null,
null,
null,
null,
]);
expect(payload.splitMode).toBe("2-way");
expect(payload.rowSizes).toEqual([100]);
expect(payload.rowColSizes).toEqual([[50, 50]]);
});
it("sets activeSlotId to null when the active tab is not capturable", () => {
const payload = buildWorkspacePayload({
tabs: [makeTab({ id: "t1", type: "host-manager" })],
activeTabId: "t1",
splitMode: "none",
paneTabIds: [null, null, null, null, null, null],
rowSizes: [100],
rowColSizes: [[100]],
});
expect(payload.activeSlotId).toBeNull();
expect(payload.tabs).toHaveLength(0);
});
it("round-trips the sidebar arrangement", () => {
const payload = buildWorkspacePayload({
tabs: [],
activeTabId: "dashboard",
splitMode: "none",
paneTabIds: [null, null, null, null, null, null],
rowSizes: [100],
rowColSizes: [[100]],
sidebar: {
left: { view: "hosts", open: true, width: 320 },
right: { view: "history", open: true, width: 240 },
},
});
expect(payload.sidebar).toEqual({
left: { view: "hosts", open: true, width: 320 },
right: { view: "history", open: true, width: 240 },
});
});
it("omits sidebar when not supplied so older payloads stay unchanged", () => {
const payload = buildWorkspacePayload({
tabs: [],
activeTabId: "dashboard",
splitMode: "none",
paneTabIds: [null, null, null, null, null, null],
rowSizes: [100],
rowColSizes: [[100]],
});
expect(payload.sidebar).toBeUndefined();
expect(payload.version).toBe(1);
});
});
@@ -0,0 +1,118 @@
import { describe, expect, it, vi, beforeEach } from "vitest";
const authApiMock = vi.hoisted(() => ({
get: vi.fn(async () => ({ data: [] })),
post: vi.fn(async () => ({ data: {} })),
patch: vi.fn(async () => ({ data: {} })),
put: vi.fn(async () => ({ data: {} })),
delete: vi.fn(async () => ({ data: { success: true } })),
}));
vi.mock("@/main-axios", () => ({
authApi: authApiMock,
handleApiError: (error: unknown) => error,
}));
import {
listWorkspaces,
createWorkspace,
renameWorkspace,
updateWorkspaceContent,
deleteWorkspace,
duplicateWorkspace,
setDefaultWorkspace,
applyWorkspaceServer,
getLastSessionWorkspace,
saveLastSessionWorkspace,
} from "../../src/frontend/workspaces-api";
import type { WorkspacePayload } from "@/types/ui-types";
beforeEach(() => {
authApiMock.get.mockClear();
authApiMock.post.mockClear();
authApiMock.patch.mockClear();
authApiMock.put.mockClear();
authApiMock.delete.mockClear();
});
const samplePayload: WorkspacePayload = {
version: 1,
tabs: [],
activeSlotId: null,
splitMode: "none",
paneTabIds: [null, null, null, null, null, null],
rowSizes: [100],
rowColSizes: [[100]],
};
describe("workspaces-api", () => {
it("listWorkspaces GETs /workspaces", async () => {
authApiMock.get.mockResolvedValueOnce({ data: [{ id: 1 }] });
const result = await listWorkspaces();
expect(authApiMock.get).toHaveBeenCalledWith("/workspaces");
expect(result).toEqual([{ id: 1 }]);
});
it("createWorkspace POSTs /workspaces with the payload", async () => {
await createWorkspace({
name: "Test A",
color: "#fff",
payload: samplePayload,
});
expect(authApiMock.post).toHaveBeenCalledWith("/workspaces", {
name: "Test A",
color: "#fff",
payload: samplePayload,
});
});
it("renameWorkspace PATCHes /workspaces/:id", async () => {
await renameWorkspace(5, { name: "New Name" });
expect(authApiMock.patch).toHaveBeenCalledWith("/workspaces/5", {
name: "New Name",
});
});
it("updateWorkspaceContent PUTs /workspaces/:id/content", async () => {
await updateWorkspaceContent(5, samplePayload);
expect(authApiMock.put).toHaveBeenCalledWith("/workspaces/5/content", {
payload: samplePayload,
});
});
it("deleteWorkspace DELETEs /workspaces/:id", async () => {
await deleteWorkspace(5);
expect(authApiMock.delete).toHaveBeenCalledWith("/workspaces/5");
});
it("duplicateWorkspace POSTs /workspaces/:id/duplicate with a name", async () => {
await duplicateWorkspace(5, "Test A (copy)");
expect(authApiMock.post).toHaveBeenCalledWith("/workspaces/5/duplicate", {
name: "Test A (copy)",
});
});
it("setDefaultWorkspace POSTs /workspaces/:id/set-default", async () => {
await setDefaultWorkspace(5);
expect(authApiMock.post).toHaveBeenCalledWith("/workspaces/5/set-default");
});
it("applyWorkspaceServer POSTs /workspaces/:id/apply", async () => {
await applyWorkspaceServer(5);
expect(authApiMock.post).toHaveBeenCalledWith("/workspaces/5/apply");
});
it("getLastSessionWorkspace GETs /workspaces/last-session", async () => {
authApiMock.get.mockResolvedValueOnce({ data: null });
const result = await getLastSessionWorkspace();
expect(authApiMock.get).toHaveBeenCalledWith("/workspaces/last-session");
expect(result).toBeNull();
});
it("saveLastSessionWorkspace PUTs /workspaces/last-session", async () => {
await saveLastSessionWorkspace(samplePayload);
expect(authApiMock.put).toHaveBeenCalledWith("/workspaces/last-session", {
payload: samplePayload,
});
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "@termix/plugin-sdk/tsconfig.plugin.json",
"compilerOptions": {
"paths": {
"@/types/*": ["../../src/types/*"],
"@/*": ["../../src/ui/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.tsx", "tests/**/*.ts", "tests/**/*.tsx"]
}
+3
View File
@@ -0,0 +1,3 @@
import { pluginVitestConfig } from "@termix/plugin-sdk/vitest-preset";
export default pluginVitestConfig(import.meta.url);