feat: rebuild workspaces as the reference plugin

This commit is contained in:
LukeGus committed 2026-09-23 07:04:03 -05:00
1 parent d774df8b41
commit f217d8db89
79 files changed
+32995 -2184

No files matched your search

+41 -3
View File
@@ -1,11 +1,49 @@
import type { Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import { startWorkspacesService, stopWorkspacesService } from "./routes.js";
import { workspaces } from "./tables.js";
import { createWorkspaceRepository } from "./repository.js";
import { registerWorkspaceRoutes } from "./routes.js";
/** What other plugins get from ctx.services.get("workspaces.saved"). */
export interface WorkspacesService {
/** The calling user's workspaces, without their layouts. */
list: () => Promise<Array<{ id: number; name: string; isDefault: boolean }>>;
}
export async function activate(ctx: PluginContext) {
startWorkspacesService(ctx.http.router());
const table = await ctx.db.define(workspaces);
const repo = createWorkspaceRepository(ctx.db, table);
registerWorkspaceRoutes(ctx.http.router<Router>(), repo, ctx);
// The last_session row belongs to one install. Syncing it would leave the
// user with two, one from each side.
ctx.sync.registerEntity({
type: "workspaces",
table,
order: 200,
shouldSync: (row) => row.kind !== "last_session",
});
const service: WorkspacesService = {
list: async () => {
const userId = ctx.currentActor();
if (!userId) return [];
const rows = await repo.listByUser(userId);
return rows
.filter((row) => row.kind === "manual")
.map((row) => ({
id: row.id,
name: row.name,
isDefault: !!row.isDefault,
}));
},
};
ctx.services.provide("workspaces.saved", service);
ctx.log.info("Workspaces routes mounted at /plugin-api/workspaces");
}
export async function deactivate() {
stopWorkspacesService();
// Everything above was registered through ctx and is disposed by core.
}
@@ -0,0 +1,252 @@
import { randomUUID } from "node:crypto";
import { and, eq, ne } from "drizzle-orm";
import type { PluginDatabase } from "@termix/plugin-sdk/backend";
export type WorkspaceKind = "manual" | "last_session";
export interface WorkspaceRecord {
id: number;
userId: string;
name: string;
color: string | null;
icon: string | null;
kind: WorkspaceKind;
isDefault: boolean;
payload: string;
syncId: string | null;
createdAt: string;
updatedAt: string;
lastUsedAt: string | null;
}
export interface WorkspaceCreateInput {
name: string;
color?: string | null;
icon?: string | null;
payload: string;
}
export interface WorkspaceUpdateInput {
name?: string;
color?: string | null;
icon?: string | null;
}
/* eslint-disable @typescript-eslint/no-explicit-any */
// The table comes from ctx.db.define, which the SDK hands back untyped, and
// the drizzle handle is the server's own. Typed at this module's edge instead.
type Table = any;
type Drizzle = any;
/* eslint-enable @typescript-eslint/no-explicit-any */
export type WorkspaceRepository = ReturnType<typeof createWorkspaceRepository>;
/**
* Per-user workspace storage.
*
* Written without RETURNING so it runs the same on all three engines: an
* insert is read back by the sync id it was given, an update by its id.
*/
export function createWorkspaceRepository(db: PluginDatabase, table: Table) {
const client = () => db.client<Drizzle>();
async function findById(
userId: string,
id: number,
): Promise<WorkspaceRecord | null> {
const drizzle = await client();
const rows = await drizzle
.select()
.from(table)
.where(and(eq(table.id, id), eq(table.userId, userId)))
.limit(1);
return (rows[0] as WorkspaceRecord) ?? null;
}
async function findBySyncId(syncId: string): Promise<WorkspaceRecord> {
const drizzle = await client();
const rows = await drizzle
.select()
.from(table)
.where(eq(table.syncId, syncId))
.limit(1);
return rows[0] as WorkspaceRecord;
}
async function findLastSession(
userId: string,
): Promise<WorkspaceRecord | null> {
const drizzle = await client();
const rows = await drizzle
.select()
.from(table)
.where(and(eq(table.userId, userId), eq(table.kind, "last_session")))
.limit(1);
return (rows[0] as WorkspaceRecord) ?? null;
}
async function insert(
userId: string,
values: Omit<
WorkspaceRecord,
"id" | "userId" | "syncId" | "createdAt" | "updatedAt" | "lastUsedAt"
>,
now: string,
): Promise<WorkspaceRecord> {
const syncId = randomUUID();
const drizzle = await client();
await drizzle
.insert(table)
.values({ ...values, userId, syncId, createdAt: now, updatedAt: now });
await db.persist();
return findBySyncId(syncId);
}
async function write(
userId: string,
id: number,
values: Record<string, unknown>,
): Promise<WorkspaceRecord | null> {
const drizzle = await client();
await drizzle
.update(table)
.set(values)
.where(and(eq(table.id, id), eq(table.userId, userId)));
await db.persist();
return findById(userId, id);
}
/** A manual workspace the user owns, or null. Last Session is not editable. */
async function findManual(
userId: string,
id: number,
): Promise<WorkspaceRecord | null> {
const existing = await findById(userId, id);
return existing && existing.kind === "manual" ? existing : null;
}
return {
findById,
findLastSession,
async listByUser(userId: string): Promise<WorkspaceRecord[]> {
const drizzle = await client();
return drizzle.select().from(table).where(eq(table.userId, userId));
},
async upsertLastSession(
userId: string,
payload: string,
now = new Date().toISOString(),
): Promise<WorkspaceRecord> {
const existing = await findLastSession(userId);
if (!existing) {
return insert(
userId,
{
name: "Last Session",
color: null,
icon: null,
kind: "last_session",
isDefault: false,
payload,
},
now,
);
}
return write(userId, existing.id, { payload, updatedAt: now });
},
async create(
userId: string,
input: WorkspaceCreateInput,
now = new Date().toISOString(),
): Promise<WorkspaceRecord> {
return insert(
userId,
{
name: input.name,
color: input.color ?? null,
icon: input.icon ?? null,
kind: "manual",
isDefault: false,
payload: input.payload,
},
now,
);
},
async update(
userId: string,
id: number,
input: WorkspaceUpdateInput,
now = new Date().toISOString(),
): Promise<WorkspaceRecord | null> {
const existing = await findManual(userId, id);
if (!existing) return null;
return write(userId, id, {
name: input.name ?? existing.name,
color: input.color === undefined ? existing.color : input.color,
icon: input.icon === undefined ? existing.icon : input.icon,
updatedAt: now,
});
},
async updateContent(
userId: string,
id: number,
payload: string,
now = new Date().toISOString(),
): Promise<WorkspaceRecord | null> {
if (!(await findManual(userId, id))) return null;
return write(userId, id, { payload, updatedAt: now });
},
async setDefault(
userId: string,
id: number,
now = new Date().toISOString(),
): Promise<WorkspaceRecord | null> {
if (!(await findManual(userId, id))) return null;
const drizzle = await client();
await drizzle
.update(table)
.set({ isDefault: false, updatedAt: now })
.where(
and(
eq(table.userId, userId),
eq(table.isDefault, true),
ne(table.id, id),
),
);
return write(userId, id, { isDefault: true, updatedAt: now });
},
async unsetDefault(
userId: string,
id: number,
now = new Date().toISOString(),
): Promise<WorkspaceRecord | null> {
if (!(await findManual(userId, id))) return null;
return write(userId, id, { isDefault: false, updatedAt: now });
},
async touchLastUsed(
userId: string,
id: number,
now = new Date().toISOString(),
): Promise<void> {
await write(userId, id, { lastUsedAt: now });
},
async delete(userId: string, id: number): Promise<boolean> {
if (!(await findManual(userId, id))) return false;
const drizzle = await client();
await drizzle
.delete(table)
.where(and(eq(table.id, id), eq(table.userId, userId)));
await db.persist();
return true;
},
};
}
+329 -397
View File
@@ -1,15 +1,6 @@
import type { AuthenticatedRequest } from "../../../../src/types/index.js";
import express, { type Request, type Response, type Router } 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";
export const router = express.Router();
const authManager = AuthManager.getInstance();
const authenticateJWT = authManager.createAuthMiddleware();
const requireDataAccess = authManager.createDataAccessMiddleware();
import type { Request, Response, Router } from "express";
import type { PluginContext } from "@termix/plugin-sdk/backend";
import type { WorkspaceRecord, WorkspaceRepository } from "./repository.js";
function isNonEmptyString(val: unknown): val is string {
return typeof val === "string" && val.trim().length > 0;
@@ -46,73 +37,93 @@ function serialize(record: WorkspaceRecord) {
};
}
function actor(ctx: PluginContext): string {
// Core's plugin router authenticates every request and runs it as that user.
return ctx.currentActor() as string;
}
function logError(
ctx: PluginContext,
message: string,
error: unknown,
details: { operation: string; workspaceId?: number },
): void {
const target =
details.workspaceId !== undefined ? ` ${details.workspaceId}` : "";
ctx.log.error(
`${message}${target} (${details.operation})`,
error instanceof Error ? error : new Error(String(error)),
);
}
/**
* @openapi
* /workspaces:
* get:
* summary: List the current user's saved workspaces
* description: Returns every manual workspace plus the single auto-maintained "Last Session" workspace, each with a computed tabCount.
* tags:
* - Workspaces
* responses:
* 200:
* description: List of workspaces.
* Mounts the workspace routes on the plugin's router, which core serves at
* /plugin-api/workspaces with auth in front. Every route needs workspaces.use,
* so an admin can hide the feature per role.
*/
router.get(
"/",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
export function registerWorkspaceRoutes(
router: Router,
repo: WorkspaceRepository,
ctx: PluginContext,
): void {
router.use(ctx.rbac.require("use") as never);
/**
* @openapi
* /plugin-api/workspaces:
* get:
* summary: List the current user's saved workspaces
* description: Returns every manual workspace plus the single auto-maintained "Last Session" workspace, each with a computed tabCount.
* tags:
* - Workspaces
* responses:
* 200:
* description: List of workspaces.
*/
router.get("/", async (req: Request, res: Response) => {
const userId = actor(ctx);
try {
const records =
await createCurrentWorkspaceRepository().listByUser(userId);
const records = await repo.listByUser(userId);
res.json(records.map(serialize));
} catch (err) {
databaseLogger.error("Failed to list workspaces", err, {
logError(ctx, "Failed to list workspaces", err, {
operation: "workspace_list_failed",
userId,
});
res.status(500).json({ error: "Failed to list workspaces" });
}
},
);
});
/**
* @openapi
* /workspaces:
* post:
* summary: Save the current tab arrangement as a new named workspace
* tags:
* - Workspaces
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* color:
* type: string
* icon:
* type: string
* payload:
* type: object
* responses:
* 200:
* description: Workspace created.
* 400:
* description: Invalid request body.
*/
router.post(
"/",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces:
* post:
* summary: Save the current tab arrangement as a new named workspace
* tags:
* - Workspaces
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* color:
* type: string
* icon:
* type: string
* payload:
* type: object
* responses:
* 200:
* description: Workspace created.
* 400:
* description: Invalid request body.
*/
router.post("/", async (req: Request, res: Response) => {
const userId = actor(ctx);
const { name, color, icon, payload } = req.body ?? {};
if (!isNonEmptyString(name)) {
@@ -125,7 +136,7 @@ router.post(
}
try {
const created = await createCurrentWorkspaceRepository().create(userId, {
const created = await repo.create(userId, {
name: name.trim(),
color: isNonEmptyString(color) ? color : null,
icon: isNonEmptyString(icon) ? icon : null,
@@ -133,77 +144,64 @@ router.post(
});
res.json(serialize(created));
} catch (err) {
databaseLogger.error("Failed to create workspace", err, {
logError(ctx, "Failed to create workspace", err, {
operation: "workspace_create_failed",
userId,
});
res.status(500).json({ error: "Failed to create workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/last-session:
* get:
* summary: Fetch the auto-maintained "Last Session" workspace
* description: Returns null if the current session has never been auto-saved yet.
* tags:
* - Workspaces
* responses:
* 200:
* description: The Last Session workspace, or null.
*/
router.get(
"/last-session",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/last-session:
* get:
* summary: Fetch the auto-maintained "Last Session" workspace
* description: Returns null if the current session has never been auto-saved yet.
* tags:
* - Workspaces
* responses:
* 200:
* description: The Last Session workspace, or null.
*/
router.get("/last-session", async (req: Request, res: Response) => {
const userId = actor(ctx);
try {
const record =
await createCurrentWorkspaceRepository().findLastSession(userId);
const record = await repo.findLastSession(userId);
res.json(record ? serialize(record) : null);
} catch (err) {
databaseLogger.error("Failed to fetch last session workspace", err, {
logError(ctx, "Failed to fetch last session workspace", err, {
operation: "workspace_last_session_get_failed",
userId,
});
res.status(500).json({ error: "Failed to fetch last session workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/last-session:
* put:
* summary: Upsert the auto-maintained "Last Session" workspace
* description: Always overwrites the single Last Session row for the caller - never creates a second one. Called by the frontend's debounced auto-save effect.
* tags:
* - Workspaces
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* payload:
* type: object
* responses:
* 200:
* description: Last Session workspace saved.
* 400:
* description: Invalid request body.
*/
router.put(
"/last-session",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/last-session:
* put:
* summary: Upsert the auto-maintained "Last Session" workspace
* description: Always overwrites the single Last Session row for the caller - never creates a second one. Called by the frontend's debounced auto-save effect.
* tags:
* - Workspaces
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* payload:
* type: object
* responses:
* 200:
* description: Last Session workspace saved.
* 400:
* description: Invalid request body.
*/
router.put("/last-session", async (req: Request, res: Response) => {
const userId = actor(ctx);
const { payload } = req.body ?? {};
if (!isValidPayload(payload)) {
@@ -213,49 +211,43 @@ router.put(
}
try {
const saved = await createCurrentWorkspaceRepository().upsertLastSession(
const saved = await repo.upsertLastSession(
userId,
JSON.stringify(payload),
);
res.json(serialize(saved));
} catch (err) {
databaseLogger.error("Failed to save last session workspace", err, {
logError(ctx, "Failed to save last session workspace", err, {
operation: "workspace_last_session_save_failed",
userId,
});
res.status(500).json({ error: "Failed to save last session workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}:
* patch:
* summary: Rename or recolor a workspace
* description: Does not accept a payload - use PUT /workspaces/{id}/content to overwrite a workspace's saved tab arrangement. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace updated.
* 400:
* description: Invalid request, or target is the Last Session workspace.
* 404:
* description: Workspace not found.
*/
router.patch(
"/:id",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}:
* patch:
* summary: Rename or recolor a workspace
* description: Does not accept a payload - use PUT /workspaces/{id}/content to overwrite a workspace's saved tab arrangement. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace updated.
* 400:
* description: Invalid request, or target is the Last Session workspace.
* 404:
* description: Workspace not found.
*/
router.patch("/:id", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
@@ -267,68 +259,58 @@ router.patch(
}
try {
const updated = await createCurrentWorkspaceRepository().update(
userId,
id,
{
name: name !== undefined ? name.trim() : undefined,
color,
icon,
},
);
const updated = await repo.update(userId, id, {
name: name !== undefined ? name.trim() : undefined,
color,
icon,
});
if (!updated) {
return res.status(404).json({ error: "Workspace not found" });
}
res.json(serialize(updated));
} catch (err) {
databaseLogger.error("Failed to update workspace", err, {
logError(ctx, "Failed to update workspace", err, {
operation: "workspace_update_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to update workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}/content:
* put:
* summary: Overwrite a workspace's saved tab arrangement with a new payload
* description: Used by "Update with current" in the Workspaces panel. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* payload:
* type: object
* responses:
* 200:
* description: Workspace content updated.
* 400:
* description: Invalid request body.
* 404:
* description: Workspace not found.
*/
router.put(
"/:id/content",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}/content:
* put:
* summary: Overwrite a workspace's saved tab arrangement with a new payload
* description: Used by "Update with current" in the Workspaces panel. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* payload:
* type: object
* responses:
* 200:
* description: Workspace content updated.
* 400:
* description: Invalid request body.
* 404:
* description: Workspace not found.
*/
router.put("/:id/content", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
@@ -342,7 +324,7 @@ router.put(
}
try {
const updated = await createCurrentWorkspaceRepository().updateContent(
const updated = await repo.updateContent(
userId,
id,
JSON.stringify(payload),
@@ -353,50 +335,44 @@ router.put(
}
res.json(serialize(updated));
} catch (err) {
databaseLogger.error("Failed to update workspace content", err, {
logError(ctx, "Failed to update workspace content", err, {
operation: "workspace_content_update_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to update workspace content" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}/duplicate:
* post:
* summary: Duplicate a workspace's content and color/icon under a new name
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* responses:
* 200:
* description: New workspace created from the duplicate.
* 404:
* description: Workspace not found.
*/
router.post(
"/:id/duplicate",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}/duplicate:
* post:
* summary: Duplicate a workspace's content and color/icon under a new name
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* requestBody:
* required: true
* content:
* application/json:
* schema:
* type: object
* properties:
* name:
* type: string
* responses:
* 200:
* description: New workspace created from the duplicate.
* 404:
* description: Workspace not found.
*/
router.post("/:id/duplicate", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
const { name } = req.body ?? {};
if (id === null) {
@@ -407,13 +383,12 @@ router.post(
}
try {
const repository = createCurrentWorkspaceRepository();
const source = await repository.findById(userId, id);
const source = await repo.findById(userId, id);
if (!source) {
return res.status(404).json({ error: "Workspace not found" });
}
const created = await repository.create(userId, {
const created = await repo.create(userId, {
name: name.trim(),
color: source.color,
icon: source.icon,
@@ -421,224 +396,181 @@ router.post(
});
res.json(serialize(created));
} catch (err) {
databaseLogger.error("Failed to duplicate workspace", err, {
logError(ctx, "Failed to duplicate workspace", err, {
operation: "workspace_duplicate_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to duplicate workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}/set-default:
* post:
* summary: Mark a workspace as the restore-on-login default
* description: Clears isDefault on any other workspace for the caller. Idempotent if the target is already the default. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace set as default.
* 404:
* description: Workspace not found.
*/
router.post(
"/:id/set-default",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}/set-default:
* post:
* summary: Mark a workspace as the restore-on-login default
* description: Clears isDefault on any other workspace for the caller. Idempotent if the target is already the default. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace set as default.
* 404:
* description: Workspace not found.
*/
router.post("/:id/set-default", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
}
try {
const updated = await createCurrentWorkspaceRepository().setDefault(
userId,
id,
);
const updated = await repo.setDefault(userId, id);
if (!updated) {
return res.status(404).json({ error: "Workspace not found" });
}
res.json(serialize(updated));
} catch (err) {
databaseLogger.error("Failed to set default workspace", err, {
logError(ctx, "Failed to set default workspace", err, {
operation: "workspace_set_default_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to set default workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}/unset-default:
* post:
* summary: Remove a workspace as the restore-on-login default
* description: Idempotent if the target is not currently the default. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace unset as default.
* 404:
* description: Workspace not found.
*/
router.post(
"/:id/unset-default",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}/unset-default:
* post:
* summary: Remove a workspace as the restore-on-login default
* description: Idempotent if the target is not currently the default. Rejects the Last Session workspace.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace unset as default.
* 404:
* description: Workspace not found.
*/
router.post("/:id/unset-default", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
}
try {
const updated = await createCurrentWorkspaceRepository().unsetDefault(
userId,
id,
);
const updated = await repo.unsetDefault(userId, id);
if (!updated) {
return res.status(404).json({ error: "Workspace not found" });
}
res.json(serialize(updated));
} catch (err) {
databaseLogger.error("Failed to unset default workspace", err, {
logError(ctx, "Failed to unset default workspace", err, {
operation: "workspace_unset_default_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to unset default workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}/apply:
* post:
* summary: Fetch a workspace to apply and mark it as just used
* description: Returns the full workspace with its payload parsed, and touches lastUsedAt server-side so the caller does not need a second round trip.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: The workspace to apply.
* 404:
* description: Workspace not found.
*/
router.post(
"/:id/apply",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}/apply:
* post:
* summary: Fetch a workspace to apply and mark it as just used
* description: Returns the full workspace with its payload parsed, and touches lastUsedAt server-side so the caller does not need a second round trip.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: The workspace to apply.
* 404:
* description: Workspace not found.
*/
router.post("/:id/apply", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
}
try {
const repository = createCurrentWorkspaceRepository();
const record = await repository.findById(userId, id);
const record = await repo.findById(userId, id);
if (!record) {
return res.status(404).json({ error: "Workspace not found" });
}
await repository.touchLastUsed(userId, id);
await repo.touchLastUsed(userId, id);
res.json(serialize(record));
} catch (err) {
databaseLogger.error("Failed to apply workspace", err, {
logError(ctx, "Failed to apply workspace", err, {
operation: "workspace_apply_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to apply workspace" });
}
},
);
});
/**
* @openapi
* /workspaces/{id}:
* delete:
* summary: Delete a workspace
* description: Rejects the Last Session workspace, which is not user-deletable.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace deleted.
* 404:
* description: Workspace not found.
*/
router.delete(
"/:id",
authenticateJWT,
requireDataAccess,
async (req: Request, res: Response) => {
const userId = (req as AuthenticatedRequest).userId;
/**
* @openapi
* /plugin-api/workspaces/{id}:
* delete:
* summary: Delete a workspace
* description: Rejects the Last Session workspace, which is not user-deletable.
* tags:
* - Workspaces
* parameters:
* - in: path
* name: id
* required: true
* schema:
* type: integer
* responses:
* 200:
* description: Workspace deleted.
* 404:
* description: Workspace not found.
*/
router.delete("/:id", async (req: Request, res: Response) => {
const userId = actor(ctx);
const id = parseWorkspaceId(req.params.id);
if (id === null) {
return res.status(400).json({ error: "Invalid workspace ID" });
}
try {
const deleted = await createCurrentWorkspaceRepository().delete(
userId,
id,
);
const deleted = await repo.delete(userId, id);
if (!deleted) {
return res.status(404).json({ error: "Workspace not found" });
}
res.json({ success: true });
} catch (err) {
databaseLogger.error("Failed to delete workspace", err, {
logError(ctx, "Failed to delete workspace", err, {
operation: "workspace_delete_failed",
userId,
workspaceId: id,
});
res.status(500).json({ error: "Failed to delete workspace" });
}
},
);
export function startWorkspacesService(mountOn: Router): void {
mountOn.use(router);
}
export function stopWorkspacesService(): void {
// Unmounted by the runtime when the plugin deactivates.
});
}
+45
View File
@@ -0,0 +1,45 @@
import {
adoptLegacyTable,
boolean,
defineTable,
id,
refUser,
text,
timestamp,
varchar,
} from "@termix/plugin-sdk/db";
/**
* Saved tab arrangements, one row per workspace plus one "last_session" row
* per user that the frontend keeps current.
*
* Adopted from core's user_workspaces, so the column and index names are the
* legacy ones: the rename carries the existing rows and index across.
*/
export const workspaces = adoptLegacyTable(
"user_workspaces",
defineTable(
"workspaces",
{
id: id(),
userId: refUser(),
name: text().notNull(),
color: text(),
icon: text(),
// "manual" | "last_session"
kind: text().notNull().default("manual"),
isDefault: boolean().notNull().default(false),
// JSON: the shell layout from app.tabs.getLayout
payload: text().notNull().default("{}"),
syncId: varchar().unique(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp().notNull().defaultNow(),
lastUsedAt: timestamp(),
},
{
indexes: [{ name: "idx_user_workspaces_user_id", columns: ["userId"] }],
},
),
);
export const tables = [workspaces];