Skip to content

Self-improving AI Employees for everyone

feat(home): delete an employee from the sidebar

trohitg950f659b4f20
diff --git a/CLAUDE.md b/CLAUDE.md
index 838ea3ae..ab1dab69 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -13,7 +13,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[UI Migration Plan](./docs-internal/ARCHIVE/ui_migration_plan.md)** | *Archived.* antd → shadcn/ui migration completion log (Waves 1–10). Current state lives in [Frontend Architecture](./docs-internal/frontend_architecture.md) and [Theme System](./docs-internal/theme_system.md). |
| **[Temporal Cleanup & Resilience Plan (Waves 15-18)](./docs-internal/ARCHIVE/TEMPORAL_CLEANUP_AND_RESILIENCE_PLAN.md)** | *Archived — all four waves shipped.* 15 dead-code retirement (Redis-Streams branch in event_waiter, APScheduler cron stack, orphaned `connection_status` factory), 16 per-queue task routing (`TemporalWorkerPool`), 17 resilience hardening (cron `catchup_window`, SDK interceptors, `DEPLOYMENT_MODE`, periodic heartbeats; the one-shot LLM-step retry it records was later reverted to unlimited-with-backoff), 18 worker performance tuning. Current settings live in [Temporal Architecture](./docs-internal/TEMPORAL_ARCHITECTURE.md). |
| **[Node Allowlist](./docs-internal/node_allowlist.md)** | Single-config UI visibility — `server/config/node_allowlist.json` controls which nodes / credential categories / skill folders show in the UI. Five lists with two enforcement tiers (mode-gated allowlist + absolute blocklist). `useNodeAllowlist` hook exposes `isVisible` / `isBlocked` / `isAllowed` / `isCredentialCategoryDisabled` / `isSkillFolderDisabled`. Adding a new disabled domain = single JSON edit, no code change. |
-| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (only their name above the conversation; Pause is in the Workspace header), the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written only through `services/chat_thread.py`; the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |
+| **[Normal Mode (Home)](./docs-internal/normal_mode.md)** | The owner-facing landing screen: describe a job, an LLM on the server drafts a setup screen (a JSON UI spec the client parses, normalises and renders from a fixed catalogue), and Hire builds, validates, saves and starts one workflow per AI employee (`services/employees/`, graph built from `config/employee_apps.json` plus the owner's skill library and a Canvas node, and checked against `node_allowlist.json` `enabled_nodes`). Covers the screen switch (`app/`, `shellMode` / `ui_shell_mode`, `VITE_NORMAL_MODE=false` kill switch, Home shows light/dark only), the employee page (only their name above the conversation; Pause is in the Workspace header), deleting an employee from the team sidebar (stopped through Reset first, then gone from every tab), the `approvalGate` "ask me before sending" step, run records for "done today" (`machina-run-record-v1`), automatic-pause reasons, Settings (Profile fields; usage-only Billing via `get_employee_usage`; Skills, the user-skills library each new hire copies onto a Skills node; consumer Connectors with `publisher` / `verified`; Plugins, the starter bundles in `hire/starters.json`; the last three share one catalog page), the Workspace dock (an employee's Canvas board, named by the summary's `canvas_node_id`; a live Browser tab with user takeover, shared with Dev mode; Mobile shows the managed local Android phone), the "Web browser" app (read-only under "ask me first" through the tool's `ask_first_params`; while the agent waits in `request_user` the summary's `browser_request` shows Needs you and Help in browser), Talk on the employee page (a thread over the chat session whose id is the workflow id, rows written only through `services/chat_thread.py`; the talk line is chatTrigger → an agent → `chatReply` "Reply in Chat": a chat hire's own agent is its talk agent, other hires get a "Talk with {name}" agent sharing the worker's tools and skills with its own Context, and schedule hires also "Post to Talk"), Turn on Talk (for talk `off`) and Apply (while the summary's `pending_changes` is true) via `enable_employee_talk` / `apply_employee_changes`, each a restart on the saved graph through `services/deployment/restart.py`, self-extension from Talk through the Agent Builder within the Hire rule (`services/employees/policy.py`), the 3D orb, the wire contract and the `employee_lifecycle` / `approval_lifecycle` / `chat.updated` broadcasts. |
| **[Theme System](./docs-internal/theme_system.md)** | 12-way visual theme system — 2 base (light, dark) + 5 utopian (renaissance, greek, edo, steampunk, atomic) + 5 dystopian (cyber, wasteland, rot, plague, surveillance) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), per-theme `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, decorative-layer wrappers (`.app-frame` / `.canvas-host` / `.modal-frame`), per-component decorative ornaments (panel textures + canvas decorations + node pseudo-element overlays + theme-specific keyframes), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent (Cyber neon cyan, Surveillance REC red, Renaissance ultramarine, etc.), **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `AppShell` on both screens, while the tab is hidden or the window is blurred; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyph system** (290 inline SVG glyph strings across 29 keys × 10 themes via [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts) + theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **decorative HTML primitives** (`<SvgFilterDefs>` mounting `#ink-blot` / `#noise` / `#crt` filter IDs at app root, `<DropCap>` wrapper for Renaissance ornament rule), **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), **per-theme scrollbar webkit rules** in all 12 themes, 9-event WebAudio sound system (10 packs via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
| **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), 12-theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 12 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |
| **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |
@@ -2760,6 +2760,7 @@ This function:
- **Claude Code budget flag**: the Claude Code agent (`nodes/agent/claude_code_agent/`) does not pass `--max-budget-usd`. It, `--max-turns` and `--fallback-model` are print-mode (`-p`) flags, and the session pool runs `claude` interactively over stream-json, so `_provider.py` accepts the task spec's `max_budget_usd` and ignores it; `tests/services/cli_agent/test_providers.py` asserts the flag is absent.
- **Persisted-prefix cache contract**: `PersistQueryClientProvider` hydrates entries with the QueryClient's *default* options, so any prefix in `PERSISTED_KEY_PREFIXES` (`client/src/lib/queryPersist.ts`) MUST also have a matching `queryClient.setQueryDefaults(['<prefix>'], { staleTime: FOREVER, gcTime: FOREVER })` declaration in `client/src/lib/queryClient.ts`. Per-call options don't apply on hydration. Canonical persisted set: `nodeSpec`, `nodeGroups`. `skillContent` and `credentialValues` carry FOREVER `setQueryDefaults` for the in-memory cache but are deliberately NOT persisted; `credentialValues` was previously persisted here but was removed per OWASP HTML5 Security Cheat Sheet / ASVS V9.9 — decrypted API keys must never live in `localStorage`. The in-memory TanStack Query cache (`gcTime: ∞`) keeps the credentials form populated for the session lifetime; on reload the panel refetches via WS. `credentialCatalogue` has its own `idb-keyval` warm-start path so it is intentionally not in either list.
- **WebSocket `sendRequest` replay queue**: when the socket is not open, requests enqueue with `AbortController`-backed per-request timeouts (default 30s) and replay on reconnect inside `ws.onopen` before `setIsReady(true)`. Queue capped at 200 with FIFO eviction. Any close rejects requests already sent (their outcome is unknown, so they are never replayed) and keeps queued ones under their original deadline; only `disposeConnection` (logout or unmount) closes with code 1000 and drops the queue. Implementation in `client/src/contexts/WebSocketContext.tsx` (`pendingSendQueueRef`, `drainPendingSends`, `disposeConnection`).
+- **Deleting a workflow stops it first, and nothing writes it back**: the REST `DELETE /api/database/workflows/{id}` and the `delete_workflow` WS command share `delete_workflow_with_context_archival` (`services/workflow_storage/handlers.py`), which first calls `stop_workflow_for_deletion` (`services/workflow_storage/deletion.py`): a generation that is live, paused, failed or still resetting, or an existing Workspace controller, goes through Reset (`handle_reset_workflow` with the latest control revision), and a legacy local deployment is cancelled. A failed shutdown, or a Start admitted meanwhile, refuses the delete with `workflow_shutdown_failed` (reason in `detail`) and keeps the graph; a hire that never ran is deleted without connecting to Temporal. Every save of an existing workflow passes `save_workflow(..., require_existing=True)` (an UPDATE whose row count is checked in the same transaction as the Context archive intents), so an editor save, read-time normalization or Vertex cloud-tool minting that lands after the delete fails with `workflow_not_found` instead of re-inserting the graph. Client: `useAppStore.deleteWorkflow` deletes, then `forgetWorkflow` (also run by the `workflow.deleted` case in `WebSocketContext.tsx`, so it applies while Home is unmounted) cancels in-flight list and detail reads, prunes the workflow and employee caches (`features/home/data/employeeCache.ts::removeEmployee`) and clears only matching editor, Home and Workspace state. Nothing creates an Untitled replacement, and the Dev editor no longer creates one when no workflow exists. Employee lifecycle events and the hire, Turn on Talk and Apply responses refresh the employee queries (`refreshEmployee`) instead of merging their summaries, so a late payload cannot bring a deleted employee back. Locked by `tests/services/test_workflow_deletion_shutdown.py`, `tests/services/test_workflow_context_archive_outbox.py`, `client/src/store/__tests__/deleteWorkflow.test.ts` and `features/home/__tests__/homeSidebar.test.tsx`.
- **`currentWorkflowId` single source**: lives in `useAppStore.currentWorkflow.id` only. Non-React listeners (WS handlers) read via `useAppStore.getState().currentWorkflow?.id` -- the documented Zustand escape hatch. The push to `nodeStatusStore.setCurrentWorkflowId` is driven from one `useEffect` in `Dashboard.tsx`. Removed the prior `currentWorkflowIdRef` mirror inside WebSocketContext that misrouted broadcasts during workflow switches.
- **Execution correlation IDs**: `handle_execute_node` issues a `uuid4().hex` token at request entry, propagates it through every `node_status` / `node_output` broadcast for the run, and returns it in the response payload as `execution_id`. Frontend `ExecutionResult.executionId` carries it; `OutputSection` dedups runs by it instead of `JSON.stringify(outputs)` (which collapsed distinct executions whose payloads matched). Same trace-id pattern as OpenTelemetry / HTTP request ids.
- **`clear_node_status` idle reset**: `StatusBroadcaster.clear_node_status(node_id)` resets the slot to `{status: "idle", data: {}, cleared: true}` instead of `del`'ing it. Deleting created a race window where the in-flight execution's `success` broadcast re-created the entry and stuck the UI on "completed" for a cancelled node. Idle reset preserves entry identity so subsequent broadcasts update normally; the `cleared: true` flag distinguishes "never ran" from "explicitly cleared."
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 2c54783d..b1018b57 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -43,9 +43,8 @@ import CommandPaletteHost from './components/ui/CommandPaletteHost';
import { withSound } from './hooks/useSound';
import { useAppTheme } from './hooks/useAppTheme';
import { useWorkflowManagement } from './hooks/useWorkflowManagement';
-import { useWorkflowsQuery, WORKFLOWS_QUERY_KEY } from './hooks/useWorkflowsQuery';
-import { useQueryClient } from '@tanstack/react-query';
-import { workflowApi } from './services/workflowApi';
+import { useWorkflowsQuery, workflowsQueryOptions } from './hooks/useWorkflowsQuery';
+import { isCancelledError, useQueryClient } from '@tanstack/react-query';
import { useDragAndDrop } from './hooks/useDragAndDrop';
import { useComponentPalette } from './hooks/useComponentPalette';
import { useReactFlowNodes } from './hooks/useReactFlowNodes';
@@ -165,7 +164,6 @@ const DashboardContent: React.FC = () => {
const sidebarVisible = useAppStore((s) => s.sidebarVisible);
const componentPaletteVisible = useAppStore((s) => s.componentPaletteVisible);
const loadWorkflow = useAppStore((s) => s.loadWorkflow);
- const createNewWorkflow = useAppStore((s) => s.createNewWorkflow);
const deleteWorkflow = useAppStore((s) => s.deleteWorkflow);
const migrateCurrentWorkflow = useAppStore((s) => s.migrateCurrentWorkflow);
const toggleSidebar = useAppStore((s) => s.toggleSidebar);
@@ -946,7 +944,8 @@ const DashboardContent: React.FC = () => {
};
fileInput.click();
};
- // Load saved workflows on mount and auto-select most recent or create new if none exist
+ // Select an existing workflow on mount. Only an explicit New/Hire action
+ // creates a saved workflow; opening an empty editor must not add an employee.
const hasMigrated = React.useRef(false);
const hasInitialized = React.useRef(false);
useEffect(() => {
@@ -958,44 +957,32 @@ const DashboardContent: React.FC = () => {
currentWorkflowId: currentWorkflow?.id,
});
- const fetchWorkflowsList = () => queryClient.fetchQuery({
- queryKey: WORKFLOWS_QUERY_KEY,
- queryFn: async () => {
- const summaries = await workflowApi.getAllWorkflows();
- return summaries.map(w => ({
- id: w.id,
- name: w.name,
- nodeCount: w.nodeCount,
- createdAt: new Date(w.createdAt),
- lastModified: new Date(w.lastModified),
- }));
- },
- });
+ const fetchWorkflowsList = () => queryClient.fetchQuery(workflowsQueryOptions());
+ const reportInitializationError = (error: unknown) => {
+ // Confirmed deletion deliberately cancels stale list/detail requests.
+ if (!isCancelledError(error)) console.error('Failed to initialize workflows:', error);
+ };
const initWorkflows = async () => {
const list = await fetchWorkflowsList();
+ if (useAppStore.getState().currentWorkflow) return;
if (list.length > 0) {
const mostRecent = [...list].sort(
(a, b) => b.lastModified.getTime() - a.lastModified.getTime()
)[0];
await loadWorkflow(mostRecent.id);
}
- const state = useAppStore.getState();
- if (!state.currentWorkflow) {
- console.log('[Dashboard] No saved workflows found, creating new one');
- createNewWorkflow();
- }
};
if (!currentWorkflow) {
- initWorkflows();
+ void initWorkflows().catch(reportInitializationError);
} else if (!hasMigrated.current) {
console.log('[Dashboard] Migrating current workflow');
- migrateCurrentWorkflow();
+ void migrateCurrentWorkflow().catch(reportInitializationError);
hasMigrated.current = true;
- void fetchWorkflowsList(); // seed sidebar list cache
+ void fetchWorkflowsList().catch(reportInitializationError); // seed sidebar list cache
}
- }, [queryClient, currentWorkflow, loadWorkflow, createNewWorkflow, migrateCurrentWorkflow]);
+ }, [queryClient, currentWorkflow, loadWorkflow, migrateCurrentWorkflow]);
// Track previous workflow ID for viewport save/restore (n8n pattern)
const prevWorkflowIdRef = React.useRef<string | null>(null);
@@ -1246,7 +1233,9 @@ const DashboardContent: React.FC = () => {
workflows={savedWorkflows}
currentWorkflowId={currentWorkflow?.id}
onSelectWorkflow={handleSelectWorkflow}
- onDeleteWorkflow={deleteWorkflow}
+ onDeleteWorkflow={async (id) => {
+ if (!(await deleteWorkflow(id))) toast.error('Could not delete the workflow. Try again.');
+ }}
/>
)}
</div>
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 70dd0520..84cf6d73 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -1146,7 +1146,9 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
edge_count?: number;
}>;
const eventType = event?.type ?? '';
- if (['.imported', '.renamed', '.created', '.deleted'].some((stage) => eventType.endsWith(stage))) {
+ if (eventType.endsWith('.deleted') && event.subject) {
+ useAppStore.getState().forgetWorkflow(event.subject);
+ } else if (['.imported', '.renamed', '.created'].some((stage) => eventType.endsWith(stage))) {
void queryClient.invalidateQueries({ queryKey: WORKFLOWS_QUERY_KEY });
}
// Normal mode's team list follows the same lifecycle.
diff --git a/client/src/contexts/__tests__/webSocketActions.test.tsx b/client/src/contexts/__tests__/webSocketActions.test.tsx
index 1f4680ac..6e1dc0cd 100644
--- a/client/src/contexts/__tests__/webSocketActions.test.tsx
+++ b/client/src/contexts/__tests__/webSocketActions.test.tsx
@@ -62,6 +62,9 @@ import { queryClient } from '../../lib/queryClient';
import { queryKeys } from '../../lib/queryConfig';
import { useAppStore, type WorkflowData } from '../../store/useAppStore';
import { useWorkflowControlStore } from '../../stores/workflowControlStore';
+import { EMPLOYEES_QUERY_KEY } from '../../features/home/data/employeeCache';
+import { useHomeStore } from '../../features/home/state/homeStore';
+import { WORKFLOWS_QUERY_KEY } from '../../hooks/useWorkflowsQuery';
function broadcast(message: Record<string, unknown>): void {
act(() => {
@@ -113,6 +116,27 @@ describe('WebSocket actions for Normal mode', () => {
vi.restoreAllMocks();
});
+ it('removes a remotely deleted employee while Home is unmounted', () => {
+ const id = 'remote-deleted-employee';
+ const workflow: WorkflowData = {
+ id, name: 'Maya', slug: 'maya', nodes: [], edges: [],
+ createdAt: new Date(0), lastModified: new Date(0),
+ };
+ useAppStore.setState({ currentWorkflow: workflow, hasUnsavedChanges: true, shellMode: 'dev' });
+ useHomeStore.getState().showEmployee(id);
+ queryClient.setQueryData(WORKFLOWS_QUERY_KEY, [workflow]);
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [{ workflow_id: id }]);
+ const { unmount } = mount();
+ broadcast({ type: 'workflow_lifecycle', data: { specversion: '1.0', type: 'com.opencompany.workflow.deleted', subject: id } });
+ expect(useAppStore.getState().currentWorkflow).toBeNull();
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(false);
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ expect(queryClient.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);
+ expect(queryClient.getQueryData(WORKFLOWS_QUERY_KEY)).toEqual([]);
+ unmount();
+ queryClient.clear();
+ });
+
it('keeps the actions context stable while the main value churns', () => {
const actions: WebSocketActions[] = [];
const values: unknown[] = [];
diff --git a/client/src/features/home/__tests__/employeeView.test.tsx b/client/src/features/home/__tests__/employeeView.test.tsx
index fb9f5980..2e8100e8 100644
--- a/client/src/features/home/__tests__/employeeView.test.tsx
+++ b/client/src/features/home/__tests__/employeeView.test.tsx
@@ -52,6 +52,16 @@ function summary(patch: Record<string, unknown>, control: Record<string, unknown
}
function renderPage(employee: EmployeeSummary, onConnect = vi.fn()) {
+ const sendOtherRequest = actions.sendRequest.getMockImplementation();
+ actions.sendRequest.mockImplementation(async (type: string, data?: Record<string, unknown>) => {
+ if (type === 'list_employees') return { success: true, employees: [employee] };
+ if (type === 'get_employee') {
+ return data?.workflow_id === employee.workflow_id
+ ? { success: true, employee }
+ : { success: false, error: 'not_found' };
+ }
+ return sendOtherRequest?.(type, data);
+ });
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
client.setQueryData(EMPLOYEES_QUERY_KEY, [employee]);
render(
diff --git a/client/src/features/home/__tests__/employeesCache.test.ts b/client/src/features/home/__tests__/employeesCache.test.ts
index 3e86b5de..07e3104f 100644
--- a/client/src/features/home/__tests__/employeesCache.test.ts
+++ b/client/src/features/home/__tests__/employeesCache.test.ts
@@ -1,19 +1,20 @@
/**
- * Keeping the team current from broadcasts: duplicates are dropped by
- * (source, id), a late broadcast never rolls a row back, removals delete,
- * and workflow changes refetch the list.
+ * Lifecycle events refresh authoritative server queries; their payloads
+ * never overwrite rows. Confirmed deletion prunes caches and navigation.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { QueryClient } from '@tanstack/react-query';
+import { QueryClient, QueryObserver } from '@tanstack/react-query';
import {
EMPLOYEES_QUERY_KEY,
applyEmployeeLifecycle,
applyWorkflowLifecycle,
employeeDetailKey,
+ removeEmployee,
resetSeenEmployeeEvents,
} from '../data/employees';
import type { EmployeeSummary } from '../data/schemas';
+import { useHomeStore } from '../state/homeStore';
function summary(id: string, revision: number, name = id): Record<string, unknown> {
return { workflow_id: id, name, revision, control: {} };
@@ -37,33 +38,56 @@ const names = () => client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?
beforeEach(() => {
vi.useFakeTimers();
resetSeenEmployeeEvents();
+ useHomeStore.setState({ view: { kind: 'hire' }, workspaceFor: null, hireNotice: null, glow: null });
client = new QueryClient();
client.setQueryData(EMPLOYEES_QUERY_KEY, [summary('a', 5), summary('b', 5)].map((raw) => ({ ...raw, apps: [], missing_apps: [] })));
});
afterEach(() => {
+ vi.clearAllTimers();
vi.useRealTimers();
client.clear();
+ vi.restoreAllMocks();
});
describe('applyEmployeeLifecycle', () => {
- it('puts a hire first and updates in place', () => {
+ it('coalesces hire/update signals into a server list refresh without merging their summaries', async () => {
+ const backendRows = [summary('c', 4), summary('a', 5), summary('b', 8)] as unknown as EmployeeSummary[];
+ const fetch = vi.fn(async () => backendRows);
+ const list = new QueryObserver(client, { queryKey: EMPLOYEES_QUERY_KEY, queryFn: fetch, staleTime: Infinity });
+ const unsubscribe = list.subscribe(() => {});
applyEmployeeLifecycle(client, event('hired', summary('c', 1)));
applyEmployeeLifecycle(client, event('updated', summary('b', 6)));
- expect(names()).toEqual(['c@1', 'a@5', 'b@6']);
+ expect(names()).toEqual(['a@5', 'b@5']);
+ expect(fetch).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(300);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(names()).toEqual(['c@4', 'a@5', 'b@8']);
+ unsubscribe();
});
- it('keeps the newer row when an older broadcast arrives late', () => {
+ it('invalidates the affected detail without replacing it with a late summary', () => {
+ client.setQueryData(employeeDetailKey('a'), { workflow_id: 'a', revision: 12, job: 'Current database job' });
+ client.setQueryData(employeeDetailKey('b'), { workflow_id: 'b', revision: 5 });
applyEmployeeLifecycle(client, event('updated', summary('a', 9)));
applyEmployeeLifecycle(client, event('updated', summary('a', 7)));
- expect(names()).toEqual(['a@9', 'b@5']);
+ expect(client.getQueryData(employeeDetailKey('a'))).toMatchObject({ revision: 12, job: 'Current database job' });
+ expect(client.getQueryState(employeeDetailKey('a'))?.isInvalidated).toBe(true);
+ expect(client.getQueryState(employeeDetailKey('b'))?.isInvalidated).toBe(false);
+ vi.advanceTimersByTime(300);
+ expect(client.getQueryState(employeeDetailKey('b'))?.isInvalidated).toBe(false);
});
it('drops a duplicate delivery of the same event', () => {
+ const invalidate = vi.spyOn(client, 'invalidateQueries');
const once = event('hired', summary('d', 1), 'same-id');
applyEmployeeLifecycle(client, once);
applyEmployeeLifecycle(client, { ...once });
- expect(names()?.filter((n) => n.startsWith('d'))).toHaveLength(1);
+ expect(invalidate).toHaveBeenCalledTimes(1);
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: employeeDetailKey('d'), exact: true });
+ vi.advanceTimersByTime(300);
+ expect(invalidate).toHaveBeenCalledTimes(2);
+ expect(names()).toEqual(['a@5', 'b@5']);
});
it('removes a fired employee and their detail', () => {
@@ -73,16 +97,94 @@ describe('applyEmployeeLifecycle', () => {
expect(client.getQueryData(employeeDetailKey('a'))).toBeUndefined();
});
+ it('reads the database after delayed summaries and never recreates a removed employee from their payloads', async () => {
+ const fetch = vi.fn(async () => [summary('b', 5)] as unknown as EmployeeSummary[]);
+ const list = new QueryObserver(client, { queryKey: EMPLOYEES_QUERY_KEY, queryFn: fetch, staleTime: Infinity });
+ const unsubscribe = list.subscribe(() => {});
+ applyEmployeeLifecycle(client, event('removed', summary('a', 10)));
+ applyEmployeeLifecycle(client, event('updated', summary('a', 9)));
+ applyEmployeeLifecycle(client, event('hired', summary('a', 1)));
+ expect(names()).toEqual(['b@5']);
+ await vi.advanceTimersByTimeAsync(300);
+ expect(fetch).toHaveBeenCalled();
+ expect(names()).toEqual(['b@5']);
+ expect(client.getQueryData(employeeDetailKey('a'))).toBeUndefined();
+ unsubscribe();
+ });
+
it('refetches when the broadcast carries no usable summary, and ignores non-CloudEvents', () => {
const invalidate = vi.spyOn(client, 'invalidateQueries');
applyEmployeeLifecycle(client, { ...event('updated', summary('a', 11)), data: { workflow_id: 'a' } });
vi.advanceTimersByTime(400);
- expect(invalidate).toHaveBeenCalledWith({ queryKey: EMPLOYEES_QUERY_KEY });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: EMPLOYEES_QUERY_KEY, exact: true });
+ invalidate.mockClear();
applyEmployeeLifecycle(client, { ...event('updated', summary('a', 12)), specversion: '0.3' });
+ vi.advanceTimersByTime(300);
+ expect(invalidate).not.toHaveBeenCalled();
expect(names()).toEqual(['a@5', 'b@5']);
});
});
+describe('removeEmployee', () => {
+ it('clears navigation and one-shot state belonging to the deleted employee', () => {
+ useHomeStore.setState({
+ view: { kind: 'employee', workflowId: 'a' },
+ workspaceFor: 'a',
+ hireNotice: { workflowId: 'a', name: 'Maya', warnings: ['Missing app'] },
+ glow: { workflowId: 'a', nonce: 1 },
+ });
+ removeEmployee(client, 'a');
+ expect(names()).toEqual(['b@5']);
+ expect(useHomeStore.getState()).toMatchObject({ view: { kind: 'hire' }, workspaceFor: null, hireNotice: null, glow: null });
+ });
+
+ it('preserves another employee’s page, workspace and notices', () => {
+ const state = {
+ view: { kind: 'employee' as const, workflowId: 'b' },
+ workspaceFor: 'b',
+ hireNotice: { workflowId: 'b', name: 'Theo', warnings: ['Missing app'] },
+ glow: { workflowId: 'b', nonce: 2 },
+ };
+ useHomeStore.setState(state);
+ removeEmployee(client, 'a');
+ expect(useHomeStore.getState()).toMatchObject(state);
+ });
+
+ it('cancels stale list and detail responses so they cannot restore a deleted employee', async () => {
+ let resolveList!: (value: EmployeeSummary[]) => void;
+ let resolveDetail!: (value: { workflow_id: string }) => void;
+ let listSignal!: AbortSignal;
+ let detailSignal!: AbortSignal;
+ client.setQueryData(employeeDetailKey('a'), { workflow_id: 'a' });
+ const staleList = client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)!;
+ const listRequest = client.fetchQuery({
+ queryKey: EMPLOYEES_QUERY_KEY,
+ queryFn: ({ signal }) => {
+ listSignal = signal;
+ return new Promise<EmployeeSummary[]>((resolve) => { resolveList = resolve; });
+ },
+ staleTime: 0,
+ }).catch(() => undefined);
+ const detailRequest = client.fetchQuery({
+ queryKey: employeeDetailKey('a'),
+ queryFn: ({ signal }) => {
+ detailSignal = signal;
+ return new Promise<{ workflow_id: string }>((resolve) => { resolveDetail = resolve; });
+ },
+ staleTime: 0,
+ }).catch(() => undefined);
+ removeEmployee(client, 'a');
+ expect(listSignal.aborted).toBe(true);
+ expect(detailSignal.aborted).toBe(true);
+ resolveList(staleList);
+ resolveDetail({ workflow_id: 'a' });
+ await Promise.all([listRequest, detailRequest]);
+ expect(names()).toEqual(['b@5']);
+ expect(client.getQueryData(employeeDetailKey('a'))).toBeUndefined();
+ expect(client.getQueryState(EMPLOYEES_QUERY_KEY)?.isInvalidated).toBe(true);
+ });
+});
+
describe('applyWorkflowLifecycle', () => {
it('removes a deleted workflow and refetches on created, renamed or imported', () => {
applyWorkflowLifecycle(client, { type: 'com.opencompany.workflow.deleted', subject: 'b' });
@@ -91,6 +193,8 @@ describe('applyWorkflowLifecycle', () => {
applyWorkflowLifecycle(client, { type: 'com.opencompany.workflow.created', subject: 'z' });
applyWorkflowLifecycle(client, { type: 'com.opencompany.workflow.renamed', subject: 'a' });
vi.advanceTimersByTime(400);
- expect(invalidate).toHaveBeenCalledTimes(1);
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: employeeDetailKey('z'), exact: true });
+ expect(invalidate).toHaveBeenCalledWith({ queryKey: employeeDetailKey('a'), exact: true });
+ expect(invalidate.mock.calls.filter(([filters]) => filters?.queryKey === EMPLOYEES_QUERY_KEY)).toHaveLength(1);
});
});
diff --git a/client/src/features/home/__tests__/employeesRemount.test.tsx b/client/src/features/home/__tests__/employeesRemount.test.tsx
new file mode 100644
index 00000000..5e145d0e
--- /dev/null
+++ b/client/src/features/home/__tests__/employeesRemount.test.tsx
@@ -0,0 +1,68 @@
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ isReady: true, sendRequest, addEventListener: () => () => {} }),
+}));
+
+import { EMPLOYEES_QUERY_KEY, employeeDetailKey, useEmployeeDetailQuery, useEmployeesQuery } from '../data/employees';
+import { parseEmployee, parseEmployeeDetail } from '../data/schemas';
+
+let client: QueryClient;
+
+function wrapper({ children }: { children: ReactNode }) {
+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
+}
+
+beforeEach(() => {
+ sendRequest.mockReset();
+ client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchOnMount: false } } });
+});
+
+afterEach(() => {
+ client.clear();
+});
+
+describe('returning to Home', () => {
+ it('replaces a warm employee list with database state when deletion broadcasts were missed in Dev', async () => {
+ let backendTeam = [
+ { workflow_id: 'a', name: 'Maya' },
+ { workflow_id: 'b', name: 'Theo' },
+ ];
+ client.setQueryData(EMPLOYEES_QUERY_KEY, backendTeam.map(parseEmployee));
+ sendRequest.mockImplementation(async () => ({ success: true, employees: backendTeam }));
+
+ const first = renderHook(() => useEmployeesQuery(), { wrapper });
+ await waitFor(() => expect(first.result.current.isFetching).toBe(false));
+ expect(sendRequest).toHaveBeenCalledTimes(1);
+ first.unmount();
+
+ backendTeam = backendTeam.filter((employee) => employee.workflow_id !== 'a');
+ const second = renderHook(() => useEmployeesQuery(), { wrapper });
+ await waitFor(() => expect(second.result.current.data?.map((employee) => employee.workflow_id)).toEqual(['b']));
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(sendRequest).toHaveBeenLastCalledWith('list_employees', {});
+ second.unmount();
+ });
+
+ it('rechecks a warm employee detail and clears it when the database reports deletion', async () => {
+ const employee = { workflow_id: 'a', name: 'Maya' };
+ client.setQueryData(employeeDetailKey('a'), parseEmployeeDetail(employee));
+ sendRequest.mockResolvedValueOnce({ success: true, employee }).mockResolvedValueOnce({ success: false, error: 'not_found' });
+
+ const first = renderHook(() => useEmployeeDetailQuery('a'), { wrapper });
+ await waitFor(() => expect(first.result.current.isFetching).toBe(false));
+ expect(first.result.current.data?.workflow_id).toBe('a');
+ first.unmount();
+
+ const second = renderHook(() => useEmployeeDetailQuery('a'), { wrapper });
+ await waitFor(() => expect(second.result.current.data).toBeNull());
+ expect(sendRequest).toHaveBeenCalledTimes(2);
+ expect(sendRequest).toHaveBeenLastCalledWith('get_employee', { workflow_id: 'a' });
+ second.unmount();
+ });
+});
diff --git a/client/src/features/home/__tests__/homeSidebar.test.tsx b/client/src/features/home/__tests__/homeSidebar.test.tsx
new file mode 100644
index 00000000..c92eca41
--- /dev/null
+++ b/client/src/features/home/__tests__/homeSidebar.test.tsx
@@ -0,0 +1,119 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
+import { QueryClientProvider } from '@tanstack/react-query';
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ isReady: false, sendRequest: vi.fn(), addEventListener: () => () => {} }),
+}));
+vi.mock('@/services/workflowApi', () => ({
+ workflowApi: { deleteWorkflow: vi.fn(), saveWorkflow: vi.fn(), getWorkflow: vi.fn(), getAllWorkflows: vi.fn() },
+}));
+vi.mock('@/components/brand/Logo', () => ({ OcLogo: () => null }));
+vi.mock('../data/profile', () => ({ useOwnerSettings: () => ({ data: { profile_full_name: 'Owner' } }) }));
+vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
+
+import { ThemeProvider } from '@/contexts/ThemeContext';
+import { queryClient } from '@/lib/queryClient';
+import { workflowApi } from '@/services/workflowApi';
+import { useAppStore } from '@/store/useAppStore';
+import { EMPLOYEES_QUERY_KEY } from '../data/employeeCache';
+import { parseEmployee } from '../data/schemas';
+import { HomeSidebar } from '../sidebar/HomeSidebar';
+import { useHomeStore } from '../state/homeStore';
+import { pillToast } from '../ui/pillToast';
+
+function mountSidebar() {
+ return render(
+ <ThemeProvider>
+ <QueryClientProvider client={queryClient}>
+ <HomeSidebar />
+ </QueryClientProvider>
+ </ThemeProvider>,
+ );
+}
+
+function confirmDelete() {
+ fireEvent.click(screen.getByRole('button', { name: 'Delete Maya' }));
+ const dialog = screen.getByRole('alertdialog', { name: 'Delete Maya?' });
+ fireEvent.click(within(dialog).getByRole('button', { name: 'Delete' }));
+ return dialog;
+}
+
+beforeEach(() => {
+ queryClient.clear();
+ vi.mocked(workflowApi.deleteWorkflow).mockReset().mockResolvedValue(true);
+ vi.mocked(workflowApi.saveWorkflow).mockReset();
+ vi.mocked(pillToast).mockClear();
+ useAppStore.setState({ currentWorkflow: null, hasUnsavedChanges: false, selectedNode: null, workflowUIStates: {} });
+ useHomeStore.setState({
+ sidebarOpen: true,
+ view: { kind: 'employee', workflowId: 'b' },
+ workspaceFor: 'b',
+ hireNotice: null,
+ glow: null,
+ });
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [
+ parseEmployee({ workflow_id: 'a', name: 'Maya', role: 'Receptionist' })!,
+ parseEmployee({ workflow_id: 'b', name: 'Theo', role: 'Researcher' })!,
+ ]);
+});
+
+afterEach(() => {
+ queryClient.clear();
+ vi.restoreAllMocks();
+});
+
+describe('HomeSidebar employee deletion', () => {
+ it('offers a separate delete button and cancellation never selects or deletes the employee', () => {
+ mountSidebar();
+ const button = screen.getByRole('button', { name: 'Delete Maya' });
+ expect(button.parentElement?.closest('button')).toBeNull();
+ fireEvent.click(button);
+ expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'b' });
+ fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Cancel' }));
+ expect(workflowApi.deleteWorkflow).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'Delete Maya' })).toBeInTheDocument();
+ expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'b' });
+ });
+
+ it('deletes the selected employee through the store and returns to hiring without creating a replacement', async () => {
+ useHomeStore.setState({ view: { kind: 'employee', workflowId: 'a' }, workspaceFor: 'a' });
+ mountSidebar();
+ confirmDelete();
+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Delete Maya' })).not.toBeInTheDocument());
+ expect(workflowApi.deleteWorkflow).toHaveBeenCalledWith('a');
+ expect(workflowApi.saveWorkflow).not.toHaveBeenCalled();
+ expect(useHomeStore.getState().view).toEqual({ kind: 'hire' });
+ expect(useHomeStore.getState().workspaceFor).toBeNull();
+ expect(screen.getByRole('button', { name: 'Delete Theo' })).toBeInTheDocument();
+ });
+
+ it('disables confirmation while pending and sends only one delete', async () => {
+ let finish!: (success: boolean) => void;
+ vi.mocked(workflowApi.deleteWorkflow).mockReturnValue(new Promise((resolve) => { finish = resolve; }));
+ mountSidebar();
+ const dialog = confirmDelete();
+ const pendingButton = within(dialog).getByRole('button', { name: 'Deleting…' });
+ expect(pendingButton).toBeDisabled();
+ expect(within(dialog).getByRole('button', { name: 'Cancel' })).toBeDisabled();
+ fireEvent.click(pendingButton);
+ expect(workflowApi.deleteWorkflow).toHaveBeenCalledTimes(1);
+ await act(async () => { finish(true); });
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument();
+ expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'b' });
+ });
+
+ it('keeps the employee and selection on failure, shows an error, and allows retry', async () => {
+ vi.mocked(workflowApi.deleteWorkflow).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ mountSidebar();
+ confirmDelete();
+ await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Couldn’t delete Maya. Try again.', { tone: 'error' }));
+ expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'b' });
+ expect(queryClient.getQueryData<Array<{ workflow_id: string }>>(EMPLOYEES_QUERY_KEY)?.map((employee) => employee.workflow_id)).toEqual(['a', 'b']);
+ fireEvent.click(within(screen.getByRole('alertdialog')).getByRole('button', { name: 'Delete' }));
+ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument());
+ expect(workflowApi.deleteWorkflow).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/client/src/features/home/__tests__/talk.test.tsx b/client/src/features/home/__tests__/talk.test.tsx
index ed4cc28b..36be91e7 100644
--- a/client/src/features/home/__tests__/talk.test.tsx
+++ b/client/src/features/home/__tests__/talk.test.tsx
@@ -23,7 +23,7 @@ vi.mock('../ui/pillToast', () => ({ pillToast: vi.fn() }));
import { WORKFLOW_CONTROL_REQUEST_TIMEOUT, normalizeWorkflowControlStatus } from '@/contexts/WebSocketContext';
import { useNodeStatusStore } from '@/stores/nodeStatusStore';
-import { EMPLOYEES_QUERY_KEY } from '../data/employees';
+import { EMPLOYEES_QUERY_KEY, employeeDetailKey, removeEmployee, useEmployeesQuery } from '../data/employees';
import { presentEmployee } from '../data/presentation';
import { parseEmployee, type EmployeeSummary } from '../data/schemas';
import {
@@ -63,11 +63,18 @@ function controlFor(summary: EmployeeSummary): EmployeeControl {
let server: { messages: Record<string, unknown>[]; send: Record<string, unknown> };
let client: QueryClient;
+function TeamSubscription() {
+ useEmployeesQuery();
+ return null;
+}
+
function renderTalk(summary: EmployeeSummary) {
client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
client.setQueryData(EMPLOYEES_QUERY_KEY, [summary]);
+ client.setQueryData(employeeDetailKey(summary.workflow_id), summary);
const view = (next: EmployeeSummary) => (
<QueryClientProvider client={client}>
+ <TeamSubscription />
<EmployeeTalk employee={next} control={controlFor(next)} />
</QueryClientProvider>
);
@@ -230,10 +237,13 @@ describe('Turn on Talk', () => {
it('confirms, mentioning the drafts a restart throws away, then turns Talk on', async () => {
const user = userEvent.setup();
const off = employee({ talk: { state: 'off', agent_node_id: null }, pending_approvals: 2 });
+ const fromDatabase = employee({ revision: 10, talk: { state: 'on', agent_node_id: AGENT } });
sendRequest.mockImplementation(async (type: string) =>
type === 'enable_employee_talk'
? { success: true, employee: { ...off, control: undefined, talk: { state: 'on', agent_node_id: AGENT }, revision: 9 } }
- : { success: true, messages: [] },
+ : type === 'list_employees'
+ ? { success: true, employees: [fromDatabase] }
+ : { success: true, messages: [] },
);
renderTalk(off);
expect(sendRequest).not.toHaveBeenCalledWith('get_chat_messages', expect.anything());
@@ -247,17 +257,22 @@ describe('Turn on Talk', () => {
const [, payload, timeout] = sendRequest.mock.calls.find(([type]) => type === 'enable_employee_talk')!;
expect(payload).toEqual({ workflow_id: 'w1', idempotency_key: expect.any(String) });
expect(timeout).toBe(WORKFLOW_CONTROL_REQUEST_TIMEOUT);
- expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 9, talk: { state: 'on' } });
+ expect(client.getQueryState(employeeDetailKey('w1'))?.isInvalidated).toBe(true);
+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 10, talk: { state: 'on' } }));
+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});
});
});
describe('Apply', () => {
it('restarts the employee on the latest setup', async () => {
const summary = employee({ pending_changes: true });
+ const fromDatabase = employee({ pending_changes: false, revision: 14 });
sendRequest.mockImplementation(async (type: string) =>
type === 'apply_employee_changes'
? { success: true, employee: { ...summary, control: undefined, pending_changes: false, revision: 12 } }
- : { success: true, messages: [] },
+ : type === 'list_employees'
+ ? { success: true, employees: [fromDatabase] }
+ : { success: true, messages: [] },
);
renderTalk(summary);
expect(await screen.findByText(/Maya has new abilities for this conversation\./)).toBeInTheDocument();
@@ -268,20 +283,43 @@ describe('Apply', () => {
{ workflow_id: 'w1', idempotency_key: expect.any(String) },
WORKFLOW_CONTROL_REQUEST_TIMEOUT,
);
- expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 12, pending_changes: false });
+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 14, pending_changes: false }));
+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});
});
- it('keeps the employee it gets back when the restart fails', async () => {
+ it('refreshes database state when the restart fails instead of merging its response summary', async () => {
const summary = employee({ pending_changes: true });
+ const fromDatabase = employee({ pending_changes: true, revision: 15 }, 'ready');
sendRequest.mockImplementation(async (type: string) =>
type === 'apply_employee_changes'
? { success: false, error: 'restart_failed', employee: { ...summary, control: { state: 'ready' }, revision: 13 } }
- : { success: true, messages: [] },
+ : type === 'list_employees'
+ ? { success: true, employees: [fromDatabase] }
+ : { success: true, messages: [] },
);
renderTalk(summary);
fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));
await waitFor(() => expect(pillToast).toHaveBeenCalledWith('Maya couldn’t restart. Try starting them again.', { tone: 'error' }));
- expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 13 });
+ await waitFor(() => expect(client.getQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY)?.[0]).toMatchObject({ revision: 15, control: { state: 'ready' } }));
+ expect(sendRequest).toHaveBeenCalledWith('list_employees', {});
+ });
+
+ it('does not recreate a deleted employee when an earlier Apply response arrives', async () => {
+ const summary = employee({ pending_changes: true });
+ let finish!: (response: unknown) => void;
+ sendRequest.mockImplementation((type: string) => {
+ if (type === 'apply_employee_changes') return new Promise((resolve) => { finish = resolve; });
+ if (type === 'list_employees') return Promise.resolve({ success: true, employees: [] });
+ return Promise.resolve({ success: true, messages: [] });
+ });
+ renderTalk(summary);
+ fireEvent.click(await screen.findByRole('button', { name: 'Apply' }));
+ await waitFor(() => expect(finish).toBeTypeOf('function'));
+ await act(async () => { removeEmployee(client, 'w1'); });
+ await act(async () => { finish({ success: true, employee: { ...summary, revision: 99 } }); });
+ await waitFor(() => expect(sendRequest.mock.calls.filter(([type]) => type === 'list_employees')).toHaveLength(2));
+ expect(client.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);
+ expect(client.getQueryData(employeeDetailKey('w1'))).toBeUndefined();
});
});
diff --git a/client/src/features/home/__tests__/workspace.test.tsx b/client/src/features/home/__tests__/workspace.test.tsx
index 23b55323..465d7213 100644
--- a/client/src/features/home/__tests__/workspace.test.tsx
+++ b/client/src/features/home/__tests__/workspace.test.tsx
@@ -67,6 +67,15 @@ function employee(patch: Record<string, unknown> = {}): EmployeeSummary {
}
function renderWith(team: EmployeeSummary[], ui: ReactElement = <WorkspaceDock onConnect={vi.fn()} />) {
+ const sendOtherRequest = actions.sendRequest.getMockImplementation();
+ actions.sendRequest.mockImplementation(async (type: string, data?: Record<string, unknown>) => {
+ if (type === 'list_employees') return { success: true, employees: team };
+ if (type === 'get_employee') {
+ const selected = team.find((member) => member.workflow_id === data?.workflow_id);
+ return selected ? { success: true, employee: selected } : { success: false, error: 'not_found' };
+ }
+ return sendOtherRequest?.(type, data);
+ });
const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } } });
client.setQueryData(EMPLOYEES_QUERY_KEY, team);
render(
diff --git a/client/src/features/home/data/employeeCache.ts b/client/src/features/home/data/employeeCache.ts
new file mode 100644
index 00000000..714694da
--- /dev/null
+++ b/client/src/features/home/data/employeeCache.ts
@@ -0,0 +1,30 @@
+import type { QueryClient } from '@tanstack/react-query';
+import { useHomeStore } from '../state/homeStore';
+import type { EmployeeSummary } from './schemas';
+
+export const EMPLOYEES_QUERY_KEY = ['employees'] as const;
+export const employeeDetailKey = (workflowId: string) => ['employees', 'detail', workflowId] as const;
+
+/** Reconcile a confirmed deletion in either mode, including an in-flight list. */
+export function removeEmployee(queryClient: QueryClient, workflowId: string): void {
+ // Cancellation reverts query state synchronously. Prune afterwards so an
+ // older request cannot restore the employee when its response arrives.
+ void queryClient.cancelQueries({ queryKey: EMPLOYEES_QUERY_KEY, exact: true });
+ void queryClient.cancelQueries({ queryKey: employeeDetailKey(workflowId), exact: true });
+ queryClient.setQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY, (list) =>
+ list?.filter((employee) => employee.workflow_id !== workflowId),
+ );
+ queryClient.removeQueries({ queryKey: employeeDetailKey(workflowId), exact: true });
+
+ useHomeStore.setState((state) => ({
+ view: state.view.kind === 'employee' && state.view.workflowId === workflowId
+ ? { kind: 'hire' }
+ : state.view,
+ workspaceFor: state.workspaceFor === workflowId ? null : state.workspaceFor,
+ hireNotice: state.hireNotice?.workflowId === workflowId ? null : state.hireNotice,
+ glow: state.glow?.workflowId === workflowId ? null : state.glow,
+ }));
+
+ // Refresh anything else the canceled list request would have brought in.
+ void queryClient.invalidateQueries({ queryKey: EMPLOYEES_QUERY_KEY, exact: true });
+}
diff --git a/client/src/features/home/data/employees.ts b/client/src/features/home/data/employees.ts
index 6b1825bc..ef00045d 100644
--- a/client/src/features/home/data/employees.ts
+++ b/client/src/features/home/data/employees.ts
@@ -5,9 +5,9 @@
*
* `useEmployeeLifecycle()` keeps the cache current from broadcasts, and is
* mounted once by the Home shell:
- * - `employee_lifecycle` hired / updated carry the fresh summary: upserted
- * when newer than what the cache holds (by `revision`), so a delayed
- * broadcast never rolls a row back; removed deletes it.
+ * - `employee_lifecycle` hired / updated refresh the server queries. Event
+ * summaries may already be out of date, so they never replace cached rows.
+ * Confirmed removals prune the cache and refresh the remaining team.
* - `workflow_lifecycle` created / renamed / imported mean a workflow
* (every workflow is an employee) appeared or changed name: the list is
* refetched, debounced so a burst costs one request.
@@ -18,13 +18,13 @@ import { useEffect } from 'react';
import { useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query';
import { useWebSocketActions } from '@/contexts/WebSocketContext';
import { makeDebouncedInvalidator } from '@/lib/debouncedInvalidate';
-import { parseEmployee, parseEmployeeDetail, parseEmployees, type EmployeeDetail, type EmployeeSummary } from './schemas';
+import { parseEmployeeDetail, parseEmployees, type EmployeeDetail, type EmployeeSummary } from './schemas';
+import { EMPLOYEES_QUERY_KEY, employeeDetailKey, removeEmployee } from './employeeCache';
-export const EMPLOYEES_QUERY_KEY = ['employees'] as const;
-export const employeeDetailKey = (workflowId: string) => ['employees', 'detail', workflowId] as const;
+export { EMPLOYEES_QUERY_KEY, employeeDetailKey, removeEmployee } from './employeeCache';
const LIST_INVALIDATE_DEBOUNCE_MS = 300;
-export const invalidateEmployees = makeDebouncedInvalidator(EMPLOYEES_QUERY_KEY, LIST_INVALIDATE_DEBOUNCE_MS);
+export const invalidateEmployees = makeDebouncedInvalidator(EMPLOYEES_QUERY_KEY, LIST_INVALIDATE_DEBOUNCE_MS, true);
/** Dev builds only: `?fixture=employees` shows the handoff's sample team. */
@@ -45,6 +45,9 @@ export function useEmployeesQuery() {
},
enabled: isReady || fixture,
staleTime: 30_000,
+ // Home's lifecycle listener is absent in Dev; re-entry must reconcile
+ // even a warm cache whose removal broadcasts arrived while unmounted.
+ refetchOnMount: 'always',
});
}
@@ -64,6 +67,7 @@ export function useEmployeeDetailQuery(workflowId: string | null) {
},
enabled: isReady && Boolean(workflowId),
staleTime: 30_000,
+ refetchOnMount: 'always',
});
}
@@ -99,28 +103,10 @@ export function resetSeenEmployeeEvents(): void {
seen.clear();
}
-/** Put a summary into the cache unless the cache already holds a newer one.
- * New employees go first (placeFirst), as a fresh hire does. */
-export function upsertEmployee(queryClient: QueryClient, summary: EmployeeSummary, placeFirst: boolean): void {
- queryClient.setQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY, (list) => {
- if (!list) return list;
- const index = list.findIndex((item) => item.workflow_id === summary.workflow_id);
- if (index === -1) return placeFirst ? [summary, ...list] : [...list, summary];
- if (list[index].revision > summary.revision) return list;
- const next = list.slice();
- next[index] = summary;
- return next;
- });
- queryClient.setQueryData<EmployeeDetail | null>(employeeDetailKey(summary.workflow_id), (detail) =>
- detail && detail.revision <= summary.revision ? { ...detail, ...summary } : detail,
- );
-}
-
-function remove(queryClient: QueryClient, workflowId: string): void {
- queryClient.setQueryData<EmployeeSummary[]>(EMPLOYEES_QUERY_KEY, (list) =>
- list ? list.filter((item) => item.workflow_id !== workflowId) : list,
- );
- queryClient.removeQueries({ queryKey: employeeDetailKey(workflowId) });
+/** Read the current database state after a mutation or lifecycle signal. */
+export function refreshEmployee(queryClient: QueryClient, workflowId: string): void {
+ void queryClient.invalidateQueries({ queryKey: employeeDetailKey(workflowId), exact: true });
+ invalidateEmployees(queryClient);
}
/** Apply one `employee_lifecycle` envelope to the cache. Exported for tests. */
@@ -130,15 +116,10 @@ export function applyEmployeeLifecycle(queryClient: QueryClient, event: Lifecycl
const workflowId = event.data?.workflow_id ?? event.subject ?? '';
if (!workflowId) return;
if (type.endsWith('.removed')) {
- remove(queryClient, workflowId);
- return;
- }
- const summary = parseEmployee(event.data?.employee);
- if (!summary || summary.workflow_id !== workflowId) {
- invalidateEmployees(queryClient);
+ removeEmployee(queryClient, workflowId);
return;
}
- upsertEmployee(queryClient, summary, type.endsWith('.hired'));
+ if (type.endsWith('.hired') || type.endsWith('.updated')) refreshEmployee(queryClient, workflowId);
}
/** Apply one `workflow_lifecycle` envelope to the team list. Exported for tests. */
@@ -146,9 +127,10 @@ export function applyWorkflowLifecycle(queryClient: QueryClient, event: Lifecycl
const type = event?.type ?? '';
const workflowId = event?.subject ?? '';
if (type.endsWith('.deleted') && workflowId) {
- remove(queryClient, workflowId);
+ removeEmployee(queryClient, workflowId);
} else if (['.created', '.renamed', '.imported'].some((stage) => type.endsWith(stage))) {
- invalidateEmployees(queryClient);
+ if (workflowId) refreshEmployee(queryClient, workflowId);
+ else invalidateEmployees(queryClient);
}
}
diff --git a/client/src/features/home/data/talk.ts b/client/src/features/home/data/talk.ts
index 942dc06a..a88712ef 100644
--- a/client/src/features/home/data/talk.ts
+++ b/client/src/features/home/data/talk.ts
@@ -16,8 +16,8 @@
* the editor's hooks see only the workflow open in Dev mode), with
* fallbacks for an agent that never picks the message up or never ends.
* - `useEnableTalk()` / `useApplyChanges()`: Turn on Talk and Apply. Both
- * restart the employee, so they wait as long as Start does; the summary
- * they return goes into the team cache.
+ * restart the employee, so they wait as long as Start does, then refresh
+ * the team from the database.
* - Pure helpers the thread renders from: restart dividers, time labels.
*/
@@ -27,8 +27,7 @@ import { z } from 'zod';
import { WORKFLOW_CONTROL_REQUEST_TIMEOUT, useWebSocketActions } from '@/contexts/WebSocketContext';
import { STALE_TIME, queryKeys } from '@/lib/queryConfig';
import { useNodeStatusStore } from '@/stores/nodeStatusStore';
-import { upsertEmployee } from './employees';
-import { parseEmployee, type EmployeeSummary } from './schemas';
+import { refreshEmployee } from './employees';
/** The newest messages the thread shows. */
export const THREAD_LIMIT = 200;
@@ -286,24 +285,22 @@ export function useReplyWait(
// ----- Turn on Talk, Apply -----
-/** Both restart the employee on the server. The employee they return goes
- * into the team cache, also on `restart_failed`, which carries it too.
+/** Both restart the employee on the server. Refresh the queries afterwards,
+ * including failures that may have changed the employee before failing.
* Every click sends its own idempotency key. Errors carry the server's code. */
function useEmployeeChange(type: 'enable_employee_talk' | 'apply_employee_changes') {
const { sendRequest } = useWebSocketActions();
const queryClient = useQueryClient();
- return useMutation<EmployeeSummary | null, Error, string>({
+ return useMutation<void, Error, string>({
mutationFn: async (workflowId) => {
- const response = await sendRequest<{ success?: boolean; error?: string; employee?: unknown }>(
+ const response = await sendRequest<{ success?: boolean; error?: string }>(
type,
{ workflow_id: workflowId, idempotency_key: crypto.randomUUID() },
WORKFLOW_CONTROL_REQUEST_TIMEOUT,
);
- const employee = parseEmployee(response?.employee);
- if (employee) upsertEmployee(queryClient, employee, false);
if (response?.success === false) throw new Error(response.error || 'failed');
- return employee;
},
+ onSettled: (_data, _error, workflowId) => refreshEmployee(queryClient, workflowId),
});
}
diff --git a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
index ce27f405..3b60270f 100644
--- a/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
+++ b/client/src/features/home/genui/__tests__/HireDraftPanel.test.tsx
@@ -8,7 +8,7 @@
*/
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { act, fireEvent, render, screen } from '@testing-library/react';
+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { setReducedMotion } from '@/test/waapi';
import { useShellDialogsStore } from '@/stores/shellDialogsStore';
@@ -128,7 +128,10 @@ describe('HireDraftPanel', () => {
finish(hired());
});
expect(useDraftStore.getState().status).toBe('idle');
- expect(queryClient.getQueryData<{ workflow_id: string }[]>(EMPLOYEES_QUERY_KEY)?.[0]?.workflow_id).toBe('w1');
+ // Hiring selects the response's identity, but the list is refreshed from
+ // the database rather than populated with the mutation's summary.
+ expect(queryClient.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);
+ await waitFor(() => expect(queryClient.getQueryState(EMPLOYEES_QUERY_KEY)?.isInvalidated).toBe(true));
expect(useHomeStore.getState().glow?.workflowId).toBe('w1');
expect(useHomeStore.getState().view).toEqual({ kind: 'employee', workflowId: 'w1' });
expect(useHomeStore.getState().hireNotice).toBeNull();
diff --git a/client/src/features/home/genui/useHire.ts b/client/src/features/home/genui/useHire.ts
index 1a919a8f..e222e88d 100644
--- a/client/src/features/home/genui/useHire.ts
+++ b/client/src/features/home/genui/useHire.ts
@@ -15,7 +15,7 @@
import { useCallback } from 'react';
import { useQueryClient, type QueryClient } from '@tanstack/react-query';
import { useWebSocketActions } from '@/contexts/WebSocketContext';
-import { upsertEmployee } from '../data/employees';
+import { refreshEmployee } from '../data/employees';
import { parseEmployee, type EmployeeSummary } from '../data/schemas';
import { SPIKE, spikeOrb } from '../orb/orb';
import { useHomeStore } from '../state/homeStore';
@@ -71,7 +71,7 @@ export function hireFailureMessage(error: unknown): string {
/** The new employee joins the team: a glow, the logo, a toast, and their
* page, with what the hire said. */
export function welcomeHire(queryClient: QueryClient, employee: EmployeeSummary, response: HireResponse): void {
- upsertEmployee(queryClient, employee, true);
+ refreshEmployee(queryClient, employee.workflow_id);
const home = useHomeStore.getState();
home.glowRow(employee.workflow_id);
home.pulseLogo();
diff --git a/client/src/features/home/sidebar/HomeSidebar.tsx b/client/src/features/home/sidebar/HomeSidebar.tsx
index 9992e964..70cce5fc 100644
--- a/client/src/features/home/sidebar/HomeSidebar.tsx
+++ b/client/src/features/home/sidebar/HomeSidebar.tsx
@@ -4,11 +4,21 @@
* (width + opacity); the header then shows the logo and an open button.
*/
-import { useLayoutEffect, useRef } from 'react';
-import { PanelLeft, Plus, Settings } from 'lucide-react';
+import { useLayoutEffect, useRef, useState } from 'react';
+import { PanelLeft, Plus, Settings, X } from 'lucide-react';
import { OcLogo } from '@/components/brand/Logo';
import { ActionButton } from '@/components/ui/action-button';
import { Button } from '@/components/ui/button';
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from '@/components/ui/alert-dialog';
import { Skeleton } from '@/components/ui/skeleton';
import { animate } from '@/lib/motion';
import { cn } from '@/lib/utils';
@@ -19,6 +29,8 @@ import type { EmployeeSummary } from '../data/schemas';
import { useHomeStore } from '../state/homeStore';
import { Avatar, MicroLabel } from '../ui/primitives';
import { useWorkflowControlPending } from '@/stores/workflowControlStore';
+import { useAppStore } from '@/store/useAppStore';
+import { pillToast } from '../ui/pillToast';
function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; selected: boolean }) {
const showEmployee = useHomeStore((s) => s.showEmployee);
@@ -26,6 +38,25 @@ function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; select
const pending = useWorkflowControlPending(employee.workflow_id);
const ref = useRef<HTMLButtonElement>(null);
const view = presentEmployee(employee, pending);
+ const deleteWorkflow = useAppStore((s) => s.deleteWorkflow);
+ const [confirming, setConfirming] = useState(false);
+ const [deleting, setDeleting] = useState(false);
+ const deletingRef = useRef(false);
+
+ const remove = async () => {
+ if (deletingRef.current) return;
+ deletingRef.current = true;
+ setDeleting(true);
+ try {
+ if (!(await deleteWorkflow(employee.workflow_id))) throw new Error('Delete failed');
+ setConfirming(false);
+ } catch {
+ pillToast(`Couldn’t delete ${employee.name}. Try again.`, { tone: 'error' });
+ } finally {
+ deletingRef.current = false;
+ setDeleting(false);
+ }
+ };
// A new hire drops into the list with a green glow (design handoff "Hire").
useLayoutEffect(() => {
@@ -51,31 +82,64 @@ function EmployeeRow({ employee, selected }: { employee: EmployeeSummary; select
}, [glow]);
return (
- <button
- ref={ref}
- type="button"
- data-employee-row={employee.workflow_id}
- aria-current={selected ? 'page' : undefined}
- onClick={() => showEmployee(employee.workflow_id)}
+ <div
className={cn(
- 'flex min-h-12.5 w-full items-center gap-2.5 rounded-row px-2.5 py-1.5 text-left text-fg-default transition-colors hover:bg-bg-hover',
+ 'group flex w-full items-center rounded-row text-fg-default transition-colors hover:bg-bg-hover',
selected && 'bg-bg-hover',
)}
>
- <Avatar name={employee.name} colorRole={employee.color_role} status={view.pill.tone} pulse={view.pulse} />
- <span className="flex min-w-0 flex-1 flex-col gap-px">
- <span className="truncate text-row font-medium">{employee.name}</span>
- <span className="truncate text-xs text-fg-muted">{employee.role}</span>
- </span>
- {employee.pending_approvals > 0 && (
- <span
- className="grid h-5 min-w-5 shrink-0 place-items-center rounded-pill border border-status-waiting-border bg-status-waiting-fill px-1.5 font-mono text-2xs font-semibold text-status-waiting-ink"
- aria-label={`${employee.pending_approvals} waiting for you`}
- >
- {employee.pending_approvals}
+ <button
+ ref={ref}
+ type="button"
+ data-employee-row={employee.workflow_id}
+ aria-current={selected ? 'page' : undefined}
+ onClick={() => showEmployee(employee.workflow_id)}
+ className="flex min-h-12.5 min-w-0 flex-1 items-center gap-2.5 rounded-row px-2.5 py-1.5 text-left"
+ >
+ <Avatar name={employee.name} colorRole={employee.color_role} status={view.pill.tone} pulse={view.pulse} />
+ <span className="flex min-w-0 flex-1 flex-col gap-px">
+ <span className="truncate text-row font-medium">{employee.name}</span>
+ <span className="truncate text-xs text-fg-muted">{employee.role}</span>
</span>
- )}
- </button>
+ {employee.pending_approvals > 0 && (
+ <span
+ className="grid h-5 min-w-5 shrink-0 place-items-center rounded-pill border border-status-waiting-border bg-status-waiting-fill px-1.5 font-mono text-2xs font-semibold text-status-waiting-ink"
+ aria-label={`${employee.pending_approvals} waiting for you`}
+ >
+ {employee.pending_approvals}
+ </span>
+ )}
+ </button>
+ <Button
+ variant="quiet"
+ size="icon-sm"
+ aria-label={`Delete ${employee.name}`}
+ title={`Delete ${employee.name}`}
+ disabled={deleting}
+ onClick={() => setConfirming(true)}
+ className="mr-1 size-7.5 shrink-0 text-action-stop-ink opacity-100 transition-opacity hover:bg-action-stop-soft group-hover:opacity-100 group-focus-within:opacity-100 [@media(hover:hover)]:opacity-0"
+ >
+ <X aria-hidden className="size-3.75" />
+ </Button>
+ <AlertDialog open={confirming} onOpenChange={(open) => { if (!deletingRef.current) setConfirming(open); }}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Delete {employee.name}?</AlertDialogTitle>
+ <AlertDialogDescription>This removes the employee and their workflow. This cannot be undone.</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={deleting}>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ disabled={deleting}
+ onClick={(event) => { event.preventDefault(); void remove(); }}
+ >
+ {deleting ? 'Deleting…' : 'Delete'}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
);
}
diff --git a/client/src/hooks/useWorkflowsQuery.ts b/client/src/hooks/useWorkflowsQuery.ts
index 182f1fb1..73734ee3 100644
--- a/client/src/hooks/useWorkflowsQuery.ts
+++ b/client/src/hooks/useWorkflowsQuery.ts
@@ -1,11 +1,10 @@
/**
- * Workflow list + single-workflow queries, and save/delete mutations.
+ * Workflow list + single-workflow queries, and the save mutation.
*
* Server-owned data (the workflow list and individual workflow records)
- * lives in the TanStack Query cache, not in Zustand. The Zustand store
- * keeps only the mutable edit buffer (currentWorkflow). When a save or
- * delete completes, these mutations invalidate `['workflows']` so any
- * component consuming `useWorkflowsQuery()` re-renders with fresh data.
+ * is read from the backend database through shared Query options. Zustand
+ * keeps only the mutable edit buffer (currentWorkflow). Deletion goes through
+ * useAppStore.deleteWorkflow so both modes share confirmation-result cleanup.
*
* Mirrors the ownership boundary established by `useCatalogueQuery.ts`.
*/
@@ -14,6 +13,7 @@ import {
useQuery,
useMutation,
useQueryClient,
+ queryOptions,
type UseQueryResult,
} from '@tanstack/react-query';
import {
@@ -43,8 +43,8 @@ function toSavedWorkflow(w: WorkflowSummary): SavedWorkflow {
};
}
-export function useWorkflowsQuery(): UseQueryResult<SavedWorkflow[], Error> {
- return useQuery<SavedWorkflow[], Error>({
+export function workflowsQueryOptions() {
+ return queryOptions({
queryKey: WORKFLOWS_QUERY_KEY,
queryFn: async () => {
const list = await workflowApi.getAllWorkflows();
@@ -54,6 +54,10 @@ export function useWorkflowsQuery(): UseQueryResult<SavedWorkflow[], Error> {
});
}
+export function useWorkflowsQuery(): UseQueryResult<SavedWorkflow[], Error> {
+ return useQuery(workflowsQueryOptions());
+}
+
export interface SaveWorkflowInput {
id: string;
name: string;
@@ -73,24 +77,15 @@ export function useSaveWorkflowMutation() {
});
}
-export function useDeleteWorkflowMutation() {
- const qc = useQueryClient();
- return useMutation<void, Error, string>({
- mutationFn: async (id) => {
- const ok = await workflowApi.deleteWorkflow(id);
- if (!ok) throw new Error('Failed to delete workflow');
- },
- onSuccess: () => {
- void qc.invalidateQueries({ queryKey: WORKFLOWS_QUERY_KEY });
- },
- });
-}
-
-export function useWorkflowQuery(id: string | null | undefined) {
- return useQuery<ApiWorkflowData | null, Error>({
+export function workflowQueryOptions(id: string | null | undefined) {
+ return queryOptions<ApiWorkflowData | null, Error>({
queryKey: id ? workflowQueryKey(id) : ['workflow', 'none'],
queryFn: () => (id ? workflowApi.getWorkflow(id) : Promise.resolve(null)),
enabled: !!id,
staleTime: 30_000,
});
}
+
+export function useWorkflowQuery(id: string | null | undefined) {
+ return useQuery(workflowQueryOptions(id));
+}
diff --git a/client/src/lib/__tests__/debouncedInvalidate.test.ts b/client/src/lib/__tests__/debouncedInvalidate.test.ts
new file mode 100644
index 00000000..f46e628d
--- /dev/null
+++ b/client/src/lib/__tests__/debouncedInvalidate.test.ts
@@ -0,0 +1,40 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { QueryClient } from '@tanstack/react-query';
+import { makeDebouncedInvalidator } from '../debouncedInvalidate';
+
+let client: QueryClient;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ client = new QueryClient();
+ client.setQueryData(['team'], ['a']);
+ client.setQueryData(['team', 'detail', 'a'], { name: 'Maya' });
+});
+
+afterEach(() => {
+ client.clear();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+describe('makeDebouncedInvalidator', () => {
+ it('keeps prefix invalidation for existing callers', () => {
+ const invalidate = makeDebouncedInvalidator(['team'], 300);
+ invalidate(client);
+ vi.advanceTimersByTime(300);
+ expect(client.getQueryState(['team'])?.isInvalidated).toBe(true);
+ expect(client.getQueryState(['team', 'detail', 'a'])?.isInvalidated).toBe(true);
+ });
+
+ it('coalesces an exact-list refresh without invalidating unrelated details', () => {
+ const invalidate = makeDebouncedInvalidator(['team'], 300, true);
+ invalidate(client);
+ vi.advanceTimersByTime(200);
+ invalidate(client);
+ vi.advanceTimersByTime(299);
+ expect(client.getQueryState(['team'])?.isInvalidated).toBe(false);
+ vi.advanceTimersByTime(1);
+ expect(client.getQueryState(['team'])?.isInvalidated).toBe(true);
+ expect(client.getQueryState(['team', 'detail', 'a'])?.isInvalidated).toBe(false);
+ });
+});
diff --git a/client/src/lib/debouncedInvalidate.ts b/client/src/lib/debouncedInvalidate.ts
index cc521bed..d97a21c0 100644
--- a/client/src/lib/debouncedInvalidate.ts
+++ b/client/src/lib/debouncedInvalidate.ts
@@ -9,13 +9,13 @@
import type { QueryClient, QueryKey } from '@tanstack/react-query';
-export function makeDebouncedInvalidator(queryKey: QueryKey, delayMs: number) {
+export function makeDebouncedInvalidator(queryKey: QueryKey, delayMs: number, exact?: boolean) {
let timer: ReturnType<typeof setTimeout> | null = null;
return (queryClient: QueryClient): void => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
timer = null;
- void queryClient.invalidateQueries({ queryKey });
+ void queryClient.invalidateQueries({ queryKey, ...(exact === undefined ? {} : { exact }) });
}, delayMs);
};
}
diff --git a/client/src/store/__tests__/deleteWorkflow.test.ts b/client/src/store/__tests__/deleteWorkflow.test.ts
new file mode 100644
index 00000000..800c6c71
--- /dev/null
+++ b/client/src/store/__tests__/deleteWorkflow.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { workflowApi } from '../../services/workflowApi';
+import { queryClient } from '../../lib/queryClient';
+import { WORKFLOWS_QUERY_KEY, workflowQueryKey } from '../../hooks/useWorkflowsQuery';
+import { EMPLOYEES_QUERY_KEY, employeeDetailKey } from '../../features/home/data/employeeCache';
+import { useHomeStore } from '../../features/home/state/homeStore';
+import { useAppStore, type WorkflowData } from '../useAppStore';
+
+vi.mock('../../services/workflowApi', () => ({
+ workflowApi: { getAllWorkflows: vi.fn(), getWorkflow: vi.fn(), saveWorkflow: vi.fn(), deleteWorkflow: vi.fn() },
+}));
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((done) => { resolve = done; });
+ return { promise, resolve };
+}
+
+let sequence = 0;
+let employee: WorkflowData;
+const record = (workflow: WorkflowData) => ({
+ ...workflow, data: { nodes: workflow.nodes, edges: workflow.edges },
+ createdAt: workflow.createdAt.toISOString(), lastModified: workflow.lastModified.toISOString(),
+});
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ queryClient.clear();
+ employee = {
+ id: `delete-test-${++sequence}`, name: 'Maya', slug: 'maya',
+ nodes: [{ id: 'agent', type: 'aiAgent', position: { x: 0, y: 0 }, data: {} }],
+ edges: [], createdAt: new Date(0), lastModified: new Date(0),
+ };
+ useAppStore.setState({
+ currentWorkflow: employee, hasUnsavedChanges: true, selectedNode: employee.nodes[0],
+ workflowUIStates: {}, renamingNodeId: 'agent',
+ });
+ useHomeStore.setState({ view: { kind: 'hire' }, workspaceFor: null, hireNotice: null, glow: null });
+ vi.mocked(workflowApi.deleteWorkflow).mockResolvedValue(true);
+});
+
+afterEach(() => {
+ queryClient.clear();
+ vi.restoreAllMocks();
+});
+
+describe('workflow deletion', () => {
+ it('removes the current employee from both modes without creating an Untitled replacement', async () => {
+ useHomeStore.getState().showEmployee(employee.id);
+ useAppStore.getState().setWorkflowViewport(employee.id, { x: 10, y: 20, zoom: 1 });
+ queryClient.setQueryData(WORKFLOWS_QUERY_KEY, [employee]);
+ queryClient.setQueryData(workflowQueryKey(employee.id), record(employee));
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [{ workflow_id: employee.id, name: employee.name }]);
+ queryClient.setQueryData(employeeDetailKey(employee.id), { workflow_id: employee.id });
+
+ expect(await useAppStore.getState().deleteWorkflow(employee.id)).toBe(true);
+ expect(workflowApi.saveWorkflow).not.toHaveBeenCalled();
+ expect(useAppStore.getState()).toMatchObject({ currentWorkflow: null, hasUnsavedChanges: false, selectedNode: null, renamingNodeId: null });
+ expect(useAppStore.getState().workflowUIStates[employee.id]).toBeUndefined();
+ expect(queryClient.getQueryData(WORKFLOWS_QUERY_KEY)).toEqual([]);
+ expect(queryClient.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([]);
+ expect(queryClient.getQueryData(workflowQueryKey(employee.id))).toBeUndefined();
+ expect(queryClient.getQueryData(employeeDetailKey(employee.id))).toBeUndefined();
+ expect(useHomeStore.getState()).toMatchObject({ view: { kind: 'hire' }, workspaceFor: null });
+ });
+
+ it('keeps the graph and team when deletion fails', async () => {
+ vi.mocked(workflowApi.deleteWorkflow).mockResolvedValue(false);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ queryClient.setQueryData(EMPLOYEES_QUERY_KEY, [{ workflow_id: employee.id }]);
+ expect(await useAppStore.getState().deleteWorkflow(employee.id)).toBe(false);
+ expect(useAppStore.getState().currentWorkflow).toBe(employee);
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(true);
+ expect(queryClient.getQueryData(EMPLOYEES_QUERY_KEY)).toEqual([{ workflow_id: employee.id }]);
+ });
+
+ it('preserves another open workflow and its unsaved changes', async () => {
+ await useAppStore.getState().deleteWorkflow(`other-${sequence}`);
+ expect(useAppStore.getState().currentWorkflow).toBe(employee);
+ expect(useAppStore.getState().hasUnsavedChanges).toBe(true);
+ });
+
+ it('checks the current selection after the delete finishes', async () => {
+ const request = deferred<boolean>();
+ vi.mocked(workflowApi.deleteWorkflow).mockReturnValue(request.promise);
+ const deleting = useAppStore.getState().deleteWorkflow(employee.id);
+ const next = { ...employee, id: `next-${sequence}` };
+ useAppStore.getState().setCurrentWorkflow(next);
+ request.resolve(true);
+ await deleting;
+ expect(useAppStore.getState().currentWorkflow).toBe(next);
+ expect(workflowApi.saveWorkflow).not.toHaveBeenCalled();
+ });
+
+ it('ignores a load response that arrives after deletion', async () => {
+ const request = deferred<ReturnType<typeof record>>();
+ vi.mocked(workflowApi.getWorkflow).mockReturnValue(request.promise);
+ const loading = useAppStore.getState().loadWorkflow(employee.id);
+ await useAppStore.getState().deleteWorkflow(employee.id);
+ request.resolve(record(employee));
+ await loading;
+ expect(useAppStore.getState().currentWorkflow).toBeNull();
+ });
+
+ it('ignores a save response that arrives after deletion', async () => {
+ const request = deferred<{ success: boolean; id: string }>();
+ vi.mocked(workflowApi.saveWorkflow).mockReturnValue(request.promise);
+ const saving = useAppStore.getState().saveWorkflow();
+ await useAppStore.getState().deleteWorkflow(employee.id);
+ request.resolve({ success: true, id: employee.id });
+ await saving;
+ expect(useAppStore.getState().currentWorkflow).toBeNull();
+ });
+
+ it('ignores a migration response that arrives after deletion', async () => {
+ employee.nodes[0].type = 'googleChatModel';
+ const request = deferred<{ success: boolean; id: string }>();
+ vi.mocked(workflowApi.saveWorkflow).mockReturnValue(request.promise);
+ const migrating = useAppStore.getState().migrateCurrentWorkflow();
+ await useAppStore.getState().deleteWorkflow(employee.id);
+ request.resolve({ success: true, id: employee.id });
+ await migrating;
+ expect(useAppStore.getState().currentWorkflow).toBeNull();
+ });
+
+ it('applies remote deletion without issuing another DELETE or replacement save', () => {
+ useAppStore.getState().forgetWorkflow(employee.id);
+ expect(useAppStore.getState().currentWorkflow).toBeNull();
+ expect(workflowApi.deleteWorkflow).not.toHaveBeenCalled();
+ expect(workflowApi.saveWorkflow).not.toHaveBeenCalled();
+ });
+
+ it('still creates a workflow when New is explicitly requested', async () => {
+ await useAppStore.getState().deleteWorkflow(employee.id);
+ vi.mocked(workflowApi.saveWorkflow).mockResolvedValue({ success: true, id: `new-${sequence}` });
+ await useAppStore.getState().createNewWorkflow();
+ expect(workflowApi.saveWorkflow).toHaveBeenCalledWith('new', 'Untitled Workflow', { nodes: [], edges: [] });
+ expect(useAppStore.getState().currentWorkflow?.id).toBe(`new-${sequence}`);
+ });
+});
diff --git a/client/src/store/useAppStore.ts b/client/src/store/useAppStore.ts
index a7bb50df..31832504 100644
--- a/client/src/store/useAppStore.ts
+++ b/client/src/store/useAppStore.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand';
+import { isCancelledError } from '@tanstack/react-query';
import { Node, Edge } from 'reactflow';
import { toast } from 'sonner';
import { NEW_WORKFLOW_ID } from '../utils/workflow';
@@ -14,7 +15,8 @@ import { workflowApi } from '../services/workflowApi';
import { queryClient } from '../lib/queryClient';
import { addSavedEdges, addSavedNodes, type WorkflowOperation } from '../lib/workflowOps';
import { BRAND_STORAGE_KEYS, readAndMigrateStorageValue } from '../lib/brandStorage';
-import { WORKFLOWS_QUERY_KEY } from '../hooks/useWorkflowsQuery';
+import { WORKFLOWS_QUERY_KEY, workflowQueryKey, workflowQueryOptions, type SavedWorkflow } from '../hooks/useWorkflowsQuery';
+import { removeEmployee } from '../features/home/data/employeeCache';
const invalidateWorkflowsList = (): void => {
void queryClient.invalidateQueries({ queryKey: WORKFLOWS_QUERY_KEY });
@@ -87,6 +89,8 @@ interface AppStore {
saveWorkflow: () => Promise<void>;
loadWorkflow: (id: string) => Promise<void>;
deleteWorkflow: (id: string) => Promise<boolean>;
+ /** Apply a successful deletion from this tab or a lifecycle broadcast. */
+ forgetWorkflow: (id: string) => void;
migrateCurrentWorkflow: () => Promise<void>;
/** Adopt a batch the server already saved (`workflow_ops_apply` with
* `persisted: true`) into the open workflow, whichever screen shows.
@@ -307,6 +311,9 @@ export const useAppStore = create<AppStore>((set, get) => ({
console.error('Failed to save workflow to database');
return;
}
+ // A delete, navigation, or newer edit can finish while the save is in
+ // flight. Its response must not restore the old graph or clear new edits.
+ if (get().currentWorkflow !== currentWorkflow) return;
const aliases = result.nodeIdAliases ?? {};
// Server normalization is authoritative: it creates Context companions,
@@ -347,8 +354,21 @@ export const useAppStore = create<AppStore>((set, get) => ({
},
loadWorkflow: async (id) => {
- const result = await workflowApi.getWorkflow(id);
- if (result) {
+ // Use the same server-record query as other readers. Deletion cancels it,
+ // so late responses cannot restore a removed graph. No client ID registry
+ // decides whether a workflow exists; every later load asks the backend.
+ const key = workflowQueryKey(id);
+ let result;
+ try {
+ result = await queryClient.fetchQuery({
+ ...workflowQueryOptions(id),
+ staleTime: 0,
+ });
+ } catch (error) {
+ if (isCancelledError(error)) return;
+ throw error;
+ }
+ if (result && queryClient.getQueryData(key) === result) {
// Migrate old node types
const nodes = migrateNodes(result.data?.nodes || []);
const edges = result.data?.edges || [];
@@ -372,21 +392,31 @@ export const useAppStore = create<AppStore>((set, get) => ({
},
deleteWorkflow: async (id) => {
- const { currentWorkflow } = get();
-
const success = await workflowApi.deleteWorkflow(id);
if (!success) {
console.error('Failed to delete workflow from database');
return false;
}
- // If deleting current workflow, create a new one
- if (currentWorkflow?.id === id) {
- await get().createNewWorkflow();
- }
+ get().forgetWorkflow(id);
+ return true;
+ },
+ forgetWorkflow: (id) => {
+ set((state) => {
+ const { [id]: _deletedUI, ...workflowUIStates } = state.workflowUIStates;
+ return state.currentWorkflow?.id === id
+ ? { workflowUIStates, currentWorkflow: null, hasUnsavedChanges: false, selectedNode: null, renamingNodeId: null }
+ : { workflowUIStates };
+ });
+ // Cancel stale list/detail reads before pruning, even while Home is
+ // unmounted. Its cache does not automatically refetch on mount.
+ void queryClient.cancelQueries({ queryKey: WORKFLOWS_QUERY_KEY, exact: true });
+ void queryClient.cancelQueries({ queryKey: workflowQueryKey(id) });
+ queryClient.setQueryData<SavedWorkflow[]>(WORKFLOWS_QUERY_KEY, (list) => list?.filter((workflow) => workflow.id !== id));
+ queryClient.removeQueries({ queryKey: workflowQueryKey(id) });
+ removeEmployee(queryClient, id);
invalidateWorkflowsList();
- return true;
},
adoptSavedOperations: (workflowId, operations) => {
@@ -421,6 +451,7 @@ export const useAppStore = create<AppStore>((set, get) => ({
{ nodes: sanitizeNodes(migratedWorkflow.nodes), edges: migratedWorkflow.edges }
);
if (!result) return;
+ if (get().currentWorkflow !== currentWorkflow) return;
set({
currentWorkflow: {
diff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.md
index 7b4ae8c0..27b845c3 100644
--- a/docs-internal/normal_mode.md
+++ b/docs-internal/normal_mode.md
@@ -73,7 +73,7 @@ is the reference.
| `workspace/` | The Workspace dock (below), its header pill, and its Canvas tab, which loads in its own chunk |
| `settings/` | Settings pages (Profile, Billing, Skills, Connectors, Plugins). Catalog primitives live in `components/catalog`; Connectors embeds the shared `components/credentials/CredentialsBrowser`. Provider dialogs belong to AppShell. |
| `approvals/` | The drafts query, the decide mutation (optimistic), the approval broadcast listener |
-| `data/` | zod-parsed queries for employees, connectors and the profile; `talk.ts`, the thread and its mutations; `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules |
+| `data/` | zod-parsed queries for employees, connectors and the profile; `employeeCache.ts`, the team's query keys and `removeEmployee` (shared with the app store's delete); `talk.ts`, the thread and its mutations; `presentation.ts` maps server state to pills, actions and the message box's mode without deriving new rules |
| `orb/` | The 3D orb (below) |
| `ui/` | Small shared pieces (avatar, status dot and pill, app mark), the pill toast, and `useAutoGrow` (the composer's and the message box's growing text area) |
| `state/homeStore.ts` | UI state only: the view, the sidebar, Settings, the Connect an AI model dialog, the last hire's notice, the Workspace dock, one-shot glow and pulse signals |
@@ -92,6 +92,45 @@ motion and while the page is hidden ([lib/pageActivity.ts](../client/src/lib/pag
and never starts loops then. Toasts are a second sonner toaster
(`ui/pillToast.tsx`): one bottom-centre pill at a time.
+### Deleting an employee
+
+Each row in the team sidebar has a delete button, an X at its end: on a
+device with hover it shows when the row is hovered or focused, on touch it is
+always there. [HomeSidebar.tsx](../client/src/features/home/sidebar/HomeSidebar.tsx)
+asks for confirmation, sends one delete while it is pending, and on failure
+keeps the employee where it was and says so, so the owner can try again.
+
+- **One delete for both modes.** Home and the editor's workflow list call
+ `useAppStore.deleteWorkflow` ([store/useAppStore.ts](../client/src/store/useAppStore.ts)),
+ which deletes the saved workflow (`DELETE /api/database/workflows/{id}`,
+ the same handler as the `delete_workflow` WebSocket command).
+- **The server stops the employee first.** `delete_workflow_with_context_archival`
+ ([handlers.py](../server/services/workflow_storage/handlers.py)) calls
+ `stop_workflow_for_deletion` ([deletion.py](../server/services/workflow_storage/deletion.py)).
+ A generation that is live, paused, failed or still resetting, or a
+ Workspace controller, goes through Reset; a legacy local deployment is
+ cancelled. If that fails, or a Start slips in meanwhile, nothing is
+ deleted: the answer is `workflow_shutdown_failed` with the reason in
+ `detail`. An employee that never ran is deleted without connecting to
+ Temporal.
+- **Every tab forgets them.** After a successful delete, and on the
+ `workflow.deleted` broadcast in any tab, `forgetWorkflow` closes the
+ workflow if the editor has it open and drops it from the workflow list
+ and its query; `removeEmployee` ([data/employeeCache.ts](../client/src/features/home/data/employeeCache.ts))
+ drops the employee, goes back to Hire if their page was showing, and
+ closes their Workspace and notices. The broadcast is handled app-wide
+ (`WebSocketContext.tsx`), so this happens while Home is not showing too.
+ Reads still in flight are cancelled first, so a late answer cannot bring
+ the employee back; the next read asks the server. There is no client-side
+ list of deleted ids.
+- **Nothing replaces them.** Deleting the last workflow leaves the editor
+ empty until the owner chooses New or hires someone; the editor no longer
+ creates an Untitled workflow on its own.
+- **A late write cannot restore them.** Saving an existing workflow is an
+ update only (`save_workflow(..., require_existing=True)`): an editor's
+ save, a read's migration, or a Vertex agent's cloud tools that land after
+ the delete fail with `workflow_not_found` instead of writing the graph back.
+
### The orb
A 3D version of the logo drawn behind Home's content
@@ -296,7 +335,8 @@ the client's `HIRE_PAYLOAD_KEYS` must match, locked by
On the client ([genui/useHire.ts](../client/src/features/home/genui/useHire.ts))
every successful hire lands on the new employee's page, with a glow in the
-sidebar and a toast. The response's `warnings` show there once as the hire
+sidebar and a toast; the team list is then read back from the server rather
+than taking the summary the hire answered with. The response's `warnings` show there once as the hire
notice ("A few notes on {Name}'s setup", `hire/HireNotice.tsx`), until the
owner dismisses it or opens another view; `needs_ai` opens Connect an AI
model; every error code has plain words (`busy`: they are still being set
@@ -474,8 +514,9 @@ Workspace's task line stays on their other work.
### Turn on Talk and Apply
Both live in [handlers.py](../server/services/employees/handlers.py), run one
-at a time per employee, and answer with the employee's fresh summary, which
-the client puts in the team cache.
+at a time per employee, and answer with the employee's fresh summary.
+The client refreshes the employee queries after either outcome instead of
+merging that snapshot, which may already be stale when the response arrives.
- **`enable_employee_talk`** plans the line (`plan_talk_line`), adds it
through `apply_graph_additions` (one transaction; an editor with the
@@ -673,6 +714,7 @@ WebSocket requests (snake_case; failures come back as `success: false` with an
| `get_chat_messages` | `{session_id, limit?, all_generations?}` | `{messages}`, oldest first, each `{id, role, message, timestamp, run_key}`. Timestamps carry their UTC offset; `run_key` is the generation the row was written in. Without `all_generations`, only the latest generation's rows (none after a Reset; every row when the workflow was never started) |
| `list_approvals` | `{workflow_id?, status?, limit <= 100}` | `{approvals, counts, server_time}` |
| `decide_approval` | `{approval_id, decision, text?, subject?, decision_key}` | `{approval, will_send_on_resume}` |
+| `delete_workflow` | `{workflow_id}` | `{workflow_id, contexts_archived, context_archives_pending}`; `DELETE /api/database/workflows/{id}` is the same handler. Error `workflow_shutdown_failed` (with `detail`) when stopping the employee failed: nothing was deleted |
Broadcasts, all CloudEvents events broadcast directly (no Temporal
consumer; see [Event Framework](./event_framework.md#ui-only-lifecycle-events-broadcast-directly-never-through-emit));
@@ -680,9 +722,9 @@ every frame but `workflow_ops_apply` carries the whole envelope:
| Wire key | Type | Notes |
|---|---|---|
-| `employee_lifecycle` | `com.opencompany.employee.{hired,updated,removed}` | Subject is the workflow id; `updated` is coalesced to one per second per employee, except control changes and browser control changes (each agent step, and the wait for the owner), which go out at once |
+| `employee_lifecycle` | `com.opencompany.employee.{hired,updated,removed}` | Subject is the workflow id; `updated` is coalesced to one per second per employee, except control changes and browser control changes (each agent step, and the wait for the owner), which go out at once. Home refetches on `hired` and `updated` rather than taking the summary the event carries, which can already be out of date; `removed` drops the employee |
| `approval_lifecycle` | `com.opencompany.approval.{requested,decided,expired,cancelled}` | Identity only, never the message or the recipient |
-| `workflow_lifecycle` | gains `created` and `deleted` stages | So open editors refresh their workflow lists |
+| `workflow_lifecycle` | gains `created` and `deleted` stages | So open editors refresh their workflow lists. `deleted` also makes every tab forget the workflow and its employee (`forgetWorkflow`, see [Deleting an employee](#deleting-an-employee)) |
| `chat.updated` | `com.opencompany.chat.updated` | Sent after every chat insert and clear (`services/chat_thread.py`). Data `{workflow_id, session_id, role}`, identity only: `role` is null for a clear, `workflow_id` null for session `"default"`. Home's thread and the editor's chat pane refetch |
| `workflow_ops_apply` | `com.opencompany.workflow.ops.applied` | The frame is the event's flat data, `{workflow_id, caller_node_id, operations, persisted?}`, not the envelope. `persisted: true` marks a batch the server already saved (`apply_graph_additions`: Turn on Talk, the Agent Builder), whose ops carry the server's ids; editors adopt it without saving. See [Workflow Operations Protocol](./workflow_ops_protocol.md#persisted-batches) |
@@ -705,13 +747,19 @@ history). Talk and growing a saved employee: `tests/services/employees/`
`tests/services/test_graph_build.py`, `tests/services/test_graph_additions.py`,
`tests/services/test_graph_listeners.py`,
`tests/services/test_deployment_restart.py`,
-`tests/nodes/test_agent_builder_employee.py`. Client:
+`tests/nodes/test_agent_builder_employee.py`. Deleting:
+`tests/services/test_workflow_deletion_shutdown.py`,
+`tests/services/test_workflow_context_archive_outbox.py` (a late save or read
+cannot re-create a deleted workflow). Client:
`features/home/**/__tests__` (including `talk.test.tsx`, `thread.test.ts`,
`connectAI.test.tsx`), `app/__tests__`,
`contexts/__tests__/themePrePaint.test.ts`,
`contexts/__tests__/webSocketActions.test.tsx` (`chat.updated`, the editor
chat's rollback), `lib/__tests__/workflowOps.test.ts` and
-`hooks/__tests__/useWorkflowOpsListener.test.ts` (persisted batches).
+`hooks/__tests__/useWorkflowOpsListener.test.ts` (persisted batches),
+`store/__tests__/deleteWorkflow.test.ts`,
+`features/home/__tests__/homeSidebar.test.tsx` and `employeesRemount.test.tsx`
+(deleting), `lib/__tests__/debouncedInvalidate.test.ts`.
## Known gaps
@@ -761,7 +809,8 @@ chat's rollback), `lib/__tests__/workflowOps.test.ts` and
- A Dev editor holding unsaved edits made before a server-side change (Turn on
Talk, the Agent Builder) can still overwrite it on its next save, because
saves carry no revision check. Adopting persisted batches narrows the
- window.
+ window. Such a save can no longer bring back a deleted workflow, though:
+ saving an existing workflow is an update only.
- Pre-existing: with Temporal disabled, deployed chat triggers never fire,
and a canvas Run of a `chatTrigger` waits forever.
- An example workflow whose agent serves several triggers posts all of that