Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor: share CoS task socket updates (#5734)
Adam Eivy02276ff4bd43
diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxindex 82d3832bf8..ab93514819 100644--- a/client/src/components/apps/tabs/IssuesTab.jsx+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -10,11 +10,11 @@ import Pill from '../../ui/Pill';import toast from '../../ui/Toast';import ProviderModelSelector from '../../ProviderModelSelector';import { useThemeContext } from '../../ThemeContext';+import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';import useProviderModels from '../../../hooks/useProviderModels';import { chipColors } from '../../../lib/chipContrast';import { isProcessProvider } from '../../../utils/providers';import * as api from '../../../services/api';-import socket from '../../../services/socket';import { timeAgo } from '../../../utils/formatters';const FORGE_LABEL = { github: 'GitHub', gitlab: 'GitLab' };@@ -257,90 +257,52 @@ export default function IssuesTab({ appId, appName }) {setUnassignedOnly(false);}, [appId]);- useEffect(() => {- const subscribe = () => socket.emit('cos:subscribe');- if (socket.connected) subscribe();- socket.on('connect', subscribe);-- const applyTaskUpdate = (task) => {- if (!task?.id) return;- const nextStatus = runStatusForTask(task.status);- if (!nextStatus) return;-- const currentRuns = runsRef.current;- const nextRuns = { ...currentRuns };- const transitions = [];-- for (const [key, rawRun] of Object.entries(currentRuns)) {- const { action, issueNumber } = parseRunKey(key);- const spec = ISSUE_ACTIONS[action];- if (!spec) continue;- const run = typeof rawRun === 'string' ? { status: rawRun } : rawRun;- // Before the POST resolves there is no task id to match on, so fall back- // to the durable per-action target the server stamped. Reading THIS- // action's key is what keeps a claim's events off a replan's row.- const matchesTask = run.taskId === task.id || (- !run.taskId && task.metadata?.app === appId &&- String(task.metadata?.[spec.targetKey]) === issueNumber- );- if (!matchesTask) continue;-- const currentStatus = run.status || 'queuing';- if ((RUN_STATUS_RANK[nextStatus] ?? 0) < (RUN_STATUS_RANK[currentStatus] ?? 0)) continue;- if (run.taskId === task.id && currentStatus === nextStatus) continue;-- nextRuns[key] = { ...run, taskId: run.taskId || task.id, status: nextStatus };- transitions.push({ action, issueNumber, from: currentStatus, to: nextStatus });- }+ const applyTaskUpdate = useCallback((task) => {+ if (!task?.id) return;+ const nextStatus = runStatusForTask(task.status);+ if (!nextStatus) return;++ const currentRuns = runsRef.current;+ const nextRuns = { ...currentRuns };+ const transitions = [];++ for (const [key, rawRun] of Object.entries(currentRuns)) {+ const { action, issueNumber } = parseRunKey(key);+ const spec = ISSUE_ACTIONS[action];+ if (!spec) continue;+ const run = typeof rawRun === 'string' ? { status: rawRun } : rawRun;+ // Before the POST resolves there is no task id to match on, so fall back+ // to the durable per-action target the server stamped. Reading THIS+ // action's key is what keeps a claim's events off a replan's row.+ const matchesTask = run.taskId === task.id || (+ !run.taskId && task.metadata?.app === appId &&+ String(task.metadata?.[spec.targetKey]) === issueNumber+ );+ if (!matchesTask) continue;++ const currentStatus = run.status || 'queuing';+ if ((RUN_STATUS_RANK[nextStatus] ?? 0) < (RUN_STATUS_RANK[currentStatus] ?? 0)) continue;+ if (run.taskId === task.id && currentStatus === nextStatus) continue;++ nextRuns[key] = { ...run, taskId: run.taskId || task.id, status: nextStatus };+ transitions.push({ action, issueNumber, from: currentStatus, to: nextStatus });+ }- if (transitions.length === 0) return;- replaceRuns(() => nextRuns);+ if (transitions.length === 0) return;+ replaceRuns(() => nextRuns);- for (const { action, issueNumber, from, to } of transitions) {- if (to === from) continue;- const message = ISSUE_ACTIONS[action].transition(issueNumber, to);- if (!message) continue;- if (to === 'active') toast(message, { icon: '▶️' });- else if (to === 'completed') toast.success(message);- else if (to === 'blocked') toast.error(message);- }- };-- const handleTaskChanged = (data) => applyTaskUpdate(data?.task);- const handleTaskListChanged = (data) => {- for (const task of data?.tasks || []) applyTaskUpdate(task);- };- const handleTaskCompleted = (data) => {- for (const task of data?.tasks || []) applyTaskUpdate(task);- };- const handleAgentSpawned = (agent) => {- if (agent?.taskId) applyTaskUpdate({ id: agent.taskId, status: 'in_progress' });- };- const handleAgentCompleted = (agent) => {- // A failed agent can be requeued or blocked by its completion path, so- // only the success signal is safe as an early terminal hint. The task- // lifecycle event below remains authoritative for all outcomes.- if (agent?.taskId && agent.result?.success === true) {- applyTaskUpdate({ id: agent.taskId, status: 'completed' });- }- };-- socket.on('cos:tasks:changed', handleTaskChanged);- socket.on('cos:tasks:user:changed', handleTaskListChanged);- socket.on('cos:tasks:user:completed', handleTaskCompleted);- socket.on('cos:agent:spawned', handleAgentSpawned);- socket.on('cos:agent:completed', handleAgentCompleted);-- return () => {- socket.off('connect', subscribe);- socket.off('cos:tasks:changed', handleTaskChanged);- socket.off('cos:tasks:user:changed', handleTaskListChanged);- socket.off('cos:tasks:user:completed', handleTaskCompleted);- socket.off('cos:agent:spawned', handleAgentSpawned);- socket.off('cos:agent:completed', handleAgentCompleted);- };+ for (const { action, issueNumber, from, to } of transitions) {+ if (to === from) continue;+ const message = ISSUE_ACTIONS[action].transition(issueNumber, to);+ if (!message) continue;+ if (to === 'active') toast(message, { icon: '▶️' });+ else if (to === 'completed') toast.success(message);+ else if (to === 'blocked') toast.error(message);+ }}, [appId, replaceRuns]);+ useCosTaskUpdates(applyTaskUpdate);+const load = useCallback(async () => {const generation = requestRef.current + 1;requestRef.current = generation;diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsxindex c995b7af6e..6988d014da 100644--- a/client/src/components/apps/tabs/IssuesTab.test.jsx+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx@@ -180,6 +180,57 @@ describe('IssuesTab', () => {expect(await screen.findByRole('link', { name: /Completed/ })).toBeInTheDocument();});+ it('does not treat a failed agent completion as a completed task', async () => {+ await renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));+ expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();++ act(() => socketHandlers.get('cos:agent:completed')({+ taskId: 'task-1', result: { success: false },+ }));++ expect(screen.getByRole('link', { name: /Queued/ })).toBeInTheDocument();+ expect(screen.queryByRole('link', { name: /Completed/ })).not.toBeInTheDocument();+ });++ it('applies every task from a user task-list update', async () => {+ const SECOND_ISSUE = {+ ...ISSUE,+ number: 43,+ title: 'Sync conflict',+ url: 'https://github.com/acme/widget/issues/43',+ };+ api.getAppIssues.mockResolvedValue(okPayload([ISSUE, SECOND_ISSUE]));+ api.createSlashdoTask+ .mockResolvedValueOnce({ id: 'task-1' })+ .mockResolvedValueOnce({ id: 'task-2' });+ await renderTab();++ const claimButtons = await screen.findAllByRole('button', { name: /Claim/ });+ fireEvent.click(claimButtons[0]);+ fireEvent.click(claimButtons[1]);+ await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalledTimes(2));++ act(() => socketHandlers.get('cos:tasks:user:changed')({+ tasks: [+ { id: 'task-1', status: 'completed' },+ { id: 'task-2', status: 'completed' },+ ],+ }));++ await waitFor(() => expect(screen.getAllByRole('link', { name: /Completed/ })).toHaveLength(2));+ });++ it('removes every CoS socket listener when unmounted', async () => {+ const listenerCountBeforeMount = socketHandlers.size;+ const { unmount } = await renderTab();++ expect(socketHandlers.size).toBe(listenerCountBeforeMount + 6);+ unmount();+ expect(socketHandlers.size).toBe(listenerCountBeforeMount);+ });+it('does not lose an active socket update that arrives before the POST response', async () => {let resolveClaim;api.createSlashdoTask.mockImplementation(() => new Promise(resolve => { resolveClaim = resolve; }));diff --git a/client/src/components/apps/tabs/PullRequestsTab.jsx b/client/src/components/apps/tabs/PullRequestsTab.jsxindex 0d7a828199..19861a811f 100644--- a/client/src/components/apps/tabs/PullRequestsTab.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.jsx@@ -8,8 +8,8 @@ import BrailleSpinner from '../../BrailleSpinner';import Banner from '../../ui/Banner';import Pill from '../../ui/Pill';import toast from '../../ui/Toast';+import { useCosTaskUpdates } from '../../../hooks/useCosTaskUpdates';import * as api from '../../../services/api';-import socket from '../../../services/socket';import { timeAgo } from '../../../utils/formatters';const FORGE_LABEL = { github: 'GitHub', gitlab: 'GitLab' };@@ -110,61 +110,30 @@ export default function PullRequestsTab({ appId, appName }) {setActions({});}, [appId]);- useEffect(() => {- const subscribe = () => socket.emit('cos:subscribe');- if (socket.connected) subscribe();- socket.on('connect', subscribe);-- const applyTaskUpdate = task => {- if (!task?.id) return;- const nextStatus = actionStatusForTask(task.status);- if (!nextStatus) return;-- replaceActions(current => {- const next = { ...current };- let changed = false;- for (const [number, action] of Object.entries(current)) {- const matches = action.taskId === task.id || (- !action.taskId- && task.metadata?.app === appId- && Number(task.metadata?.reviewLoopPRNumber) === Number(number)- );- if (!matches || actionRank(nextStatus) < actionRank(action.status)) continue;- next[number] = { ...action, taskId: action.taskId || task.id, status: nextStatus };- changed = true;- }- return changed ? next : current;- });- };-- const handleTaskChanged = event => applyTaskUpdate(event?.task);- const handleTaskListChanged = event => (event?.tasks || []).forEach(applyTaskUpdate);- const handleTaskCompleted = event => (event?.tasks || []).forEach(applyTaskUpdate);- const handleAgentSpawned = agent => {- if (agent?.taskId) applyTaskUpdate({ id: agent.taskId, status: 'in_progress' });- };- const handleAgentCompleted = agent => {- if (agent?.taskId && agent.result?.success === true) {- applyTaskUpdate({ id: agent.taskId, status: 'completed' });+ const applyTaskUpdate = useCallback(task => {+ if (!task?.id) return;+ const nextStatus = actionStatusForTask(task.status);+ if (!nextStatus) return;++ replaceActions(current => {+ const next = { ...current };+ let changed = false;+ for (const [number, action] of Object.entries(current)) {+ const matches = action.taskId === task.id || (+ !action.taskId+ && task.metadata?.app === appId+ && Number(task.metadata?.reviewLoopPRNumber) === Number(number)+ );+ if (!matches || actionRank(nextStatus) < actionRank(action.status)) continue;+ next[number] = { ...action, taskId: action.taskId || task.id, status: nextStatus };+ changed = true;}- };-- socket.on('cos:tasks:changed', handleTaskChanged);- socket.on('cos:tasks:user:changed', handleTaskListChanged);- socket.on('cos:tasks:user:completed', handleTaskCompleted);- socket.on('cos:agent:spawned', handleAgentSpawned);- socket.on('cos:agent:completed', handleAgentCompleted);-- return () => {- socket.off('connect', subscribe);- socket.off('cos:tasks:changed', handleTaskChanged);- socket.off('cos:tasks:user:changed', handleTaskListChanged);- socket.off('cos:tasks:user:completed', handleTaskCompleted);- socket.off('cos:agent:spawned', handleAgentSpawned);- socket.off('cos:agent:completed', handleAgentCompleted);- };+ return changed ? next : current;+ });}, [appId, replaceActions]);+ useCosTaskUpdates(applyTaskUpdate);+const load = useCallback(async () => {const generation = requestRef.current + 1;requestRef.current = generation;diff --git a/client/src/components/apps/tabs/PullRequestsTab.test.jsx b/client/src/components/apps/tabs/PullRequestsTab.test.jsxindex 82b3ab1e43..af03f0bf03 100644--- a/client/src/components/apps/tabs/PullRequestsTab.test.jsx+++ b/client/src/components/apps/tabs/PullRequestsTab.test.jsx@@ -123,6 +123,57 @@ describe('PullRequestsTab', () => {expect(await screen.findByRole('link', { name: /Completed/ })).toBeInTheDocument();});+ it('does not treat a failed agent completion as a completed action', async () => {+ await renderTab();++ fireEvent.click(await screen.findByRole('button', { name: /Resolve & merge/ }));+ expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();++ act(() => socketHandlers.get('cos:agent:completed')({+ taskId: 'task-1', result: { success: false },+ }));++ expect(screen.getByRole('link', { name: /Queued/ })).toBeInTheDocument();+ expect(screen.queryByRole('link', { name: /Completed/ })).not.toBeInTheDocument();+ });++ it('applies every task from a user task-list update', async () => {+ const SECOND_PULL_REQUEST = {+ ...PULL_REQUEST,+ number: 18,+ title: 'Repair the sync path',+ url: 'https://github.com/acme/widget/pull/18',+ };+ api.getAppPullRequests.mockResolvedValue(okPayload([PULL_REQUEST, SECOND_PULL_REQUEST]));+ api.resolveAppPullRequest+ .mockResolvedValueOnce({ task: { id: 'task-1', status: 'pending' }, duplicate: false })+ .mockResolvedValueOnce({ task: { id: 'task-2', status: 'pending' }, duplicate: false });+ await renderTab();++ const resolveButtons = await screen.findAllByRole('button', { name: /Resolve & merge/ });+ fireEvent.click(resolveButtons[0]);+ fireEvent.click(resolveButtons[1]);+ await waitFor(() => expect(api.resolveAppPullRequest).toHaveBeenCalledTimes(2));++ act(() => socketHandlers.get('cos:tasks:user:changed')({+ tasks: [+ { id: 'task-1', status: 'completed' },+ { id: 'task-2', status: 'completed' },+ ],+ }));++ await waitFor(() => expect(screen.getAllByRole('link', { name: /Completed/ })).toHaveLength(2));+ });++ it('removes every CoS socket listener when unmounted', async () => {+ const listenerCountBeforeMount = socketHandlers.size;+ const { unmount } = await renderTab();++ expect(socketHandlers.size).toBe(listenerCountBeforeMount + 6);+ unmount();+ expect(socketHandlers.size).toBe(listenerCountBeforeMount);+ });+it('hydrates an active server-side resolve action without offering another button', async () => {api.getAppPullRequests.mockResolvedValue(okPayload([{...PULL_REQUEST,diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 9b45530d6a..1e5ed4ef2d 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -77,6 +77,7 @@ grep -i "what you want to do" client/src/hooks/README.md| Hook | Purpose | Use when ||---|---|---|+| `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. || `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. || `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. || `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 20b09c4d0d..29985fe422 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -144,6 +144,7 @@ export { default as useCatalogTypes } from './useCatalogTypes.jsx';export * from './useCatalogTypes.jsx';// === Sockets & lifecycle ===+export * from './useCosTaskUpdates.js';export * from './usePrevious.js';export * from './useShellSession.js';export * from './useSocket.js';diff --git a/client/src/hooks/useCosTaskUpdates.js b/client/src/hooks/useCosTaskUpdates.jsnew file mode 100644index 0000000000..4a93e0f516--- /dev/null+++ b/client/src/hooks/useCosTaskUpdates.js@@ -0,0 +1,53 @@+import { useEffect, useRef } from 'react';+import socket from '../services/socket';++/**+ * Subscribes a surface to the shared CoS task lifecycle and forwards each task+ * update to its current reducer without resubscribing on ordinary rerenders.+ */+export function useCosTaskUpdates(onTaskUpdate) {+ const onTaskUpdateRef = useRef(onTaskUpdate);+ onTaskUpdateRef.current = onTaskUpdate;++ useEffect(() => {+ const subscribe = () => socket.emit('cos:subscribe');+ const emitTaskUpdate = task => {+ if (task) onTaskUpdateRef.current?.(task);+ };+ const handleTaskChanged = event => emitTaskUpdate(event?.task);+ const handleTaskListChanged = event => {+ for (const task of event?.tasks || []) emitTaskUpdate(task);+ };+ const handleTaskCompleted = event => {+ for (const task of event?.tasks || []) emitTaskUpdate(task);+ };+ const handleAgentSpawned = agent => {+ if (agent?.taskId) emitTaskUpdate({ id: agent.taskId, status: 'in_progress' });+ };+ const handleAgentCompleted = agent => {+ // A failed agent can be requeued or blocked by its completion path, so+ // only the success signal is safe as an early terminal hint. The task+ // lifecycle event remains authoritative for all outcomes.+ if (agent?.taskId && agent.result?.success === true) {+ emitTaskUpdate({ id: agent.taskId, status: 'completed' });+ }+ };++ subscribe();+ socket.on('connect', subscribe);+ socket.on('cos:tasks:changed', handleTaskChanged);+ socket.on('cos:tasks:user:changed', handleTaskListChanged);+ socket.on('cos:tasks:user:completed', handleTaskCompleted);+ socket.on('cos:agent:spawned', handleAgentSpawned);+ socket.on('cos:agent:completed', handleAgentCompleted);++ return () => {+ socket.off('connect', subscribe);+ socket.off('cos:tasks:changed', handleTaskChanged);+ socket.off('cos:tasks:user:changed', handleTaskListChanged);+ socket.off('cos:tasks:user:completed', handleTaskCompleted);+ socket.off('cos:agent:spawned', handleAgentSpawned);+ socket.off('cos:agent:completed', handleAgentCompleted);+ };+ }, []);+}