Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(cowork): stop announcing a running tool call three times

Akarshan Biswas3006b642b70c
diff --git a/web-app/src/containers/MessageItem.test.tsx b/web-app/src/containers/MessageItem.test.tsx
index 572acd17e..17abbf84b 100644
--- a/web-app/src/containers/MessageItem.test.tsx
+++ b/web-app/src/containers/MessageItem.test.tsx
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { render, screen, act } from '@testing-library/react'
import { MessageItem } from './MessageItem'
import type { UIMessage } from 'ai'
+import type { SubagentRun } from '@/types/coworkSession'
vi.mock('@/i18n/react-i18next-compat', () => ({
useTranslation: () => ({ t: (k: string) => k }),
@@ -19,7 +20,7 @@ describe('agent activity status', () => {
vi.useRealTimers()
})
- const baseMessage: UIMessage = {
+ const pendingWrite: UIMessage = {
id: 'm1',
role: 'assistant',
parts: [
@@ -32,16 +33,43 @@ describe('agent activity status', () => {
],
} as UIMessage
- it('shows the active tool label and ticks elapsed time', () => {
+ /// The call's own card sits one row above with its name, arguments and a
+ /// ticking duration, so a status row saying "Writing report.html" printed the
+ /// same thing twice.
+ it('leaves a pending tool call to its own card', () => {
render(
<MessageItem
- message={baseMessage}
+ message={pendingWrite}
isFirstMessage={false}
isLastMessage={true}
status="streaming"
/>
)
- expect(screen.getByText(/Writing report\.html/)).toBeInTheDocument()
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
+ })
+
+ /// A subagent is the exception: it works in a lane of its own, so nothing in
+ /// this turn reports it and the row is the only place it shows.
+ it('reports a running subagent, and ticks its elapsed time', () => {
+ const subagents: SubagentRun[] = [
+ {
+ runId: 'r1',
+ name: 'researcher',
+ status: 'running',
+ startedAt: Date.now(),
+ turns: [],
+ },
+ ]
+ render(
+ <MessageItem
+ message={pendingWrite}
+ isFirstMessage={false}
+ isLastMessage={true}
+ status="streaming"
+ subagents={subagents}
+ />
+ )
+ expect(screen.getByText(/researcher: working/)).toBeInTheDocument()
expect(screen.getByText(/0ms/)).toBeInTheDocument()
act(() => {
@@ -50,28 +78,25 @@ describe('agent activity status', () => {
expect(screen.getByText(/3s/)).toBeInTheDocument()
})
- it('removes the status row once the tool result lands', () => {
- const doneMessage: UIMessage = {
- ...baseMessage,
- parts: [
- {
- type: 'tool-write',
- toolCallId: 'c1',
- state: 'output-available',
- input: { path: '/proj/report.html' },
- output: 'ok',
- } as never,
- ],
- } as UIMessage
-
+ it('drops the row once the subagent finishes', () => {
+ const subagents: SubagentRun[] = [
+ {
+ runId: 'r1',
+ name: 'researcher',
+ status: 'done',
+ startedAt: Date.now(),
+ turns: [],
+ },
+ ]
render(
<MessageItem
- message={doneMessage}
+ message={pendingWrite}
isFirstMessage={false}
isLastMessage={true}
- status="ready"
+ status="streaming"
+ subagents={subagents}
/>
)
- expect(screen.queryByText(/Writing report\.html/)).not.toBeInTheDocument()
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
})
diff --git a/web-app/src/containers/MessageItem.tsx b/web-app/src/containers/MessageItem.tsx
index 4a998b3c6..236514e34 100644
--- a/web-app/src/containers/MessageItem.tsx
+++ b/web-app/src/containers/MessageItem.tsx
@@ -1,11 +1,10 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
-import { memo, useState, useCallback, useEffect, useRef, useMemo } from 'react'
+import { memo, useState, useCallback, useEffect, useMemo } from 'react'
import type { UIMessage, ChatStatus } from 'ai'
import { RenderMarkdown } from './RenderMarkdown'
import { cn } from '@/lib/utils'
import { formatDuration } from '@/lib/utils'
import {
- activeToolPart,
subagentActivityLabel,
usedSkillNames,
type ActivityLabel,
@@ -13,8 +12,6 @@ import {
import type { SubagentRun } from '@/types/coworkSession'
import { Loader } from 'lucide-react'
-/** How close to the cap the step counter becomes visible. */
-const BUDGET_WARN_STEPS = 5
import { ChainOfThoughtGroup } from './message/ChainOfThoughtGroup'
import {
CHAT_STATUS,
@@ -70,10 +67,6 @@ export type MessageItemProps = {
// Cowork only: the session's background subagent runs. Omitted in regular
// chat threads, which never spawn subagents.
subagents?: SubagentRun[]
- /** Cowork only: step budget for the running turn. Rendered next to the
- * activity label, and only once it is close to the cap — a counter that is
- * always visible is noise for the 95% of turns that never approach it. */
- budget?: { step: number; max: number }
isAnimating?: boolean
hideActions?: boolean
}
@@ -87,7 +80,6 @@ export const MessageItem = memo(
isAnimating,
hideActions,
subagents,
- budget,
reasoningContainerRef,
isReasoningAtBottom,
onReasoningScroll,
@@ -110,7 +102,6 @@ export const MessageItem = memo(
filename?: string
} | null>(null)
-
const handleRegenerate = useCallback(() => {
onRegenerate?.(message.id)
}, [onRegenerate, message.id])
@@ -137,7 +128,11 @@ export const MessageItem = memo(
return message.parts
.filter((part) => {
if (part.type !== 'file') return false
- const filePart = part as { type: 'file'; url?: string; mediaType?: string }
+ const filePart = part as {
+ type: 'file'
+ url?: string
+ mediaType?: string
+ }
return filePart.url && filePart.mediaType?.startsWith('image/')
})
.map((part) => (part as { url: string }).url)
@@ -170,61 +165,24 @@ export const MessageItem = memo(
})
}, [hasPendingToolCall, message.parts, pendingApprovals])
- // Tool parts carry no start timestamp; track first-seen time per
- // toolCallId locally so the elapsed-time readout is stable across
- // re-renders (not reset every render, not reused across a new call
- // with the same id after a session reset -- cleared once a step
- // becomes non-pending in the effect below).
- const toolStartedAtRef = useRef<Map<string, number>>(new Map())
-
- const pendingTool = useMemo(() => {
- if (!isLastMessage || message.role !== 'assistant') return null
- return activeToolPart(message.parts as never)
- }, [isLastMessage, message.role, message.parts])
const usedSkills = useMemo(
() => usedSkillNames(message.parts as never),
[message.parts]
)
- useEffect(() => {
- const map = toolStartedAtRef.current
- if (pendingTool) {
- // Keep only the current pending id; purge any stale entry that may
- // have lingered from a previous tool with a different toolCallId.
- map.forEach((_, key) => {
- if (key !== pendingTool.toolCallId) map.delete(key)
- })
- if (!map.has(pendingTool.toolCallId)) {
- map.set(pendingTool.toolCallId, Date.now())
- }
- } else {
- map.clear()
- }
- }, [pendingTool])
-
- const subagentLabel = useMemo<ActivityLabel>(() => {
+ // The activity row reports a running subagent, and only that.
+ //
+ // A tool call is already on screen as its own card one row above, with its
+ // name, its arguments and a ticking duration, so labelling it here printed
+ // the same thing twice a row apart -- the duplication the trace header was
+ // trimmed for earlier. A subagent has no card: it works in a lane of its
+ // own, so this is the only place its progress shows.
+ // Memoized so the reference is stable for the elapsed-time interval effect.
+ const activityLabel = useMemo<ActivityLabel>(() => {
if (!subagents || subagents.length === 0) return null
return subagentActivityLabel(subagents)
}, [subagents])
- // `await_subagent` is only the parent's blocking wrapper; the child is the
- // work actually in progress. Show its live activity instead of the
- // misleading "Await subagent" label. Other parent tools retain priority.
- // Memoized so the reference is stable for the elapsed-time interval effect.
- const activityLabel = useMemo<ActivityLabel>(() => {
- if (pendingTool?.toolName === 'await_subagent' && subagentLabel) {
- return subagentLabel
- }
- if (pendingTool) {
- return {
- text: pendingTool.text,
- startedAt:
- toolStartedAtRef.current.get(pendingTool.toolCallId) ?? Date.now(),
- }
- }
- return subagentLabel
- }, [pendingTool, subagentLabel])
-
// Re-render once a second while a label is showing, purely to advance the
// elapsed-time readout -- no state carried, just a tick.
const [, forceTick] = useState(0)
@@ -430,11 +388,7 @@ export const MessageItem = memo(
key={`${message.id}-${partIndex}`}
className={`flex ${justify} w-full my-2`}
>
- <audio
- controls
- src={part.url}
- className="max-w-[80%] rounded-md"
- />
+ <audio controls src={part.url} className="max-w-[80%] rounded-md" />
</div>
)
}
@@ -594,28 +548,31 @@ export const MessageItem = memo(
message.role === 'user' && !isFirstMessage && 'mt-8'
)}
>
-
{/* Render message parts. A turn alternates collapsed traces with
answer paragraphs, and with no gap the two read as one block. */}
<div className="flex flex-col gap-3">{renderedParts}</div>
- {message.role === 'assistant' && !isStreaming && webCitations.length > 0 && (
- <WebSourcesRow citations={webCitations} />
- )}
-
- {message.role === 'assistant' && !isStreaming && usedSkills.length > 0 && (
- <div
- aria-label={t('common:skillsUsedLabel')}
- className="mt-2 inline-flex rounded-full border border-border bg-muted/40 px-2.5 py-1 text-xs font-medium text-muted-foreground"
- >
- {t('common:skillsUsed', { skills: usedSkills.join(', ') })}
- </div>
- )}
+ {message.role === 'assistant' &&
+ !isStreaming &&
+ webCitations.length > 0 && <WebSourcesRow citations={webCitations} />}
+
+ {message.role === 'assistant' &&
+ !isStreaming &&
+ usedSkills.length > 0 && (
+ <div
+ aria-label={t('common:skillsUsedLabel')}
+ className="mt-2 inline-flex rounded-full border border-border bg-muted/40 px-2.5 py-1 text-xs font-medium text-muted-foreground"
+ >
+ {t('common:skillsUsed', { skills: usedSkills.join(', ') })}
+ </div>
+ )}
{isLastMessage &&
message.role === 'assistant' &&
!awaitingApproval &&
- (hasPendingToolCall || status === CHAT_STATUS.SUBMITTED || activityLabel) && (
+ (hasPendingToolCall ||
+ status === CHAT_STATUS.SUBMITTED ||
+ activityLabel) && (
<div className="mt-2">
{activityLabel ? (
<div
@@ -630,14 +587,6 @@ export const MessageItem = memo(
<span className="text-muted-foreground tabular-nums">
{formatDuration(activityLabel.startedAt)}
</span>
- {budget && budget.step >= budget.max - BUDGET_WARN_STEPS && (
- <span className="ml-auto text-muted-foreground tabular-nums">
- {t('common:budget.steps', {
- step: budget.step,
- max: budget.max,
- })}
- </span>
- )}
</div>
) : (
<PromptProgress hideIdle={hasPendingToolCall} />
@@ -659,7 +608,9 @@ export const MessageItem = memo(
{messageError}
</div>
</div>
- {selectedModel && onRegenerate && status !== CHAT_STATUS.STREAMING &&
+ {selectedModel &&
+ onRegenerate &&
+ status !== CHAT_STATUS.STREAMING &&
status !== CHAT_STATUS.SUBMITTED && (
<Button
variant="outline"
@@ -683,67 +634,72 @@ export const MessageItem = memo(
{versionNav}
<CopyButton text={getFullTextContent()} />
- {onEdit && status !== CHAT_STATUS.STREAMING &&
+ {onEdit &&
+ status !== CHAT_STATUS.STREAMING &&
status !== CHAT_STATUS.SUBMITTED && (
- <EditMessageDialog
- message={getFullTextContent()}
- imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
- onSave={handleEdit}
- />
- )}
+ <EditMessageDialog
+ message={getFullTextContent()}
+ imageUrls={imageUrls.length > 0 ? imageUrls : undefined}
+ onSave={handleEdit}
+ />
+ )}
- {onDelete && status !== CHAT_STATUS.STREAMING &&
+ {onDelete &&
+ status !== CHAT_STATUS.STREAMING &&
status !== CHAT_STATUS.SUBMITTED && (
- <DeleteMessageDialog onDelete={handleDelete} />
- )}
+ <DeleteMessageDialog onDelete={handleDelete} />
+ )}
</div>
)}
{/* Message actions for assistant messages (non-tool) */}
{message.role === 'assistant' && (
- <div className="flex items-center gap-2 text-muted-foreground text-xs">
- {!isStreaming && (
- <span className="text-muted-foreground">
- {formatDate(createdAt)}
- </span>
+ <div className="flex items-center gap-2 text-muted-foreground text-xs">
+ {!isStreaming && (
+ <span className="text-muted-foreground">
+ {formatDate(createdAt)}
+ </span>
+ )}
+ <div
+ className={cn(
+ 'flex items-center gap-1',
+ (isStreaming || hideActions) && 'hidden'
+ )}
+ >
+ {versionNav}
+ <CopyButton text={getFullTextContent()} />
+ <RememberButton text={getFullTextContent()} />
+
+ {onEdit && !isStreaming && (
+ <EditMessageDialog
+ message={getFullTextContent()}
+ onSave={handleEdit}
+ />
)}
- <div
- className={cn(
- 'flex items-center gap-1',
- (isStreaming || hideActions) && 'hidden'
- )}
- >
- {versionNav}
- <CopyButton text={getFullTextContent()} />
- <RememberButton text={getFullTextContent()} />
-
- {onEdit && !isStreaming && (
- <EditMessageDialog
- message={getFullTextContent()}
- onSave={handleEdit}
- />
- )}
- {onDelete && !isStreaming && (
- <DeleteMessageDialog onDelete={handleDelete} />
+ {onDelete && !isStreaming && (
+ <DeleteMessageDialog onDelete={handleDelete} />
+ )}
+
+ {selectedModel &&
+ onContinue &&
+ !isStreaming &&
+ isLastMessage &&
+ isStopped && (
+ <Button
+ variant="ghost"
+ size="icon-xs"
+ onClick={handleContinue}
+ title={t('chat:actions.continue')}
+ >
+ <IconPlayerPlay size={16} />
+ </Button>
)}
- {selectedModel &&
- onContinue &&
- !isStreaming &&
- isLastMessage &&
- isStopped && (
- <Button
- variant="ghost"
- size="icon-xs"
- onClick={handleContinue}
- title={t('chat:actions.continue')}
- >
- <IconPlayerPlay size={16} />
- </Button>
- )}
-
- {selectedModel && onRegenerate && !isStreaming && isLastMessage && (
+ {selectedModel &&
+ onRegenerate &&
+ !isStreaming &&
+ isLastMessage && (
<Button
variant="ghost"
size="icon-xs"
@@ -753,14 +709,11 @@ export const MessageItem = memo(
<IconRefresh size={16} />
</Button>
)}
- </div>
-
- <TokenSpeedIndicator
- streaming={isStreaming}
- metadata={metadata}
- />
</div>
- )}
+
+ <TokenSpeedIndicator streaming={isStreaming} metadata={metadata} />
+ </div>
+ )}
{/* Image Preview Dialog */}
{previewImage && (
diff --git a/web-app/src/containers/__tests__/MessageItem.test.tsx b/web-app/src/containers/__tests__/MessageItem.test.tsx
index 8f49eb4ca..3915e8a0e 100644
--- a/web-app/src/containers/__tests__/MessageItem.test.tsx
+++ b/web-app/src/containers/__tests__/MessageItem.test.tsx
@@ -108,7 +108,11 @@ vi.mock('@/components/ui/button', () => ({
}))
vi.mock('@/components/PromptProgress', () => ({
- PromptProgress: () => <div data-testid="prompt-progress" />,
+ // `hideIdle` is what suppresses the generic "Working…" fallback, and the real
+ // component renders nothing when it is set with no model load in flight, so
+ // the stand-in has to honour it or every caller looks like it shows a card.
+ PromptProgress: ({ hideIdle }: { hideIdle?: boolean }) =>
+ hideIdle ? null : <div data-testid="prompt-progress" />,
}))
const pendingApprovalsRef = vi.hoisted(() => ({ current: {} as any }))
@@ -465,7 +469,9 @@ describe('MessageItem', () => {
expect(screen.getByTestId('tool-output')).toHaveTextContent('boom')
})
- it('shows progress for an executing tool call (not awaiting approval)', () => {
+ /// The tool's own card names the call and ticks its duration one row above,
+ /// so a status row repeating it was the same thing twice.
+ it('leaves an executing tool call to its own card', () => {
render(
<MessageItem
message={
@@ -480,9 +486,8 @@ describe('MessageItem', () => {
status={'ready' as any}
/>
)
- // A pending tool call renders the new activity-status row, not PromptProgress.
expect(screen.queryByTestId('prompt-progress')).not.toBeInTheDocument()
- expect(screen.getByRole('status')).toHaveTextContent(/Search/)
+ expect(screen.queryByRole('status')).not.toBeInTheDocument()
})
it('shows a persistent badge for a successfully loaded skill', () => {
diff --git a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
index f3e006071..ffafe6f2d 100644
--- a/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
+++ b/web-app/src/hooks/__tests__/useToolCallRuntime.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
findRunningToolCallId,
useToolCallRuntime,
+ withToolTiming,
} from '../useToolCallRuntime'
const store = () => useToolCallRuntime.getState()
@@ -157,4 +158,27 @@ describe('useToolCallRuntime', () => {
store().recordDiff('a', 'first again')
expect(store().diffs).toEqual({ a: 'first again', b: 'second' })
})
+
+ /// Cowork dispatches serially and has no queue to report, but its cards still
+ /// need a duration -- without a timing entry the header shows a bare spinner.
+ it('times a single call from dispatch to settle', async () => {
+ const during = withToolTiming('a', async () => {
+ expect(store().timings['a']?.startedAt).toBeDefined()
+ expect(store().timings['a']?.endedAt).toBeUndefined()
+ return 'result'
+ })
+ await expect(during).resolves.toBe('result')
+ expect(store().timings['a']?.endedAt).toBeDefined()
+ })
+
+ it('settles the call even when it throws', async () => {
+ await expect(
+ withToolTiming('a', async () => {
+ throw new Error('boom')
+ })
+ ).rejects.toThrow('boom')
+ // Otherwise it holds the running slot forever, and every later call reads
+ // as queued behind a call that is already gone.
+ expect(store().timings['a']?.endedAt).toBeDefined()
+ })
})
diff --git a/web-app/src/hooks/useToolCallRuntime.ts b/web-app/src/hooks/useToolCallRuntime.ts
index 5bb419bce..b8d6af3af 100644
--- a/web-app/src/hooks/useToolCallRuntime.ts
+++ b/web-app/src/hooks/useToolCallRuntime.ts
@@ -154,3 +154,25 @@ export const useToolCallRuntime = create<ToolCallRuntimeState>()((set) => ({
reset: () => set({ queue: [], timings: {}, progress: {}, diffs: {} }),
}))
+
+/**
+ * Run one tool call with its timing recorded, so its card can show a live
+ * duration instead of a bare spinner.
+ *
+ * For a caller that dispatches serially and so has no queue to report -- each
+ * call is its own queue of one. The chat route enqueues a whole step up front
+ * instead, which is what lets it also show "queued, 2nd in line".
+ */
+export async function withToolTiming<T>(
+ toolCallId: string,
+ run: () => Promise<T>
+): Promise<T> {
+ const runtime = useToolCallRuntime.getState()
+ runtime.enqueue([toolCallId])
+ runtime.markRunning(toolCallId)
+ try {
+ return await run()
+ } finally {
+ useToolCallRuntime.getState().markSettled(toolCallId)
+ }
+}
diff --git a/web-app/src/lib/agentActivity.test.ts b/web-app/src/lib/agentActivity.test.ts
index 5c4b82898..9df5ff41d 100644
--- a/web-app/src/lib/agentActivity.test.ts
+++ b/web-app/src/lib/agentActivity.test.ts
@@ -3,7 +3,6 @@ import {
toolActivityText,
completedToolLabel,
usedSkillNames,
- activeToolPart,
subagentActivityLabel,
awaitsModel,
} from './agentActivity'
@@ -97,42 +96,6 @@ describe('usedSkillNames', () => {
})
})
-describe('activeToolPart', () => {
- it('returns null when no part is pending', () => {
- const parts = [
- { type: 'text', state: undefined },
- {
- type: 'tool-write',
- state: 'output-available',
- toolCallId: 'c1',
- input: { path: 'a.ts' },
- },
- ]
- expect(activeToolPart(parts)).toBeNull()
- })
-
- it('returns the pending tool part text and id', () => {
- const parts = [
- {
- type: 'tool-write',
- state: 'input-available',
- toolCallId: 'c1',
- input: { path: 'report.html' },
- },
- ]
- expect(activeToolPart(parts)).toEqual({
- toolCallId: 'c1',
- toolName: 'write',
- text: 'Writing report.html',
- })
- })
-
- it('ignores non-tool parts', () => {
- const parts = [{ type: 'text', state: 'input-available' }]
- expect(activeToolPart(parts)).toBeNull()
- })
-})
-
describe('subagentActivityLabel', () => {
it('returns null when no subagent is running', () => {
const subagents: SubagentRun[] = [
diff --git a/web-app/src/lib/agentActivity.ts b/web-app/src/lib/agentActivity.ts
index 2d23979da..a091a5d26 100644
--- a/web-app/src/lib/agentActivity.ts
+++ b/web-app/src/lib/agentActivity.ts
@@ -79,30 +79,9 @@ export function completedToolLabel(
type ToolPartLike = {
type: string
state?: string
- toolCallId?: string
input?: unknown
}
-const PENDING_STATES = new Set(['input-available', 'submitted'])
-
-/** Finds the first pending tool part; returns its id, name, and activity text. */
-export function activeToolPart(
- parts: ToolPartLike[]
-): { toolCallId: string; toolName: string; text: string } | null {
- for (const part of parts) {
- if (!part.type.startsWith('tool-')) continue
- if (!part.state || !PENDING_STATES.has(part.state)) continue
- if (!part.toolCallId) continue
- const toolName = part.type.slice('tool-'.length)
- return {
- toolCallId: part.toolCallId,
- toolName,
- text: toolActivityText(toolName, part.input),
- }
- }
- return null
-}
-
export function usedSkillNames(parts: ToolPartLike[]): string[] {
const names = new Set<string>()
for (const part of parts) {
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index 2b4a3849e..e1bfa696e 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -698,7 +698,6 @@
"placeholder": "Ask for a plan. The agent won't change any files."
},
"budget": {
- "steps": "step {{step}}/{{max}}",
"stoppedSteps": "Stopped at {{max}} steps. The agent hasn’t finished.",
"keepGoing": "Keep going",
"stoppedTokens": "Stopped — this session hit its token budget.",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 547362599..a2353762d 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -17,11 +17,7 @@ import { toast } from 'sonner'
import { invoke } from '@tauri-apps/api/core'
import { getLoadedModels } from '@janhq/tauri-plugin-llamacpp-api'
import { sessionWorkspacePath } from '@janhq/tauri-plugin-agent-tools-api'
-import {
- cn,
- getModelDisplayName,
- getProviderTitle,
-} from '@/lib/utils'
+import { cn, getModelDisplayName, getProviderTitle } from '@/lib/utils'
import { predefinedProviders } from '@/constants/providers'
import { providerHasRemoteApiKeys } from '@/lib/provider-api-keys'
import { runSlashCommand, SLASH_COMMANDS } from '@/lib/coworkCommands'
@@ -41,7 +37,7 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { MessageItem } from '@/containers/MessageItem'
import SkillSelector from '@/containers/SkillSelector'
import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
-import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
+import { useToolCallRuntime, withToolTiming } from '@/hooks/useToolCallRuntime'
import { PromptProgress } from '@/components/PromptProgress'
import { useAppState } from '@/hooks/useAppState'
import { useAutoScroll } from '@/hooks/useAutoScroll'
@@ -429,166 +425,175 @@ function CoworkPage() {
messageId: undefined,
} as any),
dispatch: (call) =>
- dispatchCoworkTool(call, {
- sessionId: sid,
- readOnlyFolder: current?.folder ?? null,
- planMode: current?.planMode ?? false,
- webSearch,
- onTodo: async (input) => {
- const result = applyTodoOp(
- useCoworkSessions
- .getState()
- .sessions.find((s) => s.id === sid)?.todos,
- input
- )
- if (result.error) {
- return { output: `ERROR: ${result.error}`, isError: true }
- }
- useCoworkSessions.getState().setTodos(sid, result.list)
- return { output: renderTodoResult(result.list) }
- },
- onAsk: (callId, input) =>
- new Promise<ToolOutcome>((resolve) => {
- const parsed = parseAskRequest(input)
- if (typeof parsed === 'string') {
- resolve({ output: `ERROR: ${parsed}`, isError: true })
- return
+ // Timed through the shared runtime store, which is what puts a
+ // ticking duration on the tool's own card. Calls run one at a time
+ // here, so each is its own queue of one.
+ withToolTiming(call.toolCallId, () =>
+ dispatchCoworkTool(call, {
+ sessionId: sid,
+ readOnlyFolder: current?.folder ?? null,
+ planMode: current?.planMode ?? false,
+ webSearch,
+ onTodo: async (input) => {
+ const result = applyTodoOp(
+ useCoworkSessions
+ .getState()
+ .sessions.find((s) => s.id === sid)?.todos,
+ input
+ )
+ if (result.error) {
+ return { output: `ERROR: ${result.error}`, isError: true }
}
- setAsk({ requestId: callId, request: parsed })
- askResolvers.current.set(callId, (answers) => {
- setAsk(null)
- resolve(renderAskResult(answers))
- })
- }),
- onTask: async (callId, input) => {
- const req = parseSubagentRequest(input)
- if (typeof req === 'string') {
- return { output: `ERROR: ${req}`, isError: true }
- }
- const resolved = resolveSubagent(
- req,
- subagentDefs,
- parentToolNames(transport.advertisedTools)
- )
- if ('error' in resolved) {
- return { output: `ERROR: ${resolved.error}`, isError: true }
- }
- if (!transport.model) {
- return {
- output:
- 'ERROR: no model is loaded for this run, so no subagent can start',
- isError: true,
+ useCoworkSessions.getState().setTodos(sid, result.list)
+ return { output: renderTodoResult(result.list) }
+ },
+ onAsk: (callId, input) =>
+ new Promise<ToolOutcome>((resolve) => {
+ const parsed = parseAskRequest(input)
+ if (typeof parsed === 'string') {
+ resolve({ output: `ERROR: ${parsed}`, isError: true })
+ return
+ }
+ setAsk({ requestId: callId, request: parsed })
+ askResolvers.current.set(callId, (answers) => {
+ setAsk(null)
+ resolve(renderAskResult(answers))
+ })
+ }),
+ onTask: async (callId, input) => {
+ const req = parseSubagentRequest(input)
+ if (typeof req === 'string') {
+ return { output: `ERROR: ${req}`, isError: true }
}
- }
- // Claimed before the child starts: the tool call returns now,
- // so the path it reports has to exist now.
- const saved = await reserveSubagentResult(
- sid,
- `${resolved.name}-${callId}`
- )
- inbox.begin()
- const child = runSubagent({
- resolved,
- description: req.description,
- // The parent's instance: a second one would mean a second
- // llama-server load for the same model.
- model: transport.model,
- parentTools: transport.advertisedTools,
- system: {
- workspacePath,
- readOnlyFolder: current?.folder ?? null,
- bashAvailable: sandboxEnforces(),
- },
- signal: controller.signal,
- sessionTokens: 0,
- // A child never gets `todo`/`ask`/`task`, so these refuse
- // rather than execute: a model can still emit a call to a
- // tool that was never advertised.
- dispatch: (call) =>
- dispatchCoworkTool(call, {
- sessionId: sid,
+ const resolved = resolveSubagent(
+ req,
+ subagentDefs,
+ parentToolNames(transport.advertisedTools)
+ )
+ if ('error' in resolved) {
+ return { output: `ERROR: ${resolved.error}`, isError: true }
+ }
+ if (!transport.model) {
+ return {
+ output:
+ 'ERROR: no model is loaded for this run, so no subagent can start',
+ isError: true,
+ }
+ }
+ // Claimed before the child starts: the tool call returns now,
+ // so the path it reports has to exist now.
+ const saved = await reserveSubagentResult(
+ sid,
+ `${resolved.name}-${callId}`
+ )
+ inbox.begin()
+ const child = runSubagent({
+ resolved,
+ description: req.description,
+ // The parent's instance: a second one would mean a second
+ // llama-server load for the same model.
+ model: transport.model,
+ parentTools: transport.advertisedTools,
+ system: {
+ workspacePath,
readOnlyFolder: current?.folder ?? null,
- planMode: current?.planMode ?? false,
- webSearch,
- onTodo: async () => ({
- output:
- 'The todo list belongs to the agent that dispatched you.',
- isError: true,
- }),
- onAsk: async () => ({
- output:
- 'You cannot ask the user questions. Decide, and say what you assumed.',
- isError: true,
- }),
- onTask: async () => ({
- output: 'A subagent cannot dispatch subagents.',
- isError: true,
+ bashAvailable: sandboxEnforces(),
+ },
+ signal: controller.signal,
+ sessionTokens: 0,
+ // A child never gets `todo`/`ask`/`task`, so these refuse
+ // rather than execute: a model can still emit a call to a
+ // tool that was never advertised.
+ dispatch: (call) =>
+ dispatchCoworkTool(call, {
+ sessionId: sid,
+ readOnlyFolder: current?.folder ?? null,
+ planMode: current?.planMode ?? false,
+ webSearch,
+ onTodo: async () => ({
+ output:
+ 'The todo list belongs to the agent that dispatched you.',
+ isError: true,
+ }),
+ onAsk: async () => ({
+ output:
+ 'You cannot ask the user questions. Decide, and say what you assumed.',
+ isError: true,
+ }),
+ onTask: async () => ({
+ output: 'A subagent cannot dispatch subagents.',
+ isError: true,
+ }),
}),
- }),
- events: {
- onQueued: (waiting) =>
- useCoworkRun
- .getState()
- .queueSubagent(sid, callId, resolved.name, waiting),
- onStart: () =>
- useCoworkRun
- .getState()
- .startSubagent(sid, callId, resolved.name),
- onInner: (event) =>
+ events: {
+ onQueued: (waiting) =>
+ useCoworkRun
+ .getState()
+ .queueSubagent(sid, callId, resolved.name, waiting),
+ onStart: () =>
+ useCoworkRun
+ .getState()
+ .startSubagent(sid, callId, resolved.name),
+ onInner: (event) =>
+ useCoworkRun
+ .getState()
+ .routeIntoSubagent(sid, callId, event),
+ onEnd: (usage) =>
+ useCoworkRun.getState().endSubagent(sid, callId, usage),
+ },
+ })
+ // Detached: the errand outlives its tool call, and the parent
+ // hears about it through the inbox instead.
+ void child
+ .then(async (done) => {
useCoworkRun
.getState()
- .routeIntoSubagent(sid, callId, event),
- onEnd: (usage) =>
- useCoworkRun.getState().endSubagent(sid, callId, usage),
- },
- })
- // Detached: the errand outlives its tool call, and the parent
- // hears about it through the inbox instead.
- void child
- .then(async (done) => {
- useCoworkRun
- .getState()
- .attachSubagentOutput(sid, callId, done.output)
- // Only a real answer is filed: an error message in the file
- // the parent was told to read would be indistinguishable
- // from the answer it expected.
- const filed =
- saved && !done.isError && done.output.trim()
- ? await fillSubagentResult(sid, saved.file, done.output)
- : false
- inbox.finish(
- subagentCompletionNotice({
- name: resolved.name,
- callId,
- savedPath: filed && saved ? saved.path : null,
- output: done.output,
- isError: done.isError,
- })
- )
- })
- .catch((e) =>
- // `runSubagent` does not throw, so this is the loop itself
- // failing. The count still has to come down or the run
- // would wait on it forever.
- inbox.finish(
- subagentCompletionNotice({
- name: resolved.name,
- callId,
- savedPath: null,
- output: e instanceof Error ? e.message : String(e),
- isError: true,
- })
+ .attachSubagentOutput(sid, callId, done.output)
+ // Only a real answer is filed: an error message in the file
+ // the parent was told to read would be indistinguishable
+ // from the answer it expected.
+ const filed =
+ saved && !done.isError && done.output.trim()
+ ? await fillSubagentResult(
+ sid,
+ saved.file,
+ done.output
+ )
+ : false
+ inbox.finish(
+ subagentCompletionNotice({
+ name: resolved.name,
+ callId,
+ savedPath: filed && saved ? saved.path : null,
+ output: done.output,
+ isError: done.isError,
+ })
+ )
+ })
+ .catch((e) =>
+ // `runSubagent` does not throw, so this is the loop itself
+ // failing. The count still has to come down or the run
+ // would wait on it forever.
+ inbox.finish(
+ subagentCompletionNotice({
+ name: resolved.name,
+ callId,
+ savedPath: null,
+ output: e instanceof Error ? e.message : String(e),
+ isError: true,
+ })
+ )
)
- )
- return {
- output: dispatchedSubagentResult(
- resolved.name,
- callId,
- saved?.path ?? null
- ),
- }
- },
- }),
+ return {
+ output: dispatchedSubagentResult(
+ resolved.name,
+ callId,
+ saved?.path ?? null
+ ),
+ }
+ },
+ })
+ ),
sink,
onStep: ({ result, turns, outcomes }) => {
if (result.usage) setLiveUsage(result.usage)
@@ -1024,64 +1029,64 @@ function CoworkPage() {
</div>
)}
<ChatInput
- showSpeedToken={false}
- initialMessage={true}
- scopeKey={session?.id}
- ownsToolSet={false}
- onSubmit={handleSubmit}
- onStop={handleStop}
- chatStatus={running ? 'streaming' : 'ready'}
- tokenSource={tokenSource}
- surfaceControls={
- <>
- <CoworkPlanToggle
- planMode={planMode}
- onChange={(next) => {
- if (session?.id)
- useCoworkSessions
- .getState()
- .setPlanMode(session.id, next)
- }}
- />
- <CoworkWorkspacePill
- folder={folder}
- gitBranch={gitBranch}
- onAttach={() => void attachFolder()}
- onDetach={detachFolder}
- />
- <CoworkSandboxChip />
- <CoworkTodoChip
- todos={session?.todos}
- open={rail?.kind === 'todos'}
- onToggle={() =>
- setRail((r) =>
- r?.kind === 'todos' ? null : { kind: 'todos' }
- )
- }
- />
- <CoworkTasksChip
- subagents={subagents}
- open={rail?.kind === 'tasks'}
- onToggle={() =>
- setRail((r) =>
- r?.kind === 'tasks' ? null : { kind: 'tasks' }
- )
- }
- />
- <CoworkChangesChip
- files={fileDiffs}
- open={rail?.kind === 'diff'}
- onToggle={() =>
- setRail((r) =>
- r?.kind === 'diff' ? null : { kind: 'diff' }
- )
- }
- />
- <div className="ml-auto flex items-center">
- <SkillSelector folder={folder} />
- </div>
- </>
- }
+ showSpeedToken={false}
+ initialMessage={true}
+ scopeKey={session?.id}
+ ownsToolSet={false}
+ onSubmit={handleSubmit}
+ onStop={handleStop}
+ chatStatus={running ? 'streaming' : 'ready'}
+ tokenSource={tokenSource}
+ surfaceControls={
+ <>
+ <CoworkPlanToggle
+ planMode={planMode}
+ onChange={(next) => {
+ if (session?.id)
+ useCoworkSessions
+ .getState()
+ .setPlanMode(session.id, next)
+ }}
+ />
+ <CoworkWorkspacePill
+ folder={folder}
+ gitBranch={gitBranch}
+ onAttach={() => void attachFolder()}
+ onDetach={detachFolder}
+ />
+ <CoworkSandboxChip />
+ <CoworkTodoChip
+ todos={session?.todos}
+ open={rail?.kind === 'todos'}
+ onToggle={() =>
+ setRail((r) =>
+ r?.kind === 'todos' ? null : { kind: 'todos' }
+ )
+ }
+ />
+ <CoworkTasksChip
+ subagents={subagents}
+ open={rail?.kind === 'tasks'}
+ onToggle={() =>
+ setRail((r) =>
+ r?.kind === 'tasks' ? null : { kind: 'tasks' }
+ )
+ }
+ />
+ <CoworkChangesChip
+ files={fileDiffs}
+ open={rail?.kind === 'diff'}
+ onToggle={() =>
+ setRail((r) =>
+ r?.kind === 'diff' ? null : { kind: 'diff' }
+ )
+ }
+ />
+ <div className="ml-auto flex items-center">
+ <SkillSelector folder={folder} />
+ </div>
+ </>
+ }
/>
</div>
</div>
@@ -1105,7 +1110,10 @@ function CoworkPage() {
/>
)}
{rail?.kind === 'tasks' && (
- <CoworkTasksPanel subagents={subagents} onClose={() => setRail(null)} />
+ <CoworkTasksPanel
+ subagents={subagents}
+ onClose={() => setRail(null)}
+ />
)}
</div>
</div>