Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork): stop the first subagent dispatch of every fan-out failing
Akarshan Biswas35dacc9f3745
diff --git a/web-app/src/containers/message/SubagentToolWidget.tsx b/web-app/src/containers/message/SubagentToolWidget.tsxnew file mode 100644index 000000000..6a85c6239--- /dev/null+++ b/web-app/src/containers/message/SubagentToolWidget.tsx@@ -0,0 +1,71 @@+import { memo } from 'react'+import type { ToolUIPart } from 'ai'+import { IconSparkles } from '@tabler/icons-react'+import { Shimmer } from '@/components/ai-elements/shimmer'+import { useTranslation } from '@/i18n/react-i18next-compat'+import { isToolRunning, type ToolCallBar } from '@/lib/toolPresentation'++export type SubagentToolWidgetProps = {+ bar: Extract<ToolCallBar, { variant: 'subagent' }>+ state: ToolUIPart['state']+ errorText?: string+}++/**+ * A `task` call: which subagent was launched, and the brief it was launched+ * with.+ *+ * Deliberately says nothing about how the child is getting on. `task` returns+ * as soon as the child starts, so this card settles within a second of being+ * drawn, while the run it started goes on for minutes -- and the tasks panel+ * follows that for its whole life. A card that also tried to report progress+ * would be reporting a run it stopped watching.+ *+ * The result text is not shown either: it is a sentence addressed to the model+ * ("keep working rather than waiting for it"), and the file it names is only+ * useful to the model. A failed dispatch *is* shown, because a rejected call+ * is the one thing here the user may need to act on.+ */+export const SubagentToolWidget = memo(+ ({ bar, state, errorText }: SubagentToolWidgetProps) => {+ const { t } = useTranslation()+ const running = isToolRunning(state)++ return (+ <div className="space-y-1.5">+ <div className="flex items-center gap-2 rounded-full border bg-card/40 px-3 py-1.5">+ <IconSparkles size={16} className="shrink-0 text-primary" />+ <span className="min-w-0 flex-1 truncate text-sm font-medium">+ {bar.name || (+ <span className="text-muted-foreground/60">+ {t('tools:toolCall.subagentPlaceholder')}+ </span>+ )}+ </span>+ </div>++ {bar.task && (+ <p className="line-clamp-3 px-2 text-sm text-muted-foreground">+ {bar.task}+ </p>+ )}++ {errorText ? (+ <div className="rounded-md bg-destructive/10 px-2 py-1.5 text-sm text-destructive">+ {errorText}+ </div>+ ) : running ? (+ <div className="px-2 text-sm">+ <Shimmer duration={1}>{t('tools:toolCall.dispatching')}</Shimmer>+ </div>+ ) : (+ <p className="px-2 text-sm text-muted-foreground/70">+ {t('tools:toolCall.subagentRunning')}+ </p>+ )}+ </div>+ )+ }+)++SubagentToolWidget.displayName = 'SubagentToolWidget'diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsxindex f5cc8d07d..db712ad68 100644--- a/web-app/src/containers/message/ToolCallCard.tsx+++ b/web-app/src/containers/message/ToolCallCard.tsx@@ -16,6 +16,7 @@ import { isToolPart, type MessagePartLike } from './types'import { RagToolWidget } from './RagToolWidget'import { WebToolWidget } from './WebToolWidget'import { AgentToolWidget, TerminalWidget } from './AgentToolWidget'+import { SubagentToolWidget } from './SubagentToolWidget'const identityResolver = (input: string) => Promise.resolve(input)@@ -45,7 +46,9 @@ export const ToolCallCard = memo(? t('tools:toolCall.originDocuments'): origin.kind === 'agent'? t('tools:toolCall.originWorkspace')- : origin.detail+ : origin.kind === 'subagent'+ ? t('tools:toolCall.originSubagent')+ : origin.detailconst errorText = isError? part.error || part.errorText || t('tools:toolCall.executionFailed')@@ -98,6 +101,12 @@ export const ToolCallCard = memo(output={part.output}errorText={errorText}/>+ ) : bar.variant === 'subagent' ? (+ <SubagentToolWidget+ bar={bar}+ state={part.state}+ errorText={errorText}+ />) : bar.variant === 'workspace' ? (<AgentToolWidgetbar={bar}diff --git a/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsxnew file mode 100644index 000000000..c9cc8e10b--- /dev/null+++ b/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx@@ -0,0 +1,61 @@+import { describe, expect, it, vi } from 'vitest'+import { render, screen } from '@testing-library/react'+import '@testing-library/jest-dom'++vi.mock('@/i18n/react-i18next-compat', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}))++import { SubagentToolWidget } from '../SubagentToolWidget'++const bar = {+ variant: 'subagent' as const,+ name: 'researcher',+ task: 'Research MCP servers for physical hardware',+}++describe('SubagentToolWidget', () => {+ it('names the subagent and its brief while the call streams', () => {+ render(<SubagentToolWidget bar={bar} state="input-streaming" />)+ expect(screen.getByText('researcher')).toBeInTheDocument()+ expect(screen.getByText(bar.task)).toBeInTheDocument()+ expect(screen.getByText('tools:toolCall.dispatching')).toBeInTheDocument()+ })++ it('prompts for the subagent before the name arrives', () => {+ render(+ <SubagentToolWidget+ bar={{ variant: 'subagent', name: '', task: '' }}+ state="input-streaming"+ />+ )+ expect(+ screen.getByText('tools:toolCall.subagentPlaceholder')+ ).toBeInTheDocument()+ })++ /// `task` returns as soon as the child starts, so a settled card means+ /// "dispatched", not "finished" -- the tasks panel is what follows the run.+ it('reads as running once the call settles', () => {+ render(<SubagentToolWidget bar={bar} state="output-available" />)+ expect(+ screen.getByText('tools:toolCall.subagentRunning')+ ).toBeInTheDocument()+ })++ /// A rejected dispatch is the one thing on this card the user may need to+ /// act on, so it is not left folded away in the raw output.+ it('shows a refused dispatch', () => {+ render(+ <SubagentToolWidget+ bar={bar}+ state="output-error"+ errorText="unknown subagent 'researcher': no saved definition"+ />+ )+ expect(screen.getByText(/no saved definition/)).toBeInTheDocument()+ expect(+ screen.queryByText('tools:toolCall.subagentRunning')+ ).not.toBeInTheDocument()+ })+})diff --git a/web-app/src/lib/__tests__/coworkTools.test.ts b/web-app/src/lib/__tests__/coworkTools.test.tsindex 955224d22..3d4e16a0e 100644--- a/web-app/src/lib/__tests__/coworkTools.test.ts+++ b/web-app/src/lib/__tests__/coworkTools.test.ts@@ -150,4 +150,39 @@ describe('allowedToolNames', () => {const out = allowedToolNames(['read', TASK_TOOL_NAME], opts({ allowSubagents: false }))expect(out).toEqual(['read'])})++ /// The dispatch that fails is the first one of every fan-out: a model reaches+ /// for a descriptive name long before it has saved a definition, and a schema+ /// that mentions `system_prompt` only in passing gets it omitted.+ describe('the task schema states the one-off rule', () => {+ it('says which combination fails, on the field filled in first', async () => {+ const { buildCoworkTools } = await import('../coworkTools')+ const tools = await buildCoworkTools({+ planMode: false,+ subagentNames: [],+ allowSubagents: true,+ webSearch: false,+ })+ const task = tools['task'] as unknown as {+ description: string+ inputSchema: { jsonSchema: { properties: Record<string, { description?: string }> } }+ }+ const props = task.inputSchema.jsonSchema.properties+ expect(props.subagent_name.description).toContain('system_prompt')+ expect(props.system_prompt.description).toContain('Required')+ expect(task.description).toContain('No saved subagents yet')+ })++ it('lists the saved definitions when there are any', async () => {+ const { buildCoworkTools } = await import('../coworkTools')+ const tools = await buildCoworkTools({+ planMode: false,+ subagentNames: ['reviewer'],+ allowSubagents: true,+ webSearch: false,+ })+ const task = tools['task'] as unknown as { description: string }+ expect(task.description).toContain('Saved subagents: reviewer.')+ })+ })})diff --git a/web-app/src/lib/coworkTools.ts b/web-app/src/lib/coworkTools.tsindex ac1d13f69..1a4158db0 100644--- a/web-app/src/lib/coworkTools.ts+++ b/web-app/src/lib/coworkTools.ts@@ -114,24 +114,49 @@ const askTool: Tool = {}),} as Tool+/**+ * Wording ported from `subagent_tool_schemas` in Rust, and it has to stay that+ * literal about the one-off rule.+ *+ * A name with no saved definition and no `system_prompt` is rejected, and+ * models reach for a descriptive name (`researcher`, `designer`) long before+ * they have saved one -- so a schema that mentions `system_prompt` only as+ * something for "a one-off subagent" reads as optional, gets omitted, and the+ * first dispatch of every fan-out fails. Saying which combination fails, on the+ * field the model fills in first, is what stops that.+ */function taskTool(subagentNames: string[]): Tool {- const known = subagentNames.length+ const saved = subagentNames.length? ` Saved subagents: ${subagentNames.join(', ')}.`- : ''+ : ' No saved subagents yet, so every call needs a `system_prompt`.'return {description:- 'Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Runs in the BACKGROUND and returns immediately with the file its answer will be written to; call it several times in one step to fan work out, keep working, and a note tells you the moment each one finishes.' +- known,+ 'Start a subagent: a nested, isolated agent with its own system prompt and narrowed tools. It does not see this conversation, so state everything it needs in `description`. Runs in the BACKGROUND and returns immediately with the file its answer will be written to; call it several times in one step to fan work out, keep working, and a note tells you the moment each one finishes. For a one-off subagent, pass `system_prompt` inline with a descriptive `subagent_name`.' ++ saved,inputSchema: jsonSchema({type: 'object',properties: {- subagent_name: { type: 'string' },- description: { type: 'string' },+ subagent_name: {+ type: 'string',+ description:+ 'Name of a saved subagent to run. For a one-off (no saved definition), pick a short descriptive name here AND pass system_prompt in the same call -- an unrecognized name with no system_prompt fails.',+ },+ description: {+ type: 'string',+ description:+ 'The task for the subagent, as its sole user message. Include everything it needs; it does not see this conversation.',+ },system_prompt: {type: 'string',- description: 'For a one-off subagent with no saved definition.',+ description:+ "Required alongside subagent_name whenever that name isn't already saved -- defines the one-off subagent's role. Omit only when subagent_name matches a saved subagent.",+ },+ allowed_tools: {+ type: 'array',+ items: { type: 'string' },+ description:+ "Tool allowlist. For a saved subagent this further narrows its own allowed_tools (never widens); for a one-off it is the subagent's toolset.",},- allowed_tools: { type: 'array', items: { type: 'string' } },},required: ['subagent_name', 'description'],additionalProperties: false,diff --git a/web-app/src/lib/partialJson.ts b/web-app/src/lib/partialJson.tsindex e0c19dfc7..18688e453 100644--- a/web-app/src/lib/partialJson.ts+++ b/web-app/src/lib/partialJson.ts@@ -94,6 +94,8 @@ const PREVIEW_FIELDS = ['url','pattern','name',+ 'subagent_name',+ 'description',] as constexport function partialToolInput(raw: string): Record<string, string> {diff --git a/web-app/src/lib/toolOrigin.ts b/web-app/src/lib/toolOrigin.tsindex 317f404ac..5ad765dde 100644--- a/web-app/src/lib/toolOrigin.ts+++ b/web-app/src/lib/toolOrigin.ts@@ -1,13 +1,16 @@/**- * Where a tool call came from. Jan runs four families of tools -- the native- * web tools, the built-in RAG tools, the built-in agent tools, and MCP server- * tools -- and a collapsed card is ambiguous without saying which.+ * Where a tool call came from. Jan runs five families of tools -- the native+ * web tools, the built-in RAG tools, the built-in agent tools, subagent+ * dispatch, and MCP server tools -- and a collapsed card is ambiguous without+ * saying which.*/export type ToolOrigin =| { kind: 'web-search'; detail: string }| { kind: 'web-fetch' }| { kind: 'rag' }| { kind: 'agent' }+ /** `task`: not a tool the workspace runs, but a whole nested agent. */+ | { kind: 'subagent' }| { kind: 'mcp'; detail: string }export type ToolOriginContext = {@@ -21,6 +24,7 @@ export type ToolOriginContext = {export const WEB_SEARCH_TOOL = 'web_search'export const WEB_FETCH_TOOL = 'web_fetch'+export const TASK_TOOL = 'task'/*** Resolution order mirrors the execution order in the thread route: native web@@ -36,6 +40,9 @@ export function resolveToolOrigin(return { kind: 'web-search', detail: webSearchProviderLabel }}if (toolName === WEB_FETCH_TOOL) return { kind: 'web-fetch' }+ // Dispatched by the surface rather than the plugin, so it is not in the agent+ // tool set and would otherwise fall through to the unlabelled generic card.+ if (toolName === TASK_TOOL) return { kind: 'subagent' }if (isAgentTool) return { kind: 'agent' }if (isRagTool) return { kind: 'rag' }if (mcpServer) return { kind: 'mcp', detail: mcpServer }diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.tsindex af923c295..d95c12210 100644--- a/web-app/src/lib/toolPresentation.ts+++ b/web-app/src/lib/toolPresentation.ts@@ -31,6 +31,12 @@ export type ToolCallBar =detail?: stringbody?: string}+ /**+ * `task`. The card answers "which subagent, and what did it just get asked+ * to do" -- how it is getting on belongs to the tasks panel, which follows+ * the child for as long as it runs.+ */+ | { variant: 'subagent'; name: string; task: string }/*** Owned by the RAG extension (extensions/rag-extension/src/tools.ts) and not@@ -67,6 +73,13 @@ export function describeNativeToolCall(if (origin.kind === 'web-fetch') {return { variant: 'address', url: asString(args.url) }}+ if (origin.kind === 'subagent') {+ return {+ variant: 'subagent',+ name: asString(args.subagent_name),+ task: asString(args.description),+ }+ }if (origin.kind === 'rag' && toolName === RAG_RETRIEVE_TOOL) {return {variant: 'documents',diff --git a/web-app/src/locales/en/tools.json b/web-app/src/locales/en/tools.jsonindex b019921e9..e801699d7 100644--- a/web-app/src/locales/en/tools.json+++ b/web-app/src/locales/en/tools.json@@ -37,6 +37,11 @@"originWeb": "Web","originDocuments": "Documents","originWorkspace": "Workspace",+ "originSubagent": "Subagent",+ "subagentPlaceholder": "subagent",+ "dispatching": "Dispatching...",+ "subagentRunning": "Running in the background",+ "subagentBrief": "Brief","viewRaw": "Raw","viewTable": "Table","showMore": "Show more",