Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: workspace_switch ⌘K/voice action + CoS auto-save hook (#2035)

Adam Eivy3d6b737b3cf7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ea5dd1ea52..2a5a5abbf9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Workspace Contexts
+
+- **Switch project workspaces from ⌘K and voice, and CoS now auto-snapshots the workspace it leaves.** A new `workspace_switch` action ("switch workspace to BookLoom", "restore my PortOS context") saves a snapshot of the workspace you're leaving, then reconciles the target project's saved context — git branch, in-repo shell sessions, scoped tasks — and reports what's still live to re-attach; it appears in the ⌘K palette and resolves by voice. When CoS dispatches a coding agent against a different app/repo than it was last working in, it now silently snapshots the previous workspace's context first (snapshot-only — no auto-restore, no LLM calls), so switching between repos preserves what each project looked like, visible on the Workspace Contexts page (#2035).
+
## Delete confirmations
- **Destructive actions now show a clear "Delete? / Cancel" prompt instead of a hidden second click.** Deleting a round, universe, series, share bucket, issue/episode, or a Writers Room work/folder — and removing an Ask conversation or deleting a world in the Universe Builder — used to silently re-arm the same button on the first click, with nothing on screen telling you a second click was needed. Each of these now pops an explicit inline confirm/cancel affordance right where you clicked, so it's obvious what will happen and easy to back out. The pipeline's "replace existing scenes / pages / audio lines" extract buttons got the same treatment (an inline "Replace? / Cancel" row) instead of arming via a fleeting toast. Delete/confirm controls in the Writers Room library were also enlarged to a comfortable 44px touch target for mobile.
diff --git a/server/routes/palette.js b/server/routes/palette.js
index 27f19b8f63..f6b996234b 100644
--- a/server/routes/palette.js
+++ b/server/routes/palette.js
@@ -54,6 +54,7 @@ const PALETTE_ACTIONS = [
{ id: 'code_agent_status', label: 'Coding agent status', section: 'Agents' },
{ id: 'time_now', label: 'Current time', section: 'System' },
{ id: 'catalog_lookup', label: 'Look up ingredient…', section: 'Catalog' },
+ { id: 'workspace_switch', label: 'Switch workspace…', section: 'Workspace' },
];
const PALETTE_ACTION_IDS = new Set(PALETTE_ACTIONS.map((a) => a.id));
diff --git a/server/routes/palette.test.js b/server/routes/palette.test.js
index d44872ca60..a331f31bfe 100644
--- a/server/routes/palette.test.js
+++ b/server/routes/palette.test.js
@@ -42,6 +42,22 @@ vi.mock('../services/catalogDB.js', () => ({
})),
listRefsForIngredient: vi.fn(async () => [{ ingredientId: 'character-1', refKind: 'universe', refId: 'u1', role: 'cast' }]),
}));
+vi.mock('../services/apps.js', () => ({
+ getActiveApps: vi.fn(async () => [{ id: 'bookloom', name: 'BookLoom' }]),
+ PORTOS_APP_ID: 'portos-default',
+}));
+vi.mock('../lib/appResolver.js', () => ({
+ resolveAppByPhrase: vi.fn((phrase, apps) =>
+ (apps || []).find((a) => a.name.toLowerCase().includes(String(phrase).toLowerCase())) || null,
+ ),
+}));
+vi.mock('../services/workspaceContext.js', () => ({
+ snapshotOnRepoSwitch: vi.fn(async () => ({ appId: 'portos-default' })),
+ restoreContext: vi.fn(async () => ({
+ saved: { branch: 'main' },
+ restorable: { shellSessions: [{ sessionId: 's1' }, { sessionId: 's2' }], missingShellSessionIds: [], branchMatches: true },
+ })),
+}));
vi.mock('../services/askService.js', () => ({
VALID_MODES: new Set(['ask', 'advise', 'draft']),
runAsk: vi.fn(async function* () {
@@ -109,6 +125,17 @@ describe('GET /api/palette/manifest', () => {
expect(ids).toContain('meatspace_log_workout');
});
+ it('exposes workspace_switch with its description + workspace param hydrated from the voice tool', async () => {
+ const res = await request(makeApp()).get('/api/palette/manifest');
+ const action = res.body.actions.find((a) => a.id === 'workspace_switch');
+ expect(action).toBeTruthy();
+ expect(action.section).toBe('Workspace');
+ expect(action.label).toMatch(/switch workspace/i);
+ // Description/params hydrate from the voice tool registry (DRY link).
+ expect(action.description).toMatch(/workspace|project/i);
+ expect(action.parameters?.properties?.workspace).toBeTruthy();
+ });
+
it('keeps ui_describe_visually OFF the palette (no screenshot context)', async () => {
const res = await request(makeApp()).get('/api/palette/manifest');
const ids = res.body.actions.map((a) => a.id);
@@ -177,6 +204,27 @@ describe('POST /api/palette/action/:id', () => {
expect(hit.snippet).toMatch(/tall stoic ranger/);
});
+ it('dispatches workspace_switch — snapshots the leaving workspace then restores the target', async () => {
+ const res = await request(makeApp())
+ .post('/api/palette/action/workspace_switch')
+ .send({ args: { workspace: 'BookLoom' } });
+ expect(res.status).toBe(200);
+ expect(res.body.ok).toBe(true);
+ expect(res.body.result.workspace).toBe('bookloom');
+ expect(res.body.result.reattachable).toBe(2);
+ expect(res.body.result.snapshotted).toBe('portos-default');
+ expect(res.body.result.summary).toMatch(/Switched to BookLoom/);
+ });
+
+ it('workspace_switch reports an unknown workspace instead of throwing', async () => {
+ const res = await request(makeApp())
+ .post('/api/palette/action/workspace_switch')
+ .send({ args: { workspace: 'nonexistent-app' } });
+ expect(res.status).toBe(200);
+ expect(res.body.ok).toBe(false);
+ expect(res.body.result.summary).toMatch(/don't see a project/i);
+ });
+
it('dispatches ui_ask through the palette and returns the answer + sources', async () => {
const res = await request(makeApp())
.post('/api/palette/action/ui_ask')
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 4a4381b898..e814f7a0b2 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -317,6 +317,18 @@ export async function spawnAgentForTask(task) {
}
const { workspacePath, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;
+ // Auto-snapshot the workspace context of the app CoS was last working in
+ // when this dispatch switches to a different app/repo (#2035). Snapshot-only
+ // — it never restores and never calls an LLM. Dynamic import avoids pulling
+ // the workspace-context graph into this hot module's load path; the call is
+ // defensive so a missing current context (or any failure) can't break the
+ // spawn.
+ await import('./workspaceContext.js')
+ .then((ws) => ws.snapshotOnRepoSwitch(task.metadata?.app || null))
+ .catch((err) => {
+ emitLog('warn', `Workspace auto-snapshot skipped for task ${task.id}: ${err?.message || err}`, { taskId: task.id });
+ });
+
const isTui = isTuiProvider(provider);
// Build the agent prompt. `provider.type` drives the light-vs-full split
diff --git a/server/services/voice/tools.js b/server/services/voice/tools.js
index 468f6a986a..650cdf44ed 100644
--- a/server/services/voice/tools.js
+++ b/server/services/voice/tools.js
@@ -24,6 +24,7 @@ import { MEDIA_TOOLS, MEDIA_INTENT_RE } from './tools/media.js';
import { PIPELINE_TOOLS, PIPELINE_INTENT_RE } from './tools/pipeline.js';
import { CODE_TOOLS, CODE_INTENT_RE } from './tools/code.js';
import { CATALOG_TOOLS, CATALOG_INTENT_RE, catalogTypeEnum, matchesCustomCatalogNoun } from './tools/catalog.js';
+import { WORKSPACE_TOOLS, WORKSPACE_INTENT_RE } from './tools/workspace.js';
import { UI_KINDS } from './tools/shared.js';
// Re-exported for pipeline.js (UI_KINDS, UI_INTENT_RE) and the form-fill
@@ -48,6 +49,7 @@ const TOOLS = [
...PIPELINE_TOOLS,
...CODE_TOOLS,
...CATALOG_TOOLS,
+ ...WORKSPACE_TOOLS,
];
// Per-turn tool filtering. Small models (qwen3-4b, granite, etc.) choke when
@@ -94,6 +96,7 @@ const TOOL_GROUPS = {
dispatch_code_agent: 'code',
code_agent_status: 'code',
catalog_lookup: 'catalog',
+ workspace_switch: 'workspace',
// UNGROUPED = always-on: time_now, daily_log_append, ui_navigate.
// brain_capture used to be always-on, but that caused form-fill turns
// ("fill description with X") to be misrouted to brain_capture because
@@ -123,6 +126,7 @@ const GROUP_INTENT = {
code: CODE_INTENT_RE,
ui: UI_INTENT_RE,
catalog: CATALOG_INTENT_RE,
+ workspace: WORKSPACE_INTENT_RE,
};
// Fail-fast at import time: any group referenced in TOOL_GROUPS that has no
diff --git a/server/services/voice/tools/workspace.js b/server/services/voice/tools/workspace.js
new file mode 100644
index 0000000000..04d4cf55b0
--- /dev/null
+++ b/server/services/voice/tools/workspace.js
@@ -0,0 +1,74 @@
+// Workspace-context voice/palette tool (#2035): switch the active project
+// workspace — snapshot the workspace you're leaving, then reconcile the named
+// project's saved context (git branch, in-repo shell sessions, scoped tasks).
+// Reuses the workspaceContext service the Workspace Contexts page already
+// drives (snapshotOnRepoSwitch + restoreContext); it never checks out branches
+// or spawns shells — that stays a manual user action.
+
+// Workspace/project switching intent — "switch workspace to X", "switch to the
+// X project", "restore my BookLoom context", "take me back to PortOS project".
+// The workspace/project(-context) token is required within ~40 chars so a plain
+// "switch to the tasks page" (a ui_navigate turn) does NOT match.
+export const WORKSPACE_INTENT_RE = /\b(?:switch|change|move|jump|flip|go|take me|get me|back)\b[^.!?\n]{0,40}\b(?:workspace|project(?:\s+context)?)\b|\brestore\b[^.!?\n]{0,40}\b(?:workspace|context)\b|\bworkspace\s+context\b/i;
+
+export const WORKSPACE_TOOLS = [
+ {
+ name: 'workspace_switch',
+ description:
+ 'Switch your active project workspace: first save a snapshot of the workspace you are leaving, then restore the named project\'s saved context — its git branch, the shell sessions rooted in its repo, and the tasks scoped to it. Use when the user says "switch workspace to BookLoom", "switch to the finance tracker project", "take me back to PortOS", or "restore my BookLoom context". Restoring only REPORTS which saved shell sessions are still live to re-attach and whether the saved git branch is still checked out — it never checks out branches or spawns shells for the user (that stays a manual action). Name the target project as `workspace`.',
+ parameters: {
+ type: 'object',
+ properties: {
+ workspace: {
+ type: 'string',
+ description: 'The project/app to switch to ("BookLoom", "finance tracker", "PortOS"). Server fuzzy-matches against the user\'s managed apps.',
+ },
+ },
+ required: ['workspace'],
+ },
+ execute: async ({ workspace } = {}) => {
+ const phrase = typeof workspace === 'string' ? workspace.trim() : '';
+ if (!phrase) {
+ return { ok: false, error: 'workspace is required', summary: "I didn't catch which workspace to switch to." };
+ }
+
+ const { getActiveApps } = await import('../../apps.js');
+ const { resolveAppByPhrase } = await import('../../../lib/appResolver.js');
+ const { snapshotOnRepoSwitch, restoreContext } = await import('../../workspaceContext.js');
+
+ const apps = await getActiveApps().catch(() => []);
+ const match = resolveAppByPhrase(phrase, apps);
+ if (!match) {
+ const names = (apps || []).map((a) => a?.name).filter(Boolean);
+ const hint = names.length ? ` Try one of: ${names.slice(0, 4).join(', ')}.` : '';
+ return {
+ ok: false,
+ error: `unknown workspace "${phrase}"`,
+ summary: `I don't see a project called ${phrase}.${hint}`,
+ };
+ }
+
+ // Snapshot the workspace we're leaving (silent, no-op if none or same),
+ // then reconcile the target's saved context against what's live now.
+ // Both are defensive — a failure to snapshot must not block the switch.
+ const snapshot = await snapshotOnRepoSwitch(match.id).catch(() => null);
+ const restore = await restoreContext(match.id).catch(() => null);
+
+ const reattach = restore?.restorable?.shellSessions?.length || 0;
+ const hadSaved = !!restore?.saved;
+ const savedNote = snapshot?.appId ? ` Saved your ${snapshot.appId} context first.` : '';
+ const restoreNote = hadSaved
+ ? ` Restored ${reattach} live shell session${reattach === 1 ? '' : 's'}.`
+ : ' No saved context there yet, so nothing to restore.';
+
+ return {
+ ok: true,
+ workspace: match.id,
+ workspaceName: match.name || match.id,
+ snapshotted: snapshot?.appId || null,
+ reattachable: reattach,
+ summary: `Switched to ${match.name || match.id}.${savedNote}${restoreNote}`,
+ };
+ },
+ },
+];
diff --git a/server/services/workspaceContext.js b/server/services/workspaceContext.js
index 1b1ad6239d..0478d88c10 100644
--- a/server/services/workspaceContext.js
+++ b/server/services/workspaceContext.js
@@ -276,5 +276,52 @@ export async function listContexts() {
});
}
+// In-memory tracker of the app id CoS (or the user, via workspace_switch) most
+// recently began working in — the single "current workspace" notion in this
+// single-user install. Intentionally NOT persisted: it models "where work is
+// happening right now," which resets on restart, not durable state.
+let currentWorkspaceAppId = null;
+
+/**
+ * Auto-snapshot hook for workspace/repo switches (#2035). When work moves to a
+ * DIFFERENT app/repo than the one we were last in — a CoS coding-agent dispatch,
+ * or a user `workspace_switch` — save a silent snapshot of the previous
+ * ("current") app's workspace context first, so it can later be restored.
+ *
+ * Snapshot-only: it NEVER restores (restoring stays an explicit user action) and
+ * makes NO LLM calls. Defensive by design — a missing/absent current workspace
+ * (first switch) or a switch to the same repo is a no-op, not a throw; a failed
+ * save is swallowed so it can't break the caller's dispatch/switch.
+ *
+ * @param {string|null} nextAppId - target app id (null ⇒ PortOS self)
+ * @returns {Promise<object|null>} the saved snapshot record, or null when nothing
+ * was snapshotted (no prior workspace, same repo, or save failed).
+ */
+export async function snapshotOnRepoSwitch(nextAppId) {
+ const target = nextAppId || PORTOS_APP_ID;
+ const previous = currentWorkspaceAppId;
+ currentWorkspaceAppId = target;
+ // First switch (no prior workspace) or same repo ⇒ nothing to snapshot.
+ if (!previous || previous === target) return null;
+ const saved = await saveContext(previous).catch((err) => {
+ console.warn(`⚠️ Workspace auto-snapshot for ${previous} failed: ${err?.message || err}`);
+ return null;
+ });
+ if (saved) {
+ console.log(`🗂️ Auto-snapshotted workspace context for ${previous} (switched to ${target})`);
+ }
+ return saved;
+}
+
+/** Read the current in-memory workspace tracker (exported for tests). */
+export function getCurrentWorkspaceAppId() {
+ return currentWorkspaceAppId;
+}
+
+/** Reset the in-memory workspace tracker — exported for unit tests. */
+export function __resetWorkspaceTracker() {
+ currentWorkspaceAppId = null;
+}
+
// Exported for unit tests — pure helpers with no I/O.
export const __test = { tasksForApp, shellSessionsForRepo };
diff --git a/server/services/workspaceContext.test.js b/server/services/workspaceContext.test.js
index 9fdd3a1d00..b8570f75d4 100644
--- a/server/services/workspaceContext.test.js
+++ b/server/services/workspaceContext.test.js
@@ -212,3 +212,37 @@ describe('listContexts', () => {
expect(portos.savedAt).toBeNull();
});
});
+
+describe('snapshotOnRepoSwitch (#2035 auto-save hook)', () => {
+ beforeEach(() => wc.__resetWorkspaceTracker());
+
+ it('is a no-op on the first switch (no prior workspace to snapshot)', async () => {
+ const saved = await wc.snapshotOnRepoSwitch('app-1');
+ expect(saved).toBeNull();
+ expect(await wc.getSavedContext('app-1')).toBeNull();
+ expect(wc.getCurrentWorkspaceAppId()).toBe('app-1');
+ });
+
+ it('snapshots the previous ("current") workspace when switching to a different repo', async () => {
+ await wc.snapshotOnRepoSwitch('app-1'); // no-op, sets current = app-1
+ const saved = await wc.snapshotOnRepoSwitch('portos-default'); // snapshots app-1
+ expect(saved).toBeTruthy();
+ expect(saved.appId).toBe('app-1');
+ expect(await wc.getSavedContext('app-1')).toBeTruthy();
+ expect(wc.getCurrentWorkspaceAppId()).toBe('portos-default');
+ });
+
+ it('does NOT snapshot when the target repo is unchanged', async () => {
+ await wc.snapshotOnRepoSwitch('app-1');
+ const saved = await wc.snapshotOnRepoSwitch('app-1');
+ expect(saved).toBeNull();
+ expect(await wc.getSavedContext('app-1')).toBeNull();
+ });
+
+ it('normalizes a null target to the PortOS app (CoS self dispatch)', async () => {
+ await wc.snapshotOnRepoSwitch('app-1');
+ const saved = await wc.snapshotOnRepoSwitch(null); // → portos-default, snapshots app-1
+ expect(saved?.appId).toBe('app-1');
+ expect(wc.getCurrentWorkspaceAppId()).toBe('portos-default');
+ });
+});