Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(workspace): Hand back gives back the screen that was taken
trohitg9d626bc8b466
diff --git a/client/src/components/browser/BrowserWorkspace.tsx b/client/src/components/browser/BrowserWorkspace.tsxindex 9ee2c5d7..800ba5f6 100644--- a/client/src/components/browser/BrowserWorkspace.tsx+++ b/client/src/components/browser/BrowserWorkspace.tsx@@ -115,20 +115,23 @@ function BrowserSessionView({ workflowId, nodeId, visible, agentName, ref }: { wclaimRef.current?.(granted);claimRef.current = null;}, []);- useImperativeHandle(ref, () => ({- claim: () => new Promise<boolean>((resolve) => {- if (controlRef.current) { resolve(true); return; }- const socket = socketRef.current;- if (!socket || socket.readyState !== WebSocket.OPEN) { resolve(false); return; }- answerClaim(false);- claimRef.current = resolve;- setError(''); setTakingControl(true);- socket.send(JSON.stringify({ type: 'control_request', force: true }));- }),- release: () => {+ useImperativeHandle(ref, () => {+ // Hiding the view already gives control back, so after that there is nothing to do.+ const giveBack = () => {if (controlRef.current) send({ type: 'control_release' });- },- }), [answerClaim, send, setError]);+ };+ return {+ claim: () => new Promise<(() => void) | null>((resolve) => {+ if (controlRef.current) { resolve(giveBack); return; }+ const socket = socketRef.current;+ if (!socket || socket.readyState !== WebSocket.OPEN) { resolve(null); return; }+ answerClaim(false);+ claimRef.current = (granted) => resolve(granted ? giveBack : null);+ setError(''); setTakingControl(true);+ socket.send(JSON.stringify({ type: 'control_request', force: true }));+ }),+ };+ }, [answerClaim, send, setError]);useEffect(() => {if (!isReady) { setPhase('connecting'); return; }@@ -167,7 +170,8 @@ function BrowserSessionView({ workflowId, nodeId, visible, agentName, ref }: { wconst message = JSON.parse(event.data);if (message.type === 'attached') setPhase(message.running ? 'live' : 'idle');if (message.type === 'state') { setState(message); if (!terminalStreamError) setPhase('live'); setTakingControl(false); }- if (message.type === 'idle') { streamEpoch += 1; setPhase('idle'); setState({ state: 'idle' }); setHasFrame(false); frameRef.current = null; setAgentAction(null); setDialog(null); }+ // A stopped browser answers every request, a control request too, with `idle`.+ if (message.type === 'idle') { streamEpoch += 1; setPhase('idle'); setState({ state: 'idle' }); setHasFrame(false); frameRef.current = null; setAgentAction(null); setDialog(null); setTakingControl(false); answerClaim(false); }if (message.type === 'page') { setAddress(message.url || ''); setPageUrl(message.url || ''); }if (message.type === 'agent_action') {// Drawn on the picture shown: none before the first one, none for another tab.diff --git a/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx b/client/src/components/browser/__tests__/BrowserWorkspace.test.tsxindex fc002180..b59f660e 100644--- a/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx+++ b/client/src/components/browser/__tests__/BrowserWorkspace.test.tsx@@ -1,5 +1,7 @@+import { createRef } from 'react';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { SurfaceControl } from '../../workspace/surface';const { actions } = vi.hoisted(() => ({ actions: { isReady: true, sendRequest: vi.fn() } }));vi.mock('@/contexts/WebSocketContext', () => ({ useWebSocketActions: () => actions }));@@ -241,6 +243,31 @@ describe('browser frame and input lifecycle boundaries', () => {fireEvent.keyDown(surface, { key: 'a', code: 'KeyA' });expect(socket.sent).toHaveLength(count);});+ it('answers the Workspace’s Take over no while the browser is stopped', async () => {+ const control = createRef<SurfaceControl>();+ render(<BrowserWorkspace workflowId="wf" nodes={nodes} ref={control} />);+ const socket = MockSocket.instances[0];+ act(() => { socket.open(); socket.message({ type: 'attached', running: false }); socket.message({ type: 'idle', reason: 'not running' }); });+ let claim!: Promise<(() => void) | null>;+ act(() => { claim = control.current!.claim(); });+ expect(socket.sent.at(-1)).toEqual({ type: 'control_request', force: true });+ // A stopped browser answers every request with `idle`.+ act(() => socket.message({ type: 'idle', reason: 'not running' }));+ await expect(claim).resolves.toBeNull();+ });+ it('gives back the control the Workspace’s Take over was granted', async () => {+ const control = createRef<SurfaceControl>();+ render(<BrowserWorkspace workflowId="wf" nodes={nodes} ref={control} />);+ const socket = MockSocket.instances[0];+ act(() => { socket.open(); socket.message({ type: 'state', state: 'agent' }); });+ let claim!: Promise<(() => void) | null>;+ act(() => { claim = control.current!.claim(); });+ act(() => { socket.message({ type: 'control', granted: true }); socket.message({ type: 'state', state: 'user', controller: 'you' }); });+ const giveBack = await claim;+ expect(giveBack).toBeTypeOf('function');+ act(() => giveBack!());+ expect(socket.sent.at(-1)).toEqual({ type: 'control_release' });+ });it('cancels a pending takeover when the document becomes hidden', () => {render(<BrowserWorkspace workflowId="wf" nodes={nodes} />);const socket = MockSocket.instances[0];diff --git a/client/src/components/mobile/MobileWorkspace.tsx b/client/src/components/mobile/MobileWorkspace.tsxindex f26b5b90..4a49ac87 100644--- a/client/src/components/mobile/MobileWorkspace.tsx+++ b/client/src/components/mobile/MobileWorkspace.tsx@@ -228,9 +228,9 @@ function MobileSession({ workflowId, nodeId, visible, isCurrentSession, canvasNoawait mobileRequest(`${path}/resume`, {});}};+ const giveBack = () => { void handBack().catch((cause) => { if (active.current) setError(cause instanceof Error ? cause.message : 'Could not hand the phone back.'); }); };useImperativeHandle(ref, () => ({- claim: () => takeControl().catch(() => false),- release: () => { void handBack().catch((cause) => { if (active.current) setError(cause instanceof Error ? cause.message : 'Could not hand the phone back.'); }); },+ claim: async () => ((await takeControl().catch(() => false)) ? giveBack : null),}));// The phone's screen as a PNG in the workspace, then on the Canvas board.const screenshot = () => perform('saving a screenshot', async () => {diff --git a/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx b/client/src/components/mobile/__tests__/MobileWorkspace.test.tsxindex 348d7677..987fe7cc 100644--- a/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx+++ b/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx@@ -1,6 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';+import { createRef } from 'react';+import type { SurfaceControl } from '../../workspace/surface';import MobileWorkspace from '../MobileWorkspace';import { mobilePoint, mobileRequest } from '../api';@@ -356,6 +358,28 @@ describe('Mobile Workspace', () => {view.rerender(<MobileWorkspace workflowId="flow" nodes={nodes} visible={false} />);await waitFor(() => expect(fetchMock.mock.calls.some(([url, options]) => url.endsWith('/release') && JSON.parse(options.body).epoch === 7)).toBe(true));});++ it('gives the phone back from the Workspace’s Take over after its view went away', async () => {+ snapshot.running = true;+ fetchMock.mockImplementation(async (url: string) => {+ if (url.endsWith('/takeover')) {+ snapshot = { ...snapshot, controller: 'viewer:server-hash', control_state: 'human', epoch: 7 };+ return json({ owner: 'viewer:server-hash', epoch: 7 });+ }+ return json(url.endsWith('/doctor') ? ready : snapshot);+ });+ const control = createRef<SurfaceControl>();+ const view = render(<MobileWorkspace workflowId="flow" nodes={nodes} ref={control} />);+ await screen.findByRole('button', { name: 'Use phone' });+ let giveBack: (() => void) | null = null;+ await act(async () => { giveBack = await control.current!.claim(); });+ expect(giveBack).toBeTypeOf('function');+ // The dock moved to another tab: the view lets the phone go, and the task it took it from still waits.+ view.unmount();+ await waitFor(() => expect(fetchMock.mock.calls.some(([url, options]) => url.endsWith('/release') && JSON.parse(options.body).resume === false)).toBe(true));+ giveBack!();+ await waitFor(() => expect(fetchMock.mock.calls.some(([url]) => url.endsWith('/resume'))).toBe(true));+ });});describe('mobile transport boundaries', () => {diff --git a/client/src/components/workspace/surface.ts b/client/src/components/workspace/surface.tsindex dc3260de..486d6f24 100644--- a/client/src/components/workspace/surface.ts+++ b/client/src/components/workspace/surface.ts@@ -1,10 +1,12 @@/*** What a Workspace surface (Browser, Mobile) lets the dock do for Take over:- * take its screen for the owner, and give it back.+ * take its screen for the owner.*/export interface SurfaceControl {- /** Take the screen; true once the server granted it. */- claim: () => Promise<boolean>;- /** Give it back, letting the employee's waiting work on it go on. */- release: () => void;+ /** Take the screen. Once the server granted it, resolves to the way to give+ * that screen back, letting the employee's waiting work on it go on; null+ * when it was refused. Giving back works after this view went away (the+ * dock moved to another tab or employee), so Hand back always gives back+ * the screen that was taken. */+ claim: () => Promise<(() => void) | null>;}diff --git a/client/src/features/home/__tests__/workspace.test.tsx b/client/src/features/home/__tests__/workspace.test.tsxindex 1c582761..d41fd2a9 100644--- a/client/src/features/home/__tests__/workspace.test.tsx+++ b/client/src/features/home/__tests__/workspace.test.tsx@@ -40,13 +40,14 @@ vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({}));vi.mock('../../../app/useShellActions', () => ({ enterDev: vi.fn() }));-// The browser's Take over handle (components/workspace/surface.ts).-const screenControl = vi.hoisted(() => ({ claim: vi.fn(), release: vi.fn() }));+// The browser's Take over handle (components/workspace/surface.ts), and the+// way to give back what a claim took.+const screenControl = vi.hoisted(() => ({ claim: vi.fn(), giveBack: vi.fn() }));vi.mock('@/components/browser/BrowserWorkspace', async () => {const { useImperativeHandle } = await import('react');return {- default: function Browser({ workflowId, nodes, visible, ref }: { workflowId: string; nodes: { node_id: string; label: string }[]; visible: boolean; ref?: import('react').Ref<typeof screenControl> }) {- useImperativeHandle(ref, () => screenControl);+ default: function Browser({ workflowId, nodes, visible, ref }: { workflowId: string; nodes: { node_id: string; label: string }[]; visible: boolean; ref?: import('react').Ref<{ claim: typeof screenControl.claim }> }) {+ useImperativeHandle(ref, () => ({ claim: screenControl.claim }));return (<div data-testid="browser-workspace" data-workflow={workflowId} data-visible={String(visible)}>{nodes.length ? nodes.map((node) => <span key={node.node_id}>{node.label}</span>) : 'No Browser node in this workflow'}@@ -223,11 +224,11 @@ describe('WorkspaceDock', () => {});it('takes over the screen and stops the employee, and hands both back', async () => {- screenControl.claim.mockReset().mockResolvedValue(true);- screenControl.release.mockReset();+ screenControl.claim.mockReset().mockResolvedValue(screenControl.giveBack);+ screenControl.giveBack.mockReset();actions.pauseWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'paused', revision: 5 }, 'w1'));actions.resumeWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 6 }, 'w1'));- useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeover: null });+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeovers: {} });renderWith([employee({ control: normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 4 }, 'w1') })]);await userEvent.click(screen.getByRole('button', { name: 'Take over' }));// The screen first, so the employee never acts on it again, then Stop.@@ -235,20 +236,62 @@ describe('WorkspaceDock', () => {expect(actions.pauseWorkflow).toHaveBeenCalledWith('w1', 4);expect(screenControl.claim.mock.invocationCallOrder[0]).toBeLessThan(actions.pauseWorkflow.mock.invocationCallOrder[0]);expect(await screen.findByText('You’re in control · Maya is waiting')).toBeInTheDocument();- expect(useHomeStore.getState().takeover).toEqual({ workflowId: 'w1', stopped: true });+ expect(useHomeStore.getState().takeovers).toEqual({ w1: { stopped: true, giveBack: screenControl.giveBack } });await userEvent.click(screen.getByRole('button', { name: 'Hand back' }));- expect(screenControl.release).toHaveBeenCalledOnce();+ expect(screenControl.giveBack).toHaveBeenCalledOnce();expect(actions.resumeWorkflow).toHaveBeenCalledOnce();expect(screen.queryByText('You’re in control · Maya is waiting')).toBeNull();- expect(useHomeStore.getState().takeover).toBeNull();+ expect(useHomeStore.getState().takeovers).toEqual({});+ });++ it('hands back the screen that was taken, whichever tab the dock shows', async () => {+ screenControl.claim.mockReset().mockResolvedValue(screenControl.giveBack);+ screenControl.giveBack.mockReset();+ actions.pauseWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'paused', revision: 5 }, 'w1'));+ actions.resumeWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 6 }, 'w1'));+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeovers: {} });+ renderWith([employee({ control: normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 4 }, 'w1') })]);+ await userEvent.click(screen.getByRole('button', { name: 'Take over' }));+ expect(await screen.findByText('You’re in control · Maya is waiting')).toBeInTheDocument();+ // The taken screen's view goes with its tab.+ await userEvent.click(screen.getByRole('tab', { name: 'Canvas' }));+ expect(screen.queryByTestId('browser-workspace')).toBeNull();+ await userEvent.click(screen.getByRole('button', { name: 'Hand back' }));+ expect(screenControl.giveBack).toHaveBeenCalledOnce();+ expect(actions.resumeWorkflow).toHaveBeenCalledWith('w1', 4);+ });++ it('keeps each employee’s Take over while the dock shows another', async () => {+ const giveBackMaya = vi.fn();+ const giveBackLeo = vi.fn();+ screenControl.claim.mockReset().mockResolvedValueOnce(giveBackMaya).mockResolvedValueOnce(giveBackLeo);+ actions.pauseWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'paused', revision: 5 }, 'w1'));+ actions.resumeWorkflow.mockReset().mockResolvedValue(normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 6 }, 'w1'));+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeovers: {} });+ renderWith([+ employee({ control: normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 4 }, 'w1') }),+ employee({ workflow_id: 'w2', name: 'Leo', control: normalizeWorkflowControlStatus({ generation: 1, state: 'running', revision: 9 }, 'w2') }),+ ]);+ await userEvent.click(screen.getByRole('button', { name: 'Take over' }));+ expect(await screen.findByText('You’re in control · Maya is waiting')).toBeInTheDocument();+ act(() => useHomeStore.getState().showEmployee('w2'));+ await userEvent.click(await screen.findByRole('button', { name: 'Take over' }));+ expect(await screen.findByText('You’re in control · Leo is waiting')).toBeInTheDocument();++ act(() => useHomeStore.getState().showEmployee('w1'));+ await userEvent.click(await screen.findByRole('button', { name: 'Hand back' }));+ expect(giveBackMaya).toHaveBeenCalledOnce();+ expect(giveBackLeo).not.toHaveBeenCalled();+ expect(actions.resumeWorkflow).toHaveBeenCalledWith('w1', 4);+ expect(useHomeStore.getState().takeovers).toEqual({ w2: { stopped: true, giveBack: giveBackLeo } });});it('leaves a stopped employee stopped, and stops no one when the screen is refused', async () => {- screenControl.claim.mockReset().mockResolvedValue(true);+ screenControl.claim.mockReset().mockResolvedValue(screenControl.giveBack);actions.pauseWorkflow.mockReset();actions.resumeWorkflow.mockReset();- useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeover: null });+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeovers: {} });renderWith([employee({ status: 'paused' })]);await userEvent.click(screen.getByRole('button', { name: 'Take over' }));expect(await screen.findByText('You’re in control · Maya is waiting')).toBeInTheDocument();@@ -256,14 +299,14 @@ describe('WorkspaceDock', () => {expect(actions.pauseWorkflow).not.toHaveBeenCalled();expect(actions.resumeWorkflow).not.toHaveBeenCalled();- screenControl.claim.mockResolvedValue(false);+ screenControl.claim.mockResolvedValue(null);await userEvent.click(screen.getByRole('button', { name: 'Take over' }));expect(actions.pauseWorkflow).not.toHaveBeenCalled();expect(screen.queryByText('You’re in control · Maya is waiting')).toBeNull();});it('offers no Take over on the Canvas tab', () => {- useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'board', takeover: null });+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'board', takeovers: {} });renderWith([employee({ canvas_node_id: null })]);expect(screen.queryByRole('button', { name: 'Take over' })).toBeNull();});@@ -359,7 +402,7 @@ describe('Workspace timeline', () => {beforeEach(() => {steps = STEPS;answerSteps();- useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeover: null });+ useHomeStore.setState({ workspaceOpen: true, workspaceTab: 'browser', takeovers: {} });});it('lists what the employee did, coloured by surface, and follows the newest step', async () => {diff --git a/client/src/features/home/state/homeStore.ts b/client/src/features/home/state/homeStore.tsindex d683423e..e7c7087b 100644--- a/client/src/features/home/state/homeStore.ts+++ b/client/src/features/home/state/homeStore.ts@@ -34,6 +34,14 @@ export interface GuideState {pendingDraft: boolean;}+/** An employee's screen the owner took (Take over). */+export interface Takeover {+ /** Take over stopped them, so Hand back resumes them. */+ stopped: boolean;+ /** Gives back the screen that was taken (components/workspace/surface.ts). */+ giveBack: () => void;+}+// View ids, not node types: the Canvas tab is 'board' so no id reads as the// `canvas` node type (tests/test_frontend_no_node_type_copies.py).const WORKSPACE_TABS = ['browser', 'board', 'android'] as const;@@ -134,9 +142,9 @@ interface HomeState {/** A Canvas item to show (a reply's document card); the nonce lets the* same one be asked for again. */workspaceFocus: WorkspaceFocus | null;- /** The owner took an employee's screen from the Workspace (Take over);- * `stopped`: Take over stopped them, so Hand back resumes them. */- takeover: { workflowId: string; stopped: boolean } | null;+ /** The employees whose screen the owner took from the Workspace (Take+ * over), by workflow id. */+ takeovers: Record<string, Takeover>;/** The Welcome guide (onboarding/WelcomeGuide). */guide: GuideState;/** New hires on their first day, by workflow id. */@@ -160,7 +168,8 @@ interface HomeState {setWorkspaceTab: (tab: WorkspaceTab) => void;/** Clamped to 360px .. the window less 420px; ends Expand. */setWorkspaceWidth: (px: number) => void;- setTakeover: (takeover: HomeState['takeover']) => void;+ /** null: handed back. */+ setTakeover: (workflowId: string, takeover: Takeover | null) => void;toggleWorkspaceWide: () => void;/** Open the Workspace on the Canvas tab, at an item and version of an* employee's board. */@@ -201,7 +210,7 @@ export const useHomeStore = create<HomeState>((set, get) => ({workspaceWide: false,workspaceFor: null,workspaceFocus: null,- takeover: null,+ takeovers: {},guide: { open: false, step: 'welcome', furthest: 0, checked: false, provider: null, pendingDraft: false },firstDays: {},@@ -251,7 +260,13 @@ export const useHomeStore = create<HomeState>((set, get) => ({set({ workspaceOpen: false });saveWorkspacePrefs(get());},- setTakeover: (takeover) => set({ takeover }),+ setTakeover: (workflowId, takeover) =>+ set((state) => {+ const takeovers = { ...state.takeovers };+ if (takeover) takeovers[workflowId] = takeover;+ else delete takeovers[workflowId];+ return { takeovers };+ }),setWorkspaceTab: (tab) => {set({ workspaceTab: tab });saveWorkspacePrefs(get());diff --git a/client/src/features/home/workspace/takeover.ts b/client/src/features/home/workspace/takeover.tsindex 2ba43284..bcdc36b5 100644--- a/client/src/features/home/workspace/takeover.ts+++ b/client/src/features/home/workspace/takeover.ts@@ -1,11 +1,13 @@/*** Take over (design handoff "Workspace panel"): the owner takes the screen* the Workspace shows (Browser or Mobile) and the employee stops while they- * use it; Hand back gives the screen back and, when Take over stopped them,+ * use it; Hand back gives that screen back and, when Take over stopped them,* resumes them. Take over claims the screen first, so the employee never* acts on it again once the owner has it, then stops them. What happened is- * kept in homeStore (`takeover`), so Hand back knows whether to resume them- * even after the dock was closed or the tab changed.+ * kept in homeStore (`takeovers`, by employee), with the taken screen's way+ * of giving it back, so Hand back gives back the screen that was taken and+ * knows whether to resume them, even after the dock was closed or moved to+ * another tab or employee.*/import { useState } from 'react';@@ -28,27 +30,28 @@ export interface TakeOver {/** `surface`: the screen the Workspace shows now, or null on the Canvas tab. */export function useTakeOver(employee: EmployeeSummary, surface: () => SurfaceControl | null): TakeOver {const { pauseWorkflow, resumeWorkflow } = useWebSocketActions();- const takeover = useHomeStore((s) => s.takeover);+ const mine = useHomeStore((s) => s.takeovers[employee.workflow_id]);const setTakeover = useHomeStore((s) => s.setTakeover);const [busy, setBusy] = useState(false);- const mine = takeover?.workflowId === employee.workflow_id ? takeover : null;const takeOver = async () => {const screen = surface();if (!screen || busy) return;setBusy(true);+ let giveBack: (() => void) | null = null;try {- if (!(await screen.claim())) {+ giveBack = await screen.claim();+ if (!giveBack) {pillToast('Couldn’t take the screen. Try again.', { tone: 'error' });return;}// Only a running employee is stopped, and only then resumed later.const running = presentEmployee(employee).primary.kind === 'pause';if (running) await pauseWorkflow(employee.workflow_id, employee.control.revision);- setTakeover({ workflowId: employee.workflow_id, stopped: running });+ setTakeover(employee.workflow_id, { stopped: running, giveBack });pillToast(`You have control — ${employee.name} will wait`);} catch (error) {- screen.release();+ giveBack?.();pillToast(controlErrorMessage(error), { tone: 'error' });} finally {setBusy(false);@@ -59,13 +62,13 @@ export function useTakeOver(employee: EmployeeSummary, surface: () => SurfaceConif (!mine || busy) return;setBusy(true);try {- surface()?.release();+ mine.giveBack();if (mine.stopped) await resumeWorkflow(employee.workflow_id, employee.control.revision);pillToast(`Handed back to ${employee.name}`);} catch (error) {pillToast(controlErrorMessage(error), { tone: 'error' });} finally {- setTakeover(null);+ setTakeover(employee.workflow_id, null);setBusy(false);}};diff --git a/docs-internal/browser_workspace.md b/docs-internal/browser_workspace.mdindex 3c9fb43f..0e7ab02b 100644--- a/docs-internal/browser_workspace.md+++ b/docs-internal/browser_workspace.md@@ -149,7 +149,9 @@ closed viewer, a protected login (`reason: "protected_login"`), a full queue,or a request the page outran before it ran (`viewer_unavailable`) is refusedout loud (`LiveControlQueue._refuse_claim`), so a viewer never waits on"Taking control…". Home's Take over (`normal_mode.md`) relies on it: the-viewer's `claim()` resolves on that answer.+viewer's `claim()` resolves on that answer. While the browser is not+running there is no queue, and the socket answers every message, a+`control_request` included, with `idle`, which the claim takes as no.## Transport and displaydiff --git a/docs-internal/normal_mode.md b/docs-internal/normal_mode.mdindex c800a0f8..af98eda2 100644--- a/docs-internal/normal_mode.md+++ b/docs-internal/normal_mode.md@@ -289,13 +289,19 @@ Help in browser), else the first on the team.lease), and only then Stops a running employee (`pause_workflow`), so theemployee never acts on the screen again once the owner has it. While theowner has it the body is framed in orange and a banner says "You’re in- control · {Name} is waiting". **Hand back** gives the screen back- (Browser hands control back; Mobile releases the lease and lets a waiting- phone task go on, through `/resume` when this view no longer holds the- lease) and resumes the employee only when Take over stopped them;- `homeStore.takeover` keeps that, so it holds across a closed dock or a- changed tab. Toasts: "You have control — {Name} will wait", "Handed back- to {Name}".+ control · {Name} is waiting". **Hand back** gives back the screen that+ was taken, whichever tab the dock shows: a granted `claim` resolves to+ that screen's way of giving it back, which works after its view went+ away (an inactive tab is unmounted). Browser hands control back (hiding+ the view already did); Mobile releases the lease and lets a waiting+ phone task go on, through `/resume` when the view no longer holds the+ lease (the server resumes only this workflow's task, since the phone is+ shared). It resumes the employee only when Take over stopped them.+ `homeStore.takeovers` keeps each employee's, so it holds across a closed+ dock, a changed tab or another employee's Take over. A browser that is+ not running answers Take over's request `idle`, which the claim takes+ as no. Toasts: "You have control — {Name} will wait", "Handed back to+ {Name}".- **Size and motion**: 460px wide by default. The left edge drags from360px to the window less 420px, and Expand gives a bigger dock withouta drag. At 1100px and wider the dock pushes the page aside; narrower, itdiff --git a/docs/mobile-workspace.md b/docs/mobile-workspace.mdindex 20f73529..9f4bbd8c 100644--- a/docs/mobile-workspace.md+++ b/docs/mobile-workspace.md@@ -36,7 +36,7 @@ Both nodes use the same phone. Adding another node does not create another emulaThe live phone fills the available Workspace height in normal view, inside a phone frame (a dark bezel) shaped by the screen's own width and height, so it turns when the phone rotates; wide panels have side bars. Above it the server says which phone it is (`status.device`, "Pixel 7 · local emulator · up to 30 fps", from `DEVICE_NAME` and `VIDEO_MAX_FPS` in `_install.py`, which also set the AVD profile and scrcpy's `max_fps`). Below it the device bar has **Back**, **Home**, **Recent apps** and **Rotate** (on its side, and back), each sent through `/input` and enabled while you use the phone, and **Screenshot to Canvas** where the employee has a Canvas: `POST /screenshot` saves the screen as a PNG in the workflow's workspace (`write_media`, a read that needs no control) and `canvas_add` puts it on the board.-Home's **Take over** (in the Workspace footer) takes the phone's lease the way **Use phone** does, and stops the employee. **Hand back** releases the lease with `resume: true`, so a task waiting for you goes on; when this view no longer holds the lease (it was hidden meanwhile), `POST /resume` lets a waiting task go on without it. `/resume` is refused while someone uses the phone and does nothing when no task waits. Each action an AI task takes on the phone ("Tapped the screen", "Went back"; `TASK_STEPS` and `KEY_STEPS` in `_runtime.py`), and you taking the phone over and handing it back, adds a line to the employee's Workspace timeline on Home (`services/workspace_steps.py`); a line never holds typed text or what the screen showed. Expand **Ask AI to use the phone** to enter a task; collapsing it keeps your draft. The **Phone controls** toolbar toggle exposes Stop phone, refresh, APK installation while controlling the phone, completed setup history, and help. Status and takeover stay visible.+Home's **Take over** (in the Workspace footer) takes the phone's lease the way **Use phone** does, and stops the employee. **Hand back** releases the lease with `resume: true`, so a task waiting for you goes on; when this view no longer holds the lease (it was hidden meanwhile), `POST /resume` lets a waiting task go on without it. `/resume` is refused while someone uses the phone and does nothing when no task of that workflow waits: the phone is shared, so one employee's Hand back never lets another employee's task go on. Each action an AI task takes on the phone ("Tapped the screen", "Went back"; `TASK_STEPS` and `KEY_STEPS` in `_runtime.py`), and you taking the phone over and handing it back, adds a line to the employee's Workspace timeline on Home (`services/workspace_steps.py`); a line never holds typed text or what the screen showed. Expand **Ask AI to use the phone** to enter a task; collapsing it keeps your draft. The **Phone controls** toolbar toggle exposes Stop phone, refresh, APK installation while controlling the phone, completed setup history, and help. Status and takeover stay visible.Choose **Full view** in the toolbar to fill the screen. The task panel is hidden, and secondary controls remain available through the toolbar toggle. Controls stay outside the picture so they do not cover Android buttons. Use **Exit full view** or **Esc** to return. Entering full view keeps the current connection and does not restart the phone or grant manual control. Browser Workspace uses the same layout, with address and navigation under **Browser controls**. If the browser does not support fullscreen, use the existing Workspace expand button instead.diff --git a/server/nodes/mobile/_router.py b/server/nodes/mobile/_router.pyindex 36f9d9d2..67fc9192 100644--- a/server/nodes/mobile/_router.py+++ b/server/nodes/mobile/_router.py@@ -165,14 +165,15 @@ async def release(body: Release, request: Request, workflow_id: str, node_id: st@router.post(BASE + "/resume")-async def resume(principal: str = Depends(authorize)):- """Let the AI task that waits for the owner go on (the Workspace's Hand- back), without holding the phone: the view that held it may be gone."""+async def resume(workflow_id: str, principal: str = Depends(authorize)):+ """Let this workflow's AI task that waits for the owner go on (the+ Workspace's Hand back), without holding the phone: the view that held it+ may be gone."""from ._runtime import get_runtimeruntime = get_runtime()try:- runtime.resume_waiting()+ runtime.resume_waiting(workflow_id)except MobileError as exc:raise HTTPException(409, str(exc)) from Nonereturn runtime.snapshot()diff --git a/server/nodes/mobile/_runtime.py b/server/nodes/mobile/_runtime.pyindex 8c230534..2051e990 100644--- a/server/nodes/mobile/_runtime.py+++ b/server/nodes/mobile/_runtime.py@@ -513,13 +513,14 @@ class MobileRuntime:if text:await record_phone_step(entry.get("workflow_id"), entry.get("node_id"), text)- def resume_waiting(self) -> None:- """Let the AI task that waits for the owner go on, without holding the- phone: Hand back after the view that held it went away. Refused while- someone uses the phone; nothing happens when no task waits."""+ def resume_waiting(self, workflow_id: str) -> None:+ """Let ``workflow_id``'s AI task that waits for the owner go on,+ without holding the phone: Hand back after the view that held it went+ away. Refused while someone uses the phone. Nothing happens when no+ task of that workflow waits: the phone is shared by every employee."""if self.viewer is not None:raise MobileError("not_controller", "Someone is using the phone. Finish using it first.")- if self.active and self.active.get("status") == "awaiting_user":+ if self.active and self.active.get("status") == "awaiting_user" and self.active.get("workflow_id") == workflow_id:self.resume_event.set()async def cancel(self, workflow_id: str, node_id: str, *, run_id: str | None = None):diff --git a/server/tests/test_mobile_runtime.py b/server/tests/test_mobile_runtime.pyindex 0c7774d7..3ead3014 100644--- a/server/tests/test_mobile_runtime.py+++ b/server/tests/test_mobile_runtime.py@@ -91,15 +91,18 @@ def test_hand_back_resumes_a_waiting_task_without_holding_the_phone():value = MobileRuntime()# Nothing waits: nothing happens.- value.resume_waiting()+ value.resume_waiting("w1")assert not value.resume_event.is_set()- value.active = {"run_id": "run", "status": "awaiting_user"}+ value.active = {"run_id": "run", "workflow_id": "w1", "status": "awaiting_user"}value.viewer = "someone"with pytest.raises(MobileError, match="using the phone"):- value.resume_waiting()+ value.resume_waiting("w1")assert not value.resume_event.is_set()value.viewer = None- value.resume_waiting()+ # The phone is shared: another employee's Hand back leaves this task waiting.+ value.resume_waiting("w2")+ assert not value.resume_event.is_set()+ value.resume_waiting("w1")assert value.resume_event.is_set()