diff --git a/DESIGN.md b/DESIGN.md index 4cdefdc..87f3640 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -98,7 +98,7 @@ Native-feeling UI sans handles controls, navigation, and conversation. The platf ## Layout -The default desktop is a resizable three-column workbench: sessions/resources at left, a fluid conversation center, and Changes/Files/Tools/Context at right. The left pane collapses to a 64px rail; the inspector collapses fully. The manual terminal occupies a bounded lower panel. Panel sizes persist locally, while viewport-relative caps protect the center at narrower widths. +The default desktop is a resizable three-column workbench: sessions/resources at left, a fluid conversation center, and a Work/Run/System inspector at right. Run opens on Agents by default, followed by Goal, Monitor, and Activity. Tool events appear in Activity. The left pane collapses to a 64px rail; the inspector collapses fully. The manual terminal occupies a bounded lower panel. Panel sizes persist locally, while viewport-relative caps protect the center at narrower widths. Virtualized lists own their scroll regions. Streaming content grows inside the timeline and never changes the outer grid. diff --git a/src/main/pi/PiRuntimeService.test.ts b/src/main/pi/PiRuntimeService.test.ts index 2652e1f..5d380a7 100644 --- a/src/main/pi/PiRuntimeService.test.ts +++ b/src/main/pi/PiRuntimeService.test.ts @@ -3939,7 +3939,7 @@ describe('PiRuntimeService', () => { const mainUser = { type: 'message', id: 'main-user', parentId: null, timestamp: '2025-01-01T00:00:01.000Z', message: { role: 'user', content: 'Saved prompt', timestamp: 1 } }; const mainAssistant = { type: 'message', id: 'main-assistant', parentId: 'main-user', timestamp: '2025-01-01T00:00:02.000Z', - message: { role: 'assistant', content: 'Saved answer', timestamp: 2, usage: { input: 2, output: 3, cacheRead: 5, cacheWrite: 0, totalTokens: 10, cost: { total: 0.125 } } }, + message: { role: 'assistant', content: 'Saved answer', timestamp: 2, stopReason: 'stop', durationMs: 250, usage: { input: 2, output: 3, cacheRead: 5, cacheWrite: 0, totalTokens: 10, cost: { total: 0.125 } } }, }; const toolResult = { type: 'message', id: 'tool-result', parentId: 'main-assistant', timestamp: '2025-01-01T00:00:03.000Z', @@ -3972,7 +3972,7 @@ describe('PiRuntimeService', () => { input: 20, output: 11, cacheRead: 16, cacheWrite: 2, totalTokens: 49, cost: 3.875, turns: 2, }); expect(state.tokenTelemetry?.history).toEqual([ - { input: 2, output: 3, cacheRead: 5, cacheWrite: 0, totalTokens: 10, cost: 0.125, timestamp: 2, durationMs: expect.any(Number) }, + { input: 2, output: 3, cacheRead: 5, cacheWrite: 0, totalTokens: 10, cost: 0.125, timestamp: 2, responseDurationMs: 250 }, ]); await service.dispose(); }); @@ -4510,7 +4510,7 @@ describe('PiRuntimeService', () => { { type: 'message', timestamp: '2025-01-01T00:00:04.000Z', message: { - role: 'assistant', timestamp: 4_000, + role: 'assistant', timestamp: 4_000, stopReason: 'stop', durationMs: 600, usage: { input: 50, output: 12, cacheRead: 100, cacheWrite: 0, totalTokens: 162, cost: { total: 0.011 } }, content: 'Second answer', }, @@ -4531,10 +4531,10 @@ describe('PiRuntimeService', () => { expect(fake.session.getSessionStats).toHaveBeenCalled(); expect(state.tokenTelemetry).toEqual({ session: { input: 177, output: 55, cacheRead: 684, cacheWrite: 26, totalTokens: 942, cost: 0.037, turns: 4 }, - latest: { input: 50, output: 12, cacheRead: 100, cacheWrite: 0, totalTokens: 162, cost: 0.011, timestamp: 4_000, durationMs: expect.any(Number) }, + latest: { input: 50, output: 12, cacheRead: 100, cacheWrite: 0, totalTokens: 162, cost: 0.011, timestamp: 4_000, responseDurationMs: 600 }, history: [ - { input: 100, output: 30, cacheRead: 500, cacheWrite: 20, reasoning: 12, totalTokens: 650, cost: 0.02, timestamp: 2_000, durationMs: expect.any(Number) }, - { input: 50, output: 12, cacheRead: 100, cacheWrite: 0, totalTokens: 162, cost: 0.011, timestamp: 4_000, durationMs: expect.any(Number) }, + { input: 100, output: 30, cacheRead: 500, cacheWrite: 20, reasoning: 12, totalTokens: 650, cost: 0.02, timestamp: 2_000 }, + { input: 50, output: 12, cacheRead: 100, cacheWrite: 0, totalTokens: 162, cost: 0.011, timestamp: 4_000, responseDurationMs: 600 }, ], }); await service.dispose(); diff --git a/src/main/pi/PiRuntimeService.ts b/src/main/pi/PiRuntimeService.ts index 9f19759..5c94931 100644 --- a/src/main/pi/PiRuntimeService.ts +++ b/src/main/pi/PiRuntimeService.ts @@ -75,6 +75,7 @@ import type { RuntimeState, RuntimeTokenTelemetry, RuntimeTool, + TokenMetrics, SubagentRun, SubagentUsage, SessionAttention, @@ -951,9 +952,7 @@ function validTokenCount(value: unknown): value is number { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0; } -type TokenUsageMetrics = Omit; - -function tokenUsageMetrics(usage: unknown, deriveTotal = false): TokenUsageMetrics | null { +function tokenUsageMetrics(usage: unknown, deriveTotal = false): TokenMetrics | null { if (!usage || typeof usage !== 'object') return null; const value = usage as { input?: unknown; @@ -992,13 +991,29 @@ function tokenUsageMetrics(usage: unknown, deriveTotal = false): TokenUsageMetri }; } -function tokenUsageSample(usage: unknown, timestamp: unknown, deriveTotal = false, completedAt?: unknown): RuntimeTokenTelemetry['history'][number] | null { - if (!validTokenCount(timestamp)) return null; - const metrics = tokenUsageMetrics(usage, deriveTotal); - if (!metrics) return null; - const completed = typeof completedAt === 'string' ? Date.parse(completedAt) : Number.NaN; - const durationMs = completed - timestamp; - return Number.isSafeInteger(durationMs) && durationMs > 0 ? { ...metrics, timestamp, durationMs } : { ...metrics, timestamp }; +function branchTokenUsage(branch: readonly unknown[], deriveTotal = false): Pick { + const history: RuntimeTokenTelemetry['history'] = []; + let latest: RuntimeTokenTelemetry['latest'] | undefined; + for (let index = branch.length - 1; index >= 0 && history.length < MAX_TOKEN_USAGE_HISTORY; index -= 1) { + const item = branch[index]; + if (!item || typeof item !== 'object') continue; + const entry = item as { type?: unknown; timestamp?: unknown; message?: unknown }; + const message = entry.type === 'message' ? entry.message : item; + if (!message || typeof message !== 'object') continue; + const assistant = message as { role?: unknown; timestamp?: unknown; usage?: unknown; durationMs?: unknown; stopReason?: unknown }; + if (assistant.role !== 'assistant') continue; + const timestamp = validTokenCount(assistant.timestamp) ? assistant.timestamp : typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN; + const metrics = tokenUsageMetrics(assistant.usage, deriveTotal); + const completed = assistant.stopReason === 'stop' || assistant.stopReason === 'length' || assistant.stopReason === 'toolUse'; + const sample = metrics && validTokenCount(timestamp) && timestamp <= 8.64e15 ? { + ...metrics, + timestamp, + ...(completed && metrics.output > 0 && validTokenCount(assistant.durationMs) && assistant.durationMs > 0 ? { responseDurationMs: assistant.durationMs } : {}), + } : null; + if (latest === undefined) latest = sample; + if (sample) history.push(sample); + } + return { history: history.reverse(), latest: latest ?? null }; } function sessionTokenTelemetry(session: AgentSession): RuntimeTokenTelemetry | undefined { @@ -1034,25 +1049,6 @@ function sessionTokenTelemetry(session: AgentSession): RuntimeTokenTelemetry | u } catch { branch = session.messages; } - const history: RuntimeTokenTelemetry['history'] = []; - for (let index = branch.length - 1; index >= 0 && history.length < MAX_TOKEN_USAGE_HISTORY; index -= 1) { - const item = branch[index]; - if (!item || typeof item !== 'object') continue; - const entry = item as { type?: unknown; timestamp?: unknown; message?: unknown }; - const message = entry.type === 'message' ? entry.message : item; - if (!message || typeof message !== 'object') continue; - const assistant = message as { role?: unknown; timestamp?: unknown; usage?: unknown }; - if (assistant.role !== 'assistant') continue; - const persistedTimestamp = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : undefined; - const sample = tokenUsageSample( - assistant.usage, - validTokenCount(assistant.timestamp) ? assistant.timestamp : persistedTimestamp, - false, - entry.timestamp, - ); - if (sample) history.push(sample); - } - history.sort((left, right) => left.timestamp - right.timestamp); return { session: { input: tokens.input, @@ -1063,8 +1059,7 @@ function sessionTokenTelemetry(session: AgentSession): RuntimeTokenTelemetry | u cost: value.cost, turns: value.assistantMessages, }, - latest: history.at(-1) ?? null, - history, + ...branchTokenUsage(branch), }; } @@ -1076,7 +1071,7 @@ function emptyTokenTelemetry(): RuntimeTokenTelemetry { }; } -function persistedEntryUsage(entry: Record): TokenUsageMetrics | null { +function persistedEntryUsage(entry: Record): TokenMetrics | null { if (entry.type === 'message' && entry.message && typeof entry.message === 'object') { const message = entry.message as { role?: unknown; usage?: unknown }; if (message.role !== 'assistant' && message.role !== 'toolResult') return null; @@ -1103,18 +1098,7 @@ function persistedSessionTokenTelemetry(entries: readonly Record left.timestamp - right.timestamp); - const boundedHistory = history.slice(-MAX_TOKEN_USAGE_HISTORY); - return { session, latest: boundedHistory.at(-1) ?? null, history: boundedHistory }; + return { session, ...branchTokenUsage(branch, true) }; } function usageTotal(usage: Pick): number { diff --git a/src/main/pi/SessionSnapshotReader.ts b/src/main/pi/SessionSnapshotReader.ts index 97b250d..df7153b 100644 --- a/src/main/pi/SessionSnapshotReader.ts +++ b/src/main/pi/SessionSnapshotReader.ts @@ -360,6 +360,7 @@ function compactEntry(entry: SnapshotRecord, extensionBudget: { remaining: numbe ...(typeof message.isError === 'boolean' ? { isError: message.isError } : {}), ...(boundedString(message.stopReason, 50) ? { stopReason: boundedString(message.stopReason, 50) } : {}), ...(record(message.usage) ? { usage: message.usage } : {}), + ...(message.role === 'assistant' && typeof message.durationMs === 'number' ? { durationMs: message.durationMs } : {}), ...(boundedString(message.provider, 200) ? { provider: boundedString(message.provider, 200) } : {}), ...(boundedString(message.model, 200) ? { model: boundedString(message.model, 200) } : {}), }; diff --git a/src/renderer/app/App.test.tsx b/src/renderer/app/App.test.tsx index 73f39bd..f69326c 100644 --- a/src/renderer/app/App.test.tsx +++ b/src/renderer/app/App.test.tsx @@ -60,7 +60,7 @@ describe('first-launch shell', () => { delete document.documentElement.dataset.holyShitMode; useUiStore.setState({ sidebarCollapsed: false, sidebarTab: 'sessions', inspectorCollapsed: false, leftWidth: 264, rightWidth: 332, - inspectorTab: 'changes', inspectorLastViews: { work: 'changes', run: 'goal', system: 'context' }, selectedAgent: null, + inspectorTab: 'changes', inspectorLastViews: { work: 'changes', run: 'sessions', system: 'context' }, selectedAgent: null, terminalOpen: false, browserOpen: false, musicPlayerEnabled: false, musicPlaying: false, sendMessageWithModifier: false, paletteOpen: false, settingsOpen: false, toast: null, composerDraftRequest: null, goalEditorOpen: false, }); diff --git a/src/renderer/features/chat/ConversationTimeline.tsx b/src/renderer/features/chat/ConversationTimeline.tsx index 09ddbd0..ebb9ec8 100644 --- a/src/renderer/features/chat/ConversationTimeline.tsx +++ b/src/renderer/features/chat/ConversationTimeline.tsx @@ -408,13 +408,16 @@ const DesktopConversationTimeline = memo(function DesktopConversationTimeline({ if (!flightDeckJump || flightDeckJump.projectPath !== projectPath || flightDeckJump.sessionId !== sessionId) return; const targetId = flightDeckJump.target.kind === 'message' ? flightDeckJump.target.timelineId ?? `message:${flightDeckJump.target.messageId}` - : flightDeckJump.target.kind === 'error' ? flightDeckJump.target.timelineId : null; + : flightDeckJump.target.kind === 'tool' ? `tool:${flightDeckJump.target.toolCallId}` + : flightDeckJump.target.kind === 'error' ? flightDeckJump.target.timelineId : null; if (!targetId) return; const index = displayOrder.indexOf(targetId); if (index >= 0) { virtuosoRef.current?.scrollToIndex({ index, align: 'center', behavior: 'auto' }); + if (flightDeckJump.target.kind === 'tool') return; } else { - showToast({ kind: 'info', title: 'Activity not retained', message: 'That conversation activity is no longer kept.' }); + showToast({ kind: 'info', title: 'Activity not retained', message: flightDeckJump.target.kind === 'tool' + ? 'That tool execution is not shown in the conversation.' : 'That conversation activity is no longer kept.' }); } clearFlightDeckJump(flightDeckJump.nonce); }, [clearFlightDeckJump, displayOrder, flightDeckJump, projectPath, sessionId, showToast]); diff --git a/src/renderer/features/chat/ToolCard.tsx b/src/renderer/features/chat/ToolCard.tsx index 04a137f..f5fee33 100644 --- a/src/renderer/features/chat/ToolCard.tsx +++ b/src/renderer/features/chat/ToolCard.tsx @@ -34,7 +34,7 @@ function presentedWorkflowToolStatus(toolStatus: RuntimeTool['status'], workflow return toolStatus; } -export const ToolCard = memo(function ToolCard({ toolCallId, compact = false, waitPollCount = 1, expansionCommand }: { toolCallId: string; compact?: boolean; waitPollCount?: number | undefined; expansionCommand?: DetailExpansionCommand }) { +export const ToolCard = memo(function ToolCard({ toolCallId, waitPollCount = 1, expansionCommand }: { toolCallId: string; waitPollCount?: number | undefined; expansionCommand?: DetailExpansionCommand }) { const { Symbol } = useSkinComponents(); const tool = useRuntimeStore((state) => state.toolsById[toolCallId]); const childStatusKey = useRuntimeStore((state) => state.toolsById[toolCallId]?.subagentRunIds @@ -75,7 +75,7 @@ export const ToolCard = memo(function ToolCard({ toolCallId, compact = false, wa const images = showImages && loadedImages?.length ? loadedImages : null; return ( -
+