Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): enforce plan review and enable approved execution
thinhlpg01a4cc929d01
diff --git a/web-app/src/lib/__tests__/coworkDispatch.test.ts b/web-app/src/lib/__tests__/coworkDispatch.test.tsindex 4b6f7ec3c..c27b6467e 100644--- a/web-app/src/lib/__tests__/coworkDispatch.test.ts+++ b/web-app/src/lib/__tests__/coworkDispatch.test.ts@@ -167,6 +167,44 @@ describe('dispatchCoworkTool', () => {})})+it('pauses repeated failed reads for review without swallowing the read error', async () => {+ const error = 'ERROR: No such file or directory (os error 2)'+ executeAgentTool.mockResolvedValue({ error })+ let review: unknown+ let answer!: (result: { output: string }) => void+ const context = ctx({+ planMode: true,+ failedReadPaths: new Set<string>(),+ onAsk: async (_id: string, input: unknown) => {+ review = input+ return new Promise<{ output: string }>((resolve) => {+ answer = resolve+ })+ },+ })+ const first = await dispatchCoworkTool(+ call('read', { path: 'index.html' }),+ context+ )+ expect(first.isError).toBe(true)+ expect(review).toBeUndefined()+ let finished = false+ const second = dispatchCoworkTool(+ call('read', { path: 'index.html' }),+ context+ ).then((result) => {+ finished = true+ return result+ })+ await vi.waitFor(() => expect(review).toBeDefined())+ expect(finished).toBe(false)+ answer({ output: 'Keep planning' })+ const result = await second+ expect(result.isError).toBe(true)+ expect(result.output).toContain(error)+ expect(result.output).toContain('Keep planning')+})+describe('web tools', () => {beforeEach(() => executeWebTool.mockReset())diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 5cc801c9a..15ea9e1c5 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -18,11 +18,19 @@ import {} from '@/lib/coworkMonitor'import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'+import {+ EXECUTE_PLAN_LABEL,+ EXIT_PLAN_LABEL,+ KEEP_PLANNING_LABEL,+ PLAN_REVIEW_QUESTION_ID,+} from '@/lib/coworkPrompt'export type DispatchContext = {sessionId: stringreadOnlyFolder: string | nullplanMode: boolean+ /** Request-owned failure history. Omitted by children, which cannot plan. */+ failedReadPaths?: Set<string>/** Mirrors the advertised set. Refused when off, so a call to a tool that was* never advertised cannot reach the network the user switched off. */webSearch: boolean@@ -55,6 +63,60 @@ function planRefusal(toolName: string): ToolOutcome {}}+// A model may try to create a missing file through `read` when write is+// withheld. Keep the filesystem error, but explain the approval path at the+// failure itself so the next step can recover instead of repeating the read.+const PLAN_READ_FAILURE_GUIDANCE =+ 'Plan mode is enabled: file creation and editing are disabled. ' ++ 'The read tool only reads existing files; it cannot create a missing output file. ' ++ 'Do not retry the same failed read or try to write through a read-only tool. ' ++ 'If this is a file you intend to create, stage its creation with todo ' ++ `(or keep the existing plan), then call ask with question id ${PLAN_REVIEW_QUESTION_ID} ` ++ `and options ${EXECUTE_PLAN_LABEL}, ${KEEP_PLANNING_LABEL}, ${EXIT_PLAN_LABEL}. ` ++ 'Wait for approval before implementation.'++async function toolFailure(+ call: PendingToolCall,+ error: string,+ ctx: DispatchContext+): Promise<ToolOutcome> {+ let output = error+ if (ctx.planMode && call.toolName === 'read') {+ output += `\n\n${PLAN_READ_FAILURE_GUIDANCE}`+ const path = readPath(call.input)+ if (path && ctx.failedReadPaths) {+ if (ctx.failedReadPaths.has(path)) {+ // User review is an enforced pause, not another instruction the model+ // can ignore. Keep planning grants a fresh attempt at this path.+ ctx.failedReadPaths.delete(path)+ const review = await ctx.onAsk(call.toolCallId, {+ questions: [+ {+ id: PLAN_REVIEW_QUESTION_ID,+ question: `Reading "${path}" failed again: ${error}. Review the plan before continuing.`,+ options: [+ { label: EXECUTE_PLAN_LABEL },+ { label: KEEP_PLANNING_LABEL },+ { label: EXIT_PLAN_LABEL },+ ],+ },+ ],+ })+ output += `\n\nPlan review response: ${review.output}`+ } else {+ ctx.failedReadPaths.add(path)+ }+ }+ }+ return { output, isError: true }+}++function readPath(input: unknown): string | undefined {+ if (!input || typeof input !== 'object') return undefined+ const path = (input as { path?: unknown }).path+ return typeof path === 'string' ? path : undefined+}+/*** One `monitor` op. The watcher runs in Rust; this routes the call and keeps* the session's `MonitorLane` in step, so matches queue as pings and the rail@@ -163,7 +225,11 @@ export async function dispatchCoworkTool(true,ctx.readOnlyFolder)- if (result.error) return { output: result.error, isError: true }+ if (result.error) return await toolFailure(call, result.error, ctx)+ if (toolName === 'read') {+ const path = readPath(call.input)+ if (path) ctx.failedReadPaths?.delete(path)+ }return {output:typeof result.content === 'string'@@ -173,9 +239,6 @@ export async function dispatchCoworkTool(images: result.images,}} catch (e) {- return {- output: e instanceof Error ? e.message : String(e),- isError: true,- }+ return toolFailure(call, e instanceof Error ? e.message : String(e), ctx)}}diff --git a/web-app/src/routes/__tests__/coworkSkills.test.tsx b/web-app/src/routes/__tests__/coworkSkills.test.tsxindex 321885b67..5724fba4d 100644--- a/web-app/src/routes/__tests__/coworkSkills.test.tsx+++ b/web-app/src/routes/__tests__/coworkSkills.test.tsx@@ -12,6 +12,10 @@ const backend = vi.hoisted(() => ({received: [] as UIMessage[][],hold: false,preparationError: false,+ exercise: null as+ | null+ | ((deps: CoworkRunner.RunDeps, signal: AbortSignal) => Promise<void>),+ files: new Map<string, string>(),runs: [] as {signal: AbortSignalsink: CoworkRunner.StreamSink@@ -58,6 +62,8 @@ vi.mock('@/lib/backendStorage', () => ({}))vi.mock('@/lib/coworkTransport', () => ({CoworkChatTransport: class {+ setConfig() {}+ unfreezeTools() {}async refreshTools() {if (backend.preparationError) throw new Error('Tool preparation failed')}@@ -72,6 +78,7 @@ vi.mock('@/lib/coworkRunner', async (original) => ({deps,}: Parameters<typeof CoworkRunner.runTurn>[0]) => {backend.received.push(messages)+ if (backend.exercise) await backend.exercise(deps, signal)if (backend.hold) {await new Promise<void>((resolve) => {backend.runs.push({ signal, sink: deps.sink, finish: resolve })@@ -82,6 +89,19 @@ vi.mock('@/lib/coworkRunner', async (original) => ({},}))vi.mock('@/lib/agentTools', () => ({+ executeAgentTool: async (+ name: string,+ input: { path: string; content?: string }+ ) => {+ if (name === 'write') {+ backend.files.set(input.path, input.content ?? '')+ return { content: 'created' }+ }+ const content = backend.files.get(input.path)+ return content === undefined+ ? { error: 'ERROR: No such file or directory (os error 2)' }+ : { content }+ },getSandboxStatus: async () => ({}),sandboxEnforces: () => false,activeAgentMonitorIds: async () => [],@@ -90,7 +110,6 @@ vi.mock('@/lib/agentTools', () => ({vi.mock('@/lib/coworkSubagentRegistry', () => ({listSubagents: async () => [],}))-vi.mock('@/lib/coworkDispatch', () => ({ dispatchCoworkTool: vi.fn() }))vi.mock('@/lib/model-factory', () => ({ ModelFactory: {} }))vi.mock('@janhq/tauri-plugin-agent-tools-api', () => ({sessionWorkspacePath: async () => '/sandbox',@@ -218,6 +237,7 @@ import { startNewSession, useCoworkSessions } from '@/hooks/useCoworkSessions'import { useCoworkRun } from '@/hooks/useCoworkRun'import { useMessageQueue } from '@/stores/message-queue-store'import { useModelProvider } from '@/hooks/useModelProvider'+import { answerAsk } from '@/lib/coworkRunner'import { localStorageKey } from '@/constants/localStorage'// The router mock returns the supplied component options directly.const routeOptions = Route as unknown as { component: () => ReactNode }@@ -241,6 +261,8 @@ beforeEach(() => {backend.hold = falsebackend.preparationError = falsebackend.runs = []+ backend.exercise = null+ backend.files.clear()const browserStorage = new Map<string, string>()vi.stubGlobal('localStorage', {getItem: (key: string) => browserStorage.get(key) ?? null,@@ -474,3 +496,124 @@ it('restores each session model after switching and persisted-store rehydration'expect(document.querySelector('header')).toHaveTextContent('test-model'))})++it('requires plan approval before a failed-read loop can create the requested file', async () => {+ const sid = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().setPlanMode(sid, true)+ let writeResult: CoworkRunner.ToolOutcome | undefined+ backend.exercise = async (deps, signal) => {+ await deps.dispatch(+ { toolCallId: 'r1', toolName: 'read', input: { path: 'cat.html' } },+ signal+ )+ await deps.dispatch(+ { toolCallId: 'r2', toolName: 'read', input: { path: 'cat.html' } },+ signal+ )+ writeResult = await deps.dispatch(+ {+ toolCallId: 'w1',+ toolName: 'write',+ input: { path: 'cat.html', content: '<h1>Cat</h1>' },+ },+ signal+ )+ }+ render(<CoworkPage />)+ act(() => usePrompt.getState().setPrompt('make cat html'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() =>+ expect(useCoworkRun.getState().pendingAsks[sid]?.length).toBe(1)+ )+ expect(backend.files.has('cat.html')).toBe(false)+ expect(+ useCoworkSessions.getState().sessions.find((s) => s.id === sid)?.planMode+ ).toBe(true)+ let other = ''+ act(() => {+ other = startNewSession(Object.keys(useCoworkRun.getState().runId))+ useCoworkSessions.getState().setPlanMode(other, true)+ })+ act(() => {+ answerAsk(sid, 'r2', [{ id: 'plan_review', selected: ['Execute plan'] }])+ })+ await waitFor(() =>+ expect(backend.files.get('cat.html')).toBe('<h1>Cat</h1>')+ )+ expect(writeResult?.isError).not.toBe(true)+ expect(+ useCoworkSessions.getState().sessions.find((s) => s.id === sid)?.planMode+ ).toBe(false)+ expect(+ useCoworkSessions.getState().sessions.find((s) => s.id === other)?.planMode+ ).toBe(true)+})++it.each([+ { selection: 'Keep planning', planMode: true, aborted: false },+ { selection: 'Exit plan mode', planMode: false, aborted: true },+ { selection: null, planMode: true, aborted: true },+])(+ 'does not execute when plan review receives $selection',+ async ({ selection, planMode, aborted }) => {+ const sid = useCoworkSessions.getState().createSession()+ useCoworkSessions.getState().setPlanMode(sid, true)+ let ended = false+ let wasAborted: boolean | undefined+ backend.exercise = async (deps, signal) => {+ await deps.dispatch(+ {+ toolCallId: 'review',+ toolName: 'ask',+ input: {+ questions: [+ {+ id: 'plan_review',+ question: 'Create cat.html?',+ options: [+ { label: 'Execute plan' },+ { label: 'Keep planning' },+ { label: 'Exit plan mode' },+ ],+ },+ ],+ },+ },+ signal+ )+ wasAborted = signal.aborted+ if (!signal.aborted) {+ await deps.dispatch(+ {+ toolCallId: 'write',+ toolName: 'write',+ input: { path: 'cat.html', content: '<h1>Cat</h1>' },+ },+ signal+ )+ }+ ended = true+ }+ render(<CoworkPage />)+ act(() => usePrompt.getState().setPrompt('make cat html'))+ fireEvent.click(screen.getByText('Send'))+ await waitFor(() =>+ expect(useCoworkRun.getState().pendingAsks[sid]?.length).toBe(1)+ )+ act(() => {+ answerAsk(+ sid,+ 'review',+ selection === null+ ? null+ : [{ id: 'plan_review', selected: [selection] }]+ )+ })+ await waitFor(() => expect(ended).toBe(true))+ expect(backend.files.has('cat.html')).toBe(false)+ expect(wasAborted).toBe(aborted)+ expect(+ useCoworkSessions.getState().sessions.find((s) => s.id === sid)?.planMode+ ).toBe(planMode)+ }+)diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex f2069234f..5b6a94886 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -91,6 +91,11 @@ import { getCoworkEnvironment } from '@/lib/coworkEnv'import { dispatchCoworkTool } from '@/lib/coworkDispatch'import { applyTodoOp, renderTodoResult } from '@/lib/coworkTodo'import { parseAskRequest, renderAskResult } from '@/lib/coworkAsk'+import {+ EXECUTE_PLAN_LABEL,+ EXIT_PLAN_LABEL,+ PLAN_REVIEW_QUESTION_ID,+} from '@/lib/coworkPrompt'import {getSandboxStatus,sandboxEnforces,@@ -587,7 +592,8 @@ function CoworkPage() {const webSearch = useWebSearchConfig.getState().webSearchEnabled// One snapshot per run, shared with every child this run dispatches.const environment = await getCoworkEnvironment()- const transport = new CoworkChatTransport(sid, {+ const failedReadPaths = current?.planMode ? new Set<string>() : undefined+ const runConfig = {model: { provider: selectedProvider, id: selectedModel.id },planMode: current?.planMode ?? false,subagentNames: subagentDefs.map((d) => d.name),@@ -597,7 +603,8 @@ function CoworkPage() {webSearch,workspacePath,readOnlyFolder: current?.folder ?? null,- })+ }+ const transport = new CoworkChatTransport(sid, runConfig)await transport.refreshTools()// Owned by this request: children cannot outlive the run whose signal@@ -658,7 +665,6 @@ function CoworkPage() {},}-outcome = await runTurn({messages,signal: controller.signal,@@ -684,7 +690,8 @@ function CoworkPage() {dispatchCoworkTool(call, {sessionId: sid,readOnlyFolder: current?.folder ?? null,- planMode: current?.planMode ?? false,+ planMode: runConfig.planMode,+ failedReadPaths,webSearch,monitors: monitorLane,onTodo: async (input) => {@@ -710,7 +717,37 @@ function CoworkPage() {useCoworkRun.getState().addPendingAsk(sid, callId, parsed)handle.pendingAsks.set(callId, (answers) => {useCoworkRun.getState().removePendingAsk(sid, callId)+ const planReview =+ runConfig.planMode &&+ parsed.questions.length === 1 &&+ parsed.questions[0].id === PLAN_REVIEW_QUESTION_ID+ const selection =+ answers?.length === 1 &&+ answers[0].id === PLAN_REVIEW_QUESTION_ID &&+ answers[0].selected.length === 1+ ? answers[0].selected[0]+ : undefined+ if (+ planReview &&+ (selection === EXECUTE_PLAN_LABEL ||+ selection === EXIT_PLAN_LABEL)+ ) {+ runConfig.planMode = false+ useCoworkSessions.getState().setPlanMode(sid, false)+ // Approval is a deliberate run boundary: refresh the+ // prompt and tools together before the next model step.+ transport.setConfig(runConfig)+ transport.unfreezeTools()+ failedReadPaths?.clear()+ }resolve(renderAskResult(answers))+ if (+ planReview &&+ (answers === null || selection === EXIT_PLAN_LABEL) &&+ !controller.signal.aborted+ ) {+ abortRun(sid)+ }})}),onTask: async (callId, input) => {