源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s

This commit is contained in:
agent-radar committed 2026-09-01 20:17:27 +08:00
commit 2ed3415fb7
8018 files changed
+1936476

No files matched your search

@@ -0,0 +1,104 @@
import type { WorkspaceAgentSessionDetailToolCall } from "../../workspaceAgentSessionDetailViewModel";
import { extractAgentMcpToolTarget } from "../../agentMcpToolTarget";
import { normalizeAgentApprovalPurpose } from "../agentApprovalPurpose";
import type {
AgentApprovalItemVM,
AgentApprovalOptionVM
} from "../contracts/agentApprovalItemVM";
import { isExitPlanSwitchModeInput } from "../exitPlanOptions";
export function projectAgentApprovalItem(
call: WorkspaceAgentSessionDetailToolCall,
input: Record<string, unknown> | null,
output: Record<string, unknown> | null
): AgentApprovalItemVM | null {
const callType = normalizeToken(call.callType);
const toolName = normalizeToken(call.toolName);
if (callType !== "approval" && toolName !== "approval") {
return null;
}
const requestId =
stringValue(input?.requestId) ??
stringValue(call.payload?.requestId) ??
stringValue(output?.requestId);
if (!requestId) {
return null;
}
const options = normalizeAgentApprovalOptions(
input?.options ?? call.payload?.options
);
if (isExitPlanSwitchModeInput(input)) {
return null;
}
const mcpTarget = extractAgentMcpToolTarget({
input,
payload: call.payload,
toolName: call.toolName,
name: call.name
});
const approvalPurpose = normalizeAgentApprovalPurpose(
call.payload?.approvalPurpose
);
return {
kind: "approval",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
requestId,
callId: call.id.replace(/^call:/, ""),
...(approvalPurpose ? { approvalPurpose } : {}),
title: mcpTarget?.displayName ?? (call.summary.trim() || call.name),
toolName: call.toolName,
status: stringValue(call.payload?.status) ?? call.status,
input,
options,
output,
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
export function normalizeAgentApprovalOptions(
value: unknown
): AgentApprovalOptionVM[] {
const values = arrayValue(value) ?? [];
return values.flatMap((value) => {
const option = objectValue(value);
const id = stringValue(option?.optionId) ?? stringValue(option?.id);
if (!id) {
return [];
}
const label =
stringValue(option?.name) ??
stringValue(option?.label) ??
stringValue(option?.title) ??
stringValue(option?.kind) ??
id;
return [
{
id,
label,
kind: stringValue(option?.kind) ?? "",
...(stringValue(option?.description)
? { description: stringValue(option?.description) as string }
: {})
}
];
});
}
function normalizeToken(value: string | null | undefined): string {
return (value ?? "").trim().toLowerCase();
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function objectValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function arrayValue(value: unknown): unknown[] | null {
return Array.isArray(value) ? value : null;
}
@@ -0,0 +1,352 @@
import { describe, expect, it } from "vitest";
import {
normalizeAgentActivitySession,
type AgentActivityMessage,
type AgentActivitySession
} from "@tutti-os/agent-activity-core";
import type { WorkspaceAgentActivityCard } from "../../workspaceAgentActivityListViewModel";
import { projectWorkspaceAgentMessagesToConversationVM } from "./workspaceAgentMessageProjection";
import { projectAgentCollaborationVM } from "./agentCollaborationProjection";
import type { AgentMessageRowVM } from "../contracts/agentMessageRowVM";
describe("projectAgentCollaborationVM", () => {
it("projects the full typed payload", () => {
const vm = projectAgentCollaborationVM({
workspaceId: "room-1",
agentSessionId: "session-1",
status: "completed",
payload: {
runId: "run-1",
mode: "consult",
status: "completed",
triggerSource: "user",
triggerReason: "composer_consult",
modelPlanId: "plan-1",
model: "kimi-k2",
contextScope: "summary",
resultText: "Consider a version-key guard.",
durationMs: 5200,
usage: { inputTokens: 812, outputTokens: 96 },
adoption: "pending"
}
});
expect(vm).toEqual({
kind: "collaboration",
runId: "run-1",
workspaceId: "room-1",
agentSessionId: "session-1",
mode: "consult",
status: "completed",
triggerSource: "user",
triggerReason: "composer_consult",
targetSessionId: null,
targetAgentTargetId: null,
modelPlanId: "plan-1",
modelPlanName: null,
model: "kimi-k2",
contextScope: "summary",
resultText: "Consider a version-key guard.",
failureReason: null,
durationMs: 5200,
usage: { inputTokens: 812, outputTokens: 96 },
adoption: "pending"
});
});
it("falls back to the item status and rejects payloads without a run identity", () => {
const running = projectAgentCollaborationVM({
workspaceId: "room-1",
agentSessionId: "session-1",
status: "running",
payload: { runId: "run-2", mode: "consult" }
});
expect(running?.status).toBe("running");
expect(running?.adoption).toBe("not_applicable");
expect(running?.usage).toBeNull();
expect(
projectAgentCollaborationVM({
workspaceId: "room-1",
agentSessionId: "session-1",
status: "running",
payload: { mode: "consult" }
})
).toBeNull();
expect(
projectAgentCollaborationVM({
workspaceId: "room-1",
agentSessionId: "session-1",
status: "running",
payload: { runId: "run-3" }
})
).toBeNull();
});
});
describe("collaboration message kind projection", () => {
it("projects a running consult without result text into a collaboration row", () => {
const conversation = projectWorkspaceAgentMessagesToConversationVM({
activity: activity(),
session: session({ effectiveStatus: "working" }),
workspaceRoot: "/workspace/demo",
messages: [
message({
messageId: "user-1",
id: 1,
version: 1,
role: "user",
kind: "text",
payload: { text: "Please double-check the plan." }
}),
collaborationMessage({
id: 2,
version: 2,
status: "running",
payload: collaborationPayload({ status: "running" })
})
]
});
const row = collaborationRow(conversation.rows);
expect(row).not.toBeNull();
const content = row?.messages[0];
expect(content?.contentKind).toBe("collaboration");
expect(content?.collaboration).toMatchObject({
runId: "run-1",
mode: "consult",
status: "running",
triggerSource: "user",
modelPlanId: "plan-1",
model: "kimi-k2"
});
expect(content?.collaboration?.resultText).toBeNull();
});
it("updates the same collaboration row in place on status transitions", () => {
const conversation = projectWorkspaceAgentMessagesToConversationVM({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
messages: [
message({
messageId: "user-1",
id: 1,
version: 1,
role: "user",
kind: "text",
payload: { text: "Please double-check the plan." }
}),
collaborationMessage({
id: 2,
version: 2,
status: "running",
payload: collaborationPayload({ status: "running" })
}),
collaborationMessage({
id: 3,
version: 3,
status: "completed",
payload: collaborationPayload({
status: "completed",
resultText: "Looks right; watch the merge key.",
durationMs: 4100,
usage: { inputTokens: 900, outputTokens: 120 },
adoption: "pending"
})
})
]
});
const rows = conversation.rows.filter(
(row): row is AgentMessageRowVM =>
row.kind === "message" &&
row.messages.some((content) => content.contentKind === "collaboration")
);
expect(rows).toHaveLength(1);
const content = rows[0]?.messages[0];
expect(content?.collaboration).toMatchObject({
runId: "run-1",
status: "completed",
resultText: "Looks right; watch the merge key.",
durationMs: 4100,
usage: { inputTokens: 900, outputTokens: 120 },
adoption: "pending"
});
// Collaboration cards own their copy affordance; no transcript copy text.
expect(content?.copyText ?? null).toBeNull();
});
it("does not merge collaboration rows into adjacent assistant prose", () => {
const conversation = projectWorkspaceAgentMessagesToConversationVM({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
messages: [
message({
messageId: "assistant-1",
id: 1,
version: 1,
role: "assistant",
kind: "text",
payload: { text: "Starting a consult." }
}),
collaborationMessage({
id: 2,
version: 2,
status: "completed",
payload: collaborationPayload({
status: "completed",
resultText: "Advice text."
})
}),
message({
messageId: "assistant-2",
id: 3,
version: 3,
role: "assistant",
kind: "text",
payload: { text: "Continuing after the consult." }
})
]
});
const messageRows = conversation.rows.filter(
(row): row is AgentMessageRowVM => row.kind === "message"
);
expect(messageRows).toHaveLength(3);
expect(
messageRows.map((row) =>
row.messages.some((content) => content.contentKind === "collaboration")
)
).toEqual([false, true, false]);
});
});
function collaborationRow(
rows: readonly { kind: string }[]
): AgentMessageRowVM | null {
for (const row of rows) {
if (
row.kind === "message" &&
(row as AgentMessageRowVM).messages.some(
(content) => content.contentKind === "collaboration"
)
) {
return row as AgentMessageRowVM;
}
}
return null;
}
function collaborationPayload(
overrides: Record<string, unknown> = {}
): Record<string, unknown> {
return {
runId: "run-1",
mode: "consult",
status: "running",
triggerSource: "user",
triggerReason: "composer_consult",
modelPlanId: "plan-1",
model: "kimi-k2",
adoption: "not_applicable",
...overrides
};
}
function collaborationMessage(
overrides: Partial<AgentActivityMessage> & { id?: number }
): AgentActivityMessage {
return message({
messageId: "collab:run-1",
turnId: "turn-1",
role: "assistant",
kind: "collaboration",
...overrides
});
}
function message(
overrides: Partial<AgentActivityMessage> & { id?: number }
): AgentActivityMessage {
const { id: legacyStorageId, ...canonical } = overrides;
const version = overrides.version ?? legacyStorageId ?? 1;
return {
agentSessionId: "session-1",
messageId: "message-1",
version,
turnId: "turn-1",
role: "assistant",
kind: "text",
payload: {},
occurredAtUnixMs: version,
...canonical
};
}
function activity(
overrides: Partial<WorkspaceAgentActivityCard> = {}
): WorkspaceAgentActivityCard {
return {
id: "activity-1",
sessionId: "session-1",
agentName: "Codex",
agentProvider: "codex",
status: "working",
title: "Codex",
latestActivitySummary: "Working",
sortTimeUnixMs: 10,
changedFiles: [],
userId: "user-1",
userName: "Taylor",
userAvatarUrl: "",
...overrides
};
}
function session(
overrides: Partial<AgentActivitySession> & {
effectiveStatus?: string;
turnPhase?: string;
} = {}
): AgentActivitySession {
const { effectiveStatus, turnPhase, ...canonical } = overrides;
const phase = turnPhase ?? effectiveStatus;
const hasActiveTurn =
phase === "submitted" ||
phase === "running" ||
phase === "working" ||
phase === "waiting" ||
phase === "settling";
return normalizeAgentActivitySession({
activeTurnId: null,
latestTurnInteractions: [],
pendingInteractions: [],
workspaceId: "room-1",
agentSessionId: "session-1",
userId: "user-1",
provider: "codex",
providerSessionId: "provider-session-1",
cwd: "/workspace/demo",
title: "Codex",
createdAtUnixMs: 1,
updatedAtUnixMs: 10,
...(hasActiveTurn
? {
activeTurn: {
agentSessionId: "session-1",
origin: "user_prompt",
outcome: null,
phase: phase === "working" ? "running" : phase,
settledAtUnixMs: null,
startedAtUnixMs: 1,
turnId: "turn-1",
updatedAtUnixMs: 10
},
activeTurnId: "turn-1"
}
: {}),
...canonical
});
}
@@ -0,0 +1,109 @@
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import type { AgentCollaborationVM } from "../contracts/agentCollaborationVM";
export const COLLABORATION_TIMELINE_ITEM_TYPE = "collaboration";
export function isCollaborationTimelineItem(
item: Pick<WorkspaceAgentActivityTimelineItem, "itemType">
): boolean {
return (
item.itemType.trim().toLowerCase() === COLLABORATION_TIMELINE_ITEM_TYPE
);
}
/**
* Pure projection of one durable collaboration message payload into the typed
* card view model. Returns null when the payload has no run identity, so a
* malformed row degrades to a plain assistant message instead of a broken
* card.
*/
export function projectAgentCollaborationVM(
item: Pick<
WorkspaceAgentActivityTimelineItem,
"agentSessionId" | "payload" | "status" | "workspaceId"
>
): AgentCollaborationVM | null {
const payload = normalizedPayload(item.payload);
if (!payload) {
return null;
}
const runId = stringField(payload, "runId");
const mode = stringField(payload, "mode");
if (!runId || !mode) {
return null;
}
const status =
stringField(payload, "status") ?? item.status?.trim() ?? "running";
return {
kind: "collaboration",
runId,
workspaceId: item.workspaceId?.trim() || null,
agentSessionId: item.agentSessionId.trim() || null,
mode,
status,
triggerSource: stringField(payload, "triggerSource") ?? "user",
triggerReason: stringField(payload, "triggerReason"),
targetSessionId: stringField(payload, "targetSessionId"),
targetAgentTargetId: stringField(payload, "targetAgentTargetId"),
modelPlanId: stringField(payload, "modelPlanId"),
modelPlanName:
stringField(payload, "modelPlanName") ?? stringField(payload, "planName"),
model: stringField(payload, "model"),
contextScope: stringField(payload, "contextScope"),
resultText: stringField(payload, "resultText"),
failureReason: stringField(payload, "failureReason"),
durationMs: positiveNumberField(payload, "durationMs"),
usage: usageField(payload),
adoption: stringField(payload, "adoption") ?? "not_applicable"
};
}
function usageField(
payload: Record<string, unknown>
): AgentCollaborationVM["usage"] {
const usage = normalizedPayload(
payload.usage as WorkspaceAgentActivityTimelineItem["payload"]
);
if (!usage) {
return null;
}
const inputTokens = nonNegativeNumberValue(usage.inputTokens);
const outputTokens = nonNegativeNumberValue(usage.outputTokens);
if (inputTokens === null && outputTokens === null) {
return null;
}
return {
inputTokens: inputTokens ?? 0,
outputTokens: outputTokens ?? 0
};
}
function normalizedPayload(
payload: WorkspaceAgentActivityTimelineItem["payload"]
): Record<string, unknown> | null {
return payload && typeof payload === "object" && !Array.isArray(payload)
? payload
: null;
}
function stringField(
payload: Record<string, unknown>,
key: string
): string | null {
const value = payload[key];
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function positiveNumberField(
payload: Record<string, unknown>,
key: string
): number | null {
const value = nonNegativeNumberValue(payload[key]);
return value !== null && value > 0 ? value : null;
}
function nonNegativeNumberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? value
: null;
}
@@ -0,0 +1,763 @@
import type {
WorkspaceAgentSessionDetailTurn,
WorkspaceAgentSessionDetailViewModel
} from "../../workspaceAgentSessionDetailViewModel";
import { extractImageGenerationPreview } from "../../imageGenerationTool";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import type { AgentGeneratedImageRowVM } from "../contracts/agentGeneratedImageRowVM";
import type { AgentGoalControlRowVM } from "../contracts/agentGoalControlRowVM";
import type {
AgentMessageContentVM,
AgentMessageRowVM
} from "../contracts/agentMessageRowVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import type { AgentTranscriptRowVM } from "../contracts/agentTranscriptRowVM";
import { projectAgentMessageFinalText } from "./agentMessageFinalTextProjection";
import { computeAgentToolGroups } from "./agentToolGroupingProjection";
import { buildAgentTurnSequenceItems } from "./agentTurnSequenceProjection";
import { projectTurnRows } from "./agentTurnRowProjection";
import { projectAgentProcessingRow } from "./agentProcessingProjection";
import { projectAgentTurnSummaryRows } from "./agentTurnSummaryProjection";
export interface AgentConversationProjectionOptions {
avoidGroupingEdits?: boolean;
}
const RENDER_IRRELEVANT_TRANSCRIPT_ROW_FIELDS = new Set(["occurredAtUnixMs"]);
// Codex has emitted both the older "2%" wording and the current wording
// without a percentage; the percentage is diagnostic context, not identity.
const CODEX_SKILLS_CONTEXT_BUDGET_NOTICE_PATTERN =
/skill descriptions were shortened to fit the(?:\s+\d+(?:\.\d+)?%)?\s+skills context budget/i;
const CODEX_MODEL_METADATA_FALLBACK_NOTICE_FRAGMENT =
"defaulting to fallback metadata";
const MARKDOWN_IMAGE_PATTERN =
/!\[[^\]]*]\(\s*(?:<([^>]+)>|([^)\s]+))(?:\s+["'][^"']*["'])?\s*\)/g;
export function projectAgentConversationVM(
detail: WorkspaceAgentSessionDetailViewModel,
options: AgentConversationProjectionOptions = {}
): AgentConversationVM {
const rows: AgentTranscriptRowVM[] = [];
const turns = detail.turns;
const summariesByTurnId = new Map(
projectAgentTurnSummaryRows(detail).map((summary) => [
summary.turnId,
summary
])
);
turns.forEach((turn) => {
rows.push(
...projectTurnConversationRows(turn, detail.session.workspaceId, {
agentSessionId: detail.session.agentSessionId,
avoidGroupingEdits: options.avoidGroupingEdits
})
);
const summary = summariesByTurnId.get(turn.id);
if (summary) rows.push(summary);
});
const normalizedRows = dropCodexDiagnosticNotices(
dropRedundantErrorWarningNotices(
mergeAdjacentAssistantMessageRows(
dropRedundantCompactFailureEchoRows(
mergeAdjacentTransportRetryNoticeRows(rows)
)
)
)
);
const timelineRows = insertGoalControlRows(normalizedRows, detail);
const processing = projectAgentProcessingRow(detail, timelineRows);
const projectedRows = projectAgentMessageFinalText(
processing ? [...timelineRows, processing] : timelineRows,
detail
);
return {
activity: detail.activity,
workspaceRoot: detail.workspaceRoot,
sourceDetail: detail,
rows: projectedRows
};
}
function insertGoalControlRows(
rows: readonly AgentTranscriptRowVM[],
detail: WorkspaceAgentSessionDetailViewModel
): AgentTranscriptRowVM[] {
const controls = detail.goalControls ?? [];
if (controls.length === 0) {
return [...rows];
}
const merged = [...rows];
for (const control of controls) {
const row: AgentGoalControlRowVM = {
kind: "goal-control",
id: `goal-control:${control.id}`,
turnId: null,
action: control.action,
body: control.body,
occurredAtUnixMs: control.occurredAtUnixMs ?? null,
sourceTimelineItems: control.sourceTimelineItems
};
const insertionIndex = merged.findIndex(
(candidate) =>
row.occurredAtUnixMs !== null &&
candidate.occurredAtUnixMs !== null &&
candidate.occurredAtUnixMs > row.occurredAtUnixMs
);
if (insertionIndex < 0) {
merged.push(row);
} else {
merged.splice(insertionIndex, 0, row);
}
}
return merged;
}
function dropRedundantCompactFailureEchoRows(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const filtered: AgentTranscriptRowVM[] = [];
for (const row of rows) {
const previous = filtered.at(-1);
if (
isSingleCompactFailureNoticeRow(previous) &&
isSinglePlainAssistantMessageRow(row) &&
previous.turnId === row.turnId &&
previous.messages[0]?.systemNotice?.detail?.trim() ===
row.messages[0]?.body.trim()
) {
continue;
}
filtered.push(row);
}
return filtered;
}
function isSingleCompactFailureNoticeRow(
row: AgentTranscriptRowVM | undefined
): row is AgentMessageRowVM {
if (
!row ||
row.kind !== "message" ||
row.speaker !== "assistant" ||
row.thinking.length > 0 ||
row.messages.length !== 1
) {
return false;
}
const notice = row.messages[0]?.systemNotice;
return (
notice?.command === "compact" &&
notice.commandStatus === "failed" &&
Boolean(notice.detail?.trim())
);
}
function isSinglePlainAssistantMessageRow(
row: AgentTranscriptRowVM
): row is AgentMessageRowVM {
return (
row.kind === "message" &&
row.speaker === "assistant" &&
row.thinking.length === 0 &&
row.messages.length === 1 &&
!row.messages[0]?.visibleError &&
!row.messages[0]?.systemNotice
);
}
/**
* Latest plain assistant reply in the projected transcript (newest first).
* Used as the optional consult context; error cards, system notices, plan and
* collaboration cards are skipped so only ordinary reply text qualifies.
*/
export function latestAssistantMessageText(
conversation: Pick<AgentConversationVM, "rows"> | null | undefined
): string | null {
if (!conversation) {
return null;
}
for (let rowIndex = conversation.rows.length - 1; rowIndex >= 0; rowIndex--) {
const row = conversation.rows[rowIndex];
if (row?.kind !== "message" || row.speaker !== "assistant") {
continue;
}
for (
let messageIndex = row.messages.length - 1;
messageIndex >= 0;
messageIndex--
) {
const message = row.messages[messageIndex];
if (!message || message.visibleError || message.systemNotice) {
continue;
}
if (message.contentKind && message.contentKind !== "text") {
continue;
}
const body = message.body.trim();
if (body) {
return body;
}
}
}
return null;
}
export function reconcileProjectedAgentConversationVM(
previous: AgentConversationVM | null | undefined,
next: AgentConversationVM
): AgentConversationVM {
if (!previous) {
return next;
}
const previousRowsById = new Map(previous.rows.map((row) => [row.id, row]));
let reusedRowCount = 0;
const rows = next.rows.map((row) => {
const previousRow = previousRowsById.get(row.id);
if (previousRow && equivalentTranscriptRowForRender(previousRow, row)) {
reusedRowCount += 1;
return previousRow;
}
return row;
});
const rowsArrayReused =
reusedRowCount === next.rows.length &&
next.rows.length === previous.rows.length &&
next.rows.every((_row, index) => rows[index] === previous.rows[index]);
return {
...next,
rows: rowsArrayReused ? previous.rows : rows
};
}
function equivalentTranscriptRowForRender(
previous: AgentTranscriptRowVM,
next: AgentTranscriptRowVM
): boolean {
return equivalentValueIgnoringKeys(
previous,
next,
RENDER_IRRELEVANT_TRANSCRIPT_ROW_FIELDS
);
}
function equivalentValueIgnoringKeys(
left: unknown,
right: unknown,
ignoredKeys: ReadonlySet<string>
): boolean {
if (Object.is(left, right)) {
return true;
}
if (typeof left !== typeof right || left === null || right === null) {
return false;
}
if (Array.isArray(left) || Array.isArray(right)) {
return (
Array.isArray(left) &&
Array.isArray(right) &&
left.length === right.length &&
left.every((value, index) =>
equivalentValueIgnoringKeys(value, right[index], ignoredKeys)
)
);
}
if (typeof left !== "object" || typeof right !== "object") {
return false;
}
const leftRecord = left as Record<string, unknown>;
const rightRecord = right as Record<string, unknown>;
const leftKeys = Object.keys(leftRecord).filter(
(key) => !ignoredKeys.has(key)
);
const rightKeys = Object.keys(rightRecord).filter(
(key) => !ignoredKeys.has(key)
);
return (
leftKeys.length === rightKeys.length &&
leftKeys.every(
(key) =>
Object.prototype.hasOwnProperty.call(rightRecord, key) &&
equivalentValueIgnoringKeys(
leftRecord[key],
rightRecord[key],
ignoredKeys
)
)
);
}
function mergeAdjacentAssistantMessageRows(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const merged: AgentTranscriptRowVM[] = [];
for (const row of rows) {
const previous = merged.at(-1);
if (
isMergeableAssistantMessageRow(previous) &&
canMergeAdjacentAssistantMessageRows(previous, row)
) {
const lastMessage = previous.messages.at(-1);
const nextMessage = row.messages[0];
if (lastMessage && nextMessage) {
lastMessage.body = joinAdjacentAssistantMessageBodies(
lastMessage.body,
nextMessage.body,
nextMessage.statusKind
);
lastMessage.statusKind =
nextMessage.statusKind ??
(lastMessage.statusKind === "working" ||
lastMessage.statusKind === "waiting"
? null
: lastMessage.statusKind) ??
null;
lastMessage.occurredAtUnixMs =
nextMessage.occurredAtUnixMs ?? lastMessage.occurredAtUnixMs;
}
if (row.messages.length > 1) {
previous.messages.push(...row.messages.slice(1));
}
previous.occurredAtUnixMs =
row.occurredAtUnixMs ?? previous.occurredAtUnixMs;
continue;
}
merged.push(row);
}
return merged;
}
/**
* Join adjacent assistant bodies without fusing independent Markdown blocks.
* Active streaming fragments remain byte-for-byte continuations, while a
* settled fragment gains a line boundary when neither side provides one.
*/
function joinAdjacentAssistantMessageBodies(
previousBody: string,
nextBody: string,
nextStatusKind: AgentMessageContentVM["statusKind"]
): string {
if (nextStatusKind === "working" || nextStatusKind === "waiting") {
return previousBody + nextBody;
}
if (
previousBody.endsWith("\n") ||
nextBody.startsWith("\n") ||
nextBody.startsWith("\r")
) {
return previousBody + nextBody;
}
return `${previousBody}\n${nextBody}`;
}
function dropCodexDiagnosticNotices(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const filteredRows: AgentTranscriptRowVM[] = [];
for (const row of rows) {
if (row.kind !== "message" || row.speaker !== "assistant") {
filteredRows.push(row);
continue;
}
const messages = row.messages.filter(
(message) => !isCodexDiagnosticNotice(message)
);
if (messages.length === 0 && row.thinking.length === 0) {
continue;
}
if (messages.length === row.messages.length) {
filteredRows.push(row);
continue;
}
filteredRows.push({ ...row, messages });
}
return filteredRows;
}
function isCodexDiagnosticNotice(message: AgentMessageContentVM): boolean {
const notice = message.systemNotice;
if (!notice || notice.noticeKind !== "warning") {
return false;
}
const text = [notice.title, notice.detail, message.body]
.filter(Boolean)
.join("\n")
.toLowerCase();
if (CODEX_SKILLS_CONTEXT_BUDGET_NOTICE_PATTERN.test(text)) {
// Persisted skill notices may omit source, but an explicitly non-runtime
// notice must remain visible even when its text matches this diagnostic.
return !notice.source || notice.source === "runtime";
}
return (
notice.source === "runtime" &&
text.includes(CODEX_MODEL_METADATA_FALLBACK_NOTICE_FRAGMENT)
);
}
function dropRedundantErrorWarningNotices(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const turnsWithVisibleError = new Set<string>();
for (const row of rows) {
if (row.kind !== "message" || row.speaker !== "assistant") {
continue;
}
for (const message of row.messages) {
if (message.visibleError) {
turnsWithVisibleError.add(row.turnId);
}
}
}
if (turnsWithVisibleError.size === 0) {
return [...rows];
}
const filteredRows: AgentTranscriptRowVM[] = [];
for (const row of rows) {
if (row.kind !== "message" || row.speaker !== "assistant") {
filteredRows.push(row);
continue;
}
if (!turnsWithVisibleError.has(row.turnId)) {
filteredRows.push(row);
continue;
}
const messages = row.messages.filter(
(message) => !isRedundantErrorWarningNotice(message)
);
if (messages.length === 0) {
continue;
}
if (messages.length === row.messages.length) {
filteredRows.push(row);
continue;
}
filteredRows.push({ ...row, messages });
}
return filteredRows;
}
function isRedundantErrorWarningNotice(
message: AgentMessageContentVM
): boolean {
const notice = message.systemNotice;
if (!notice || notice.noticeKind !== "warning") {
return false;
}
const title = notice.title?.trim() ?? "";
return title === "Codex reported an error.";
}
function mergeAdjacentTransportRetryNoticeRows(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const merged: AgentTranscriptRowVM[] = [];
for (const row of rows) {
const previous = merged.at(-1);
if (
isSingleTransportRetryNoticeRow(previous) &&
isSingleTransportRetryNoticeRow(row) &&
previous.turnId === row.turnId
) {
const previousMessage = previous.messages[0];
const nextMessage = row.messages[0];
if (!previousMessage || !nextMessage) {
merged.push(row);
continue;
}
const sourceTimelineItems = mergeSourceTimelineItems(
previousMessage.sourceTimelineItems,
nextMessage.sourceTimelineItems
);
previous.messages[0] = {
...previousMessage,
body: nextMessage.body || previousMessage.body,
systemNotice: nextMessage.systemNotice ?? previousMessage.systemNotice,
statusKind:
nextMessage.statusKind ?? previousMessage.statusKind ?? null,
occurredAtUnixMs:
nextMessage.occurredAtUnixMs ?? previousMessage.occurredAtUnixMs,
...(sourceTimelineItems ? { sourceTimelineItems } : {})
};
previous.occurredAtUnixMs =
row.occurredAtUnixMs ?? previous.occurredAtUnixMs;
continue;
}
merged.push(row);
}
return merged;
}
function isSingleTransportRetryNoticeRow(
row: AgentTranscriptRowVM | undefined
): row is AgentMessageRowVM {
if (
!row ||
row.kind !== "message" ||
row.speaker !== "assistant" ||
row.thinking.length > 0 ||
row.messages.length !== 1
) {
return false;
}
return row.messages[0]?.systemNotice?.noticeKind === "transport_retry";
}
function mergeSourceTimelineItems(
previous: AgentMessageContentVM["sourceTimelineItems"],
next: AgentMessageContentVM["sourceTimelineItems"]
): AgentMessageContentVM["sourceTimelineItems"] {
if (!previous || previous.length === 0) {
return next;
}
if (!next || next.length === 0) {
return previous;
}
return [...previous, ...next];
}
function isMergeableAssistantMessageRow(
row: AgentTranscriptRowVM | undefined
): row is AgentMessageRowVM {
return Boolean(
row &&
row.kind === "message" &&
row.speaker === "assistant" &&
row.thinking.length === 0 &&
!row.messages.some(isSpecialAssistantMessage)
);
}
function canMergeAdjacentAssistantMessageRows(
previous: AgentMessageRowVM,
next: AgentTranscriptRowVM
): next is AgentMessageRowVM {
return (
next.kind === "message" &&
next.speaker === "assistant" &&
next.thinking.length === 0 &&
previous.turnId === next.turnId &&
!next.messages.some(isSpecialAssistantMessage)
);
}
function isSpecialAssistantMessage(message: {
visibleError?: unknown;
systemNotice?: unknown;
contentKind?: string;
}): boolean {
return Boolean(
message.visibleError ||
message.systemNotice ||
message.contentKind === "plan" ||
message.contentKind === "collaboration" ||
message.contentKind === "tutti-plan-issue-link"
);
}
function projectTurnConversationRows(
turn: WorkspaceAgentSessionDetailTurn,
workspaceId: string | null | undefined,
options: {
agentSessionId: string;
avoidGroupingEdits?: boolean;
}
): AgentTranscriptRowVM[] {
const sequence = buildAgentTurnSequenceItems(turn, workspaceId);
const { groups, groupedIndices, suppressedIndices } = computeAgentToolGroups(
sequence,
options
);
const skippedIndices = new Set([...groupedIndices, ...suppressedIndices]);
return promoteGeneratedImageRows(
projectTurnRows(
sequence,
groups,
skippedIndices,
turn.id,
options.agentSessionId
)
);
}
function promoteGeneratedImageRows(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const promoted: AgentTranscriptRowVM[] = [];
for (const row of rows) {
promoted.push(row);
if (row.kind !== "tool-group") {
continue;
}
for (const call of row.calls) {
const artifact = projectGeneratedImageRow(call, row.turnId);
if (artifact) {
promoted.push(artifact);
}
}
}
return dropDuplicateGeneratedImageMarkdown(promoted);
}
function dropDuplicateGeneratedImageMarkdown(
rows: readonly AgentTranscriptRowVM[]
): AgentTranscriptRowVM[] {
const generatedImagesByTurn = new Map<string, Set<string>>();
for (const row of rows) {
if (row.kind !== "generated-image") {
continue;
}
const reference = normalizeGeneratedImageReference(row.uri);
if (!reference) {
continue;
}
const references = generatedImagesByTurn.get(row.turnId) ?? new Set();
references.add(reference);
generatedImagesByTurn.set(row.turnId, references);
}
if (generatedImagesByTurn.size === 0) {
return [...rows];
}
const filtered: AgentTranscriptRowVM[] = [];
for (const row of rows) {
if (row.kind !== "message" || row.speaker !== "assistant") {
filtered.push(row);
continue;
}
const generatedImages = generatedImagesByTurn.get(row.turnId);
if (!generatedImages) {
filtered.push(row);
continue;
}
let changed = false;
const messages = row.messages.flatMap((message) => {
const body = removeGeneratedImageMarkdown(message.body, generatedImages);
if (body === message.body) {
return [message];
}
changed = true;
return body ? [{ ...message, body }] : [];
});
if (messages.length === 0 && row.thinking.length === 0) {
continue;
}
filtered.push(changed ? { ...row, messages } : row);
}
return filtered;
}
function removeGeneratedImageMarkdown(
body: string,
generatedImages: ReadonlySet<string>
): string {
let removed = false;
const next = body.replace(
MARKDOWN_IMAGE_PATTERN,
(
match,
angleReference: string | undefined,
plainReference: string | undefined
) => {
const reference = normalizeGeneratedImageReference(
angleReference ?? plainReference ?? ""
);
if (!reference || !generatedImages.has(reference)) {
return match;
}
removed = true;
return "";
}
);
return removed
? next
.replace(/[ \t]+\n/g, "\n")
.replace(/\n{3,}/g, "\n\n")
.trim()
: body;
}
function normalizeGeneratedImageReference(reference: string): string | null {
let normalized = reference.trim();
if (!normalized) {
return null;
}
if (/^file:\/\//i.test(normalized)) {
if (!URL.canParse(normalized)) {
return null;
}
normalized = new URL(normalized).pathname;
} else if (/^[a-z][a-z\d+.-]*:\/\//i.test(normalized)) {
return URL.canParse(normalized) ? new URL(normalized).href : normalized;
}
normalized = decodePercentEncodedReference(normalized);
normalized = normalized.replaceAll("\\", "/");
const prefix = normalized.startsWith("/") ? "/" : "";
const parts: string[] = [];
for (const part of normalized.split("/")) {
if (!part || part === ".") {
continue;
}
if (part === ".." && parts.length > 0) {
parts.pop();
continue;
}
parts.push(part);
}
const collapsed = `${prefix}${parts.join("/")}`;
return /^[a-z]:\//i.test(collapsed) ? collapsed.toLowerCase() : collapsed;
}
function decodePercentEncodedReference(reference: string): string {
return reference.replace(/(?:%[a-f\d]{2})+/gi, (encodedRun) => {
const bytes = encodedRun
.slice(1)
.split("%")
.map((hex) => Number.parseInt(hex, 16));
return new TextDecoder().decode(Uint8Array.from(bytes));
});
}
function projectGeneratedImageRow(
call: AgentToolCallVM,
turnId: string
): AgentGeneratedImageRowVM | null {
if (
call.rendererKind !== "image-generation" ||
call.statusKind !== "completed"
) {
return null;
}
const image = extractImageGenerationPreview({
toolName: call.toolName,
displayName: call.name,
outputSavedPath: call.output?.savedPath,
outputSavedPaths: call.output?.savedPaths,
outputMimeType: call.output?.imageMimeType,
outputText: call.output?.text,
inputPrompt: call.input?.prompt,
payloadInputPrompt:
call.payload?.input &&
typeof call.payload.input === "object" &&
!Array.isArray(call.payload.input)
? (call.payload.input as Record<string, unknown>).prompt
: null
});
if (!image.imageUri) {
return null;
}
return {
kind: "generated-image",
id: `generated-image:${call.id}`,
turnId,
sourceCallId: call.id,
uri: image.imageUri,
mimeType: image.mimeType,
prompt: image.prompt,
occurredAtUnixMs: call.occurredAtUnixMs
};
}
@@ -0,0 +1,406 @@
import type { WorkspaceAgentSessionDetailTurn } from "../../workspaceAgentSessionDetailViewModel";
import { linkifyPastedTextReferences } from "../../pastedTextReferenceProjection";
import { parseTuttiModeCheckpointWake } from "../tuttiModeCheckpointWakeMarker";
import type {
AgentMessageContentVM,
AgentMessageRowVM
} from "../contracts/agentMessageRowVM";
export function projectConversationUserRow(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number],
fallbackTurnId: string,
workspaceId: string | null | undefined
): AgentMessageRowVM {
const turnId = message.turnId ?? fallbackTurnId;
const rawFirstTextBlock = firstRawUserPromptTextBlock(message);
return {
kind: "message",
id: `message:user:${message.id}`,
turnId,
speaker: "user",
rawFirstTextBlock,
messages: projectUserMessageContentParts(
message,
turnId,
workspaceId,
rawFirstTextBlock
),
thinking: [],
occurredAtUnixMs: message.occurredAtUnixMs ?? null
};
}
// A daemon checkpoint-wake prompt is detected by its agent-inert sentinel line
// (parseTuttiModeCheckpointWake), never by matching the prompt prose. When
// present we render a single compact summary card instead of the wall of text;
// the full prompt stays available behind the card's expand affordance.
function tuttiModeCheckpointWakePart(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number],
turnId: string,
rawFirstTextBlock: string | null
): AgentMessageContentVM | null {
const parsed = parseTuttiModeCheckpointWake(rawFirstTextBlock);
if (!parsed) {
return null;
}
return {
kind: "message-content",
id: `${message.id}:checkpoint-wake`,
turnId,
body: parsed.body,
presentationKind: "content",
contentKind: "tutti-checkpoint-wake",
checkpointWake: parsed.marker,
copyText: parsed.body,
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
sourceTimelineItems: message.sourceTimelineItems
};
}
function firstRawUserPromptTextBlock(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number]
): string | null {
for (const item of message.sourceTimelineItems ?? []) {
const content = item.payload?.content;
if (!Array.isArray(content)) {
continue;
}
for (const raw of content) {
const block = promptContentRecord(raw);
if (
block?.type === "text" &&
typeof block.text === "string" &&
block.kind !== "selected-text"
) {
return block.text;
}
}
}
return null;
}
function projectUserMessageContentParts(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number],
turnId: string,
workspaceId: string | null | undefined,
rawFirstTextBlock: string | null
): AgentMessageContentVM[] {
const checkpointWake = tuttiModeCheckpointWakePart(
message,
turnId,
rawFirstTextBlock
);
if (checkpointWake) {
return [checkpointWake];
}
const blocks = userPromptContentBlocks(message, workspaceId);
if (blocks.length === 0) {
return [textPart(message, turnId)];
}
const parts: AgentMessageContentVM[] = [];
const selectedTextBlocks = blocks.filter(
(block): block is UserPromptTextBlock =>
block.type === "text" && block.kind === "selected-text"
);
if (selectedTextBlocks.length > 0) {
// Reference context is a presentation-only part. The ordinary text part
// remains the sole editable/copyable user message, matching the composer
// question bubble while keeping the selected boundary visible.
parts.push({
kind: "message-content",
id: `${message.id}:selected-text`,
turnId,
body: "",
presentationKind: "content",
contentKind: "selected-text",
selectedText: {
count: selectedTextBlocks.length,
texts: selectedTextBlocks.map((block) =>
stripSelectedTextPrefix(block.text)
)
},
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
sourceTimelineItems: message.sourceTimelineItems
});
}
const imageBlocks = blocks.filter(
(block): block is UserPromptImageBlock => block.type === "image"
);
if (imageBlocks.length > 0) {
parts.push({
kind: "message-content",
id: `${message.id}:images:0`,
turnId,
body: "",
presentationKind: "content",
contentKind: "image-grid",
images: imageBlocks.map((image, index) => ({
id: `${message.id}:image:${index}`,
workspaceId: image.workspaceId,
agentSessionId: image.agentSessionId,
attachmentId: image.attachmentId,
mimeType: image.mimeType,
name: image.name,
data: image.data,
url: image.url,
path: image.path
})),
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
sourceTimelineItems: message.sourceTimelineItems
});
}
blocks.forEach((block, index) => {
if (
block.type === "image" ||
block.text.trim() === "" ||
block.kind === "selected-text"
) {
return;
}
parts.push({
kind: "message-content",
id: `${message.id}:text:${index}`,
turnId,
body: block.text,
presentationKind: "content",
contentKind: "text",
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
sourceTimelineItems: message.sourceTimelineItems
});
});
return parts.length > 0 ? parts : [textPart(message, turnId)];
}
function textPart(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number],
turnId: string
): AgentMessageContentVM {
return {
kind: "message-content",
id: message.id,
turnId,
body: message.body,
presentationKind: "content",
contentKind: "text",
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
sourceTimelineItems: message.sourceTimelineItems
};
}
type UserPromptContentBlock = UserPromptTextBlock | UserPromptImageBlock;
interface UserPromptTextBlock {
type: "text";
text: string;
kind?: string;
}
interface UserPromptImageBlock {
type: "image";
workspaceId?: string | null;
agentSessionId: string;
attachmentId?: string | null;
mimeType: string;
name?: string | null;
data?: string | null;
url?: string | null;
path?: string | null;
}
function userPromptContentBlocks(
message: WorkspaceAgentSessionDetailTurn["userMessages"][number],
fallbackWorkspaceId: string | null | undefined
): UserPromptContentBlock[] {
const item = message.sourceTimelineItems?.find((candidate) =>
Array.isArray(candidate.payload?.content)
);
const content = Array.isArray(item?.payload?.content)
? item.payload.content
: null;
if (!content) return [];
const displayPrompt = firstString(
message.sourceTimelineItems?.map((candidate) =>
typeof candidate.payload?.displayPrompt === "string"
? candidate.payload.displayPrompt
: ""
) ?? []
);
const selectedTextBlockIndexes = selectedTextContentBlockIndexes(
content,
displayPrompt
);
const visibleDisplayPrompt = isSyntheticImageOnlyDisplayPrompt(
displayPrompt,
content
)
? ""
: displayPrompt;
// Older sessions kept draft-only `mention://composer-file/...` chips in
// displayPrompt. Prefer the already-materialized provider text so transcript
// clicks resolve through ordinary file locators.
const preferMaterializedContentText =
Boolean(visibleDisplayPrompt) &&
visibleDisplayPrompt.includes("mention://composer-file/") &&
content.some((raw) => {
const block =
raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: null;
return (
block?.type === "text" &&
typeof block.text === "string" &&
block.text.trim().length > 0
);
});
const effectiveDisplayPrompt = preferMaterializedContentText
? ""
: selectedTextBlockIndexes.size > 0
? ""
: visibleDisplayPrompt;
const blocks = content.flatMap(
(raw, contentIndex): UserPromptContentBlock[] => {
const block = promptContentRecord(raw);
if (!block) return [];
if (block.type === "text" && typeof block.text === "string") {
const kind = selectedTextBlockIndexes.has(contentIndex)
? "selected-text"
: typeof block.kind === "string"
? block.kind
: undefined;
return effectiveDisplayPrompt
? []
: [
{
type: "text",
text: linkifyPastedTextReferences(block.text),
...(kind ? { kind } : {})
}
];
}
if (block.type !== "image") return [];
const mimeType =
typeof block.mimeType === "string" ? block.mimeType.trim() : "";
return [
{
type: "image",
workspaceId: item?.workspaceId ?? fallbackWorkspaceId ?? null,
agentSessionId: item?.agentSessionId ?? message.id,
attachmentId: optionalString(block.attachmentId),
mimeType,
name: optionalString(block.name),
data: optionalString(block.data),
url: optionalString(block.url),
path: optionalString(block.path)
}
];
}
);
return effectiveDisplayPrompt
? [{ type: "text", text: effectiveDisplayPrompt }, ...blocks]
: blocks;
}
function selectedTextContentBlockIndexes(
content: readonly unknown[],
displayPrompt: string
): ReadonlySet<number> {
const result = new Set<number>();
const textIndexes: number[] = [];
for (const [index, raw] of content.entries()) {
const block = promptContentRecord(raw);
if (block?.type === "text" && typeof block.text === "string") {
textIndexes.push(index);
}
}
const firstNonQuoteTextOrdinal = textIndexes.findIndex((contentIndex) => {
const block = promptContentRecord(content[contentIndex]);
return (
typeof block?.text === "string" &&
block.text.trim() !== "" &&
!isSelectedTextBlockquote(block.text)
);
});
const normalizedDisplayPrompt = displayPrompt.replace(/\r\n?/gu, "\n");
for (const [textOrdinal, contentIndex] of textIndexes.entries()) {
const block = promptContentRecord(content[contentIndex]);
const text = typeof block?.text === "string" ? block.text : "";
if (block?.kind === "selected-text") {
result.add(contentIndex);
continue;
}
if (
firstNonQuoteTextOrdinal < 0 ||
textOrdinal <= firstNonQuoteTextOrdinal ||
!isSelectedTextBlockquote(text) ||
!normalizedDisplayPrompt.includes(text.replace(/\r\n?/gu, "\n").trim())
) {
continue;
}
// The composer currently puts a non-quote typed prompt first and each
// selected transcript quote after it. Ambiguous quote-only legacy payloads
// stay ordinary Markdown; only an explicit kind can identify those.
result.add(contentIndex);
}
return result;
}
function isSelectedTextBlockquote(text: string): boolean {
const lines = text.trim().split(/\r?\n/u);
return (
lines.length > 0 && lines.every((line) => /^>\s?/u.test(line.trimStart()))
);
}
function stripSelectedTextPrefix(text: string): string {
return text
.split(/\r?\n/u)
.map((line) => line.replace(/^\s*>\s?/u, ""))
.join("\n")
.trim();
}
function promptContentRecord(raw: unknown): Record<string, unknown> | null {
return raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: null;
}
function isSyntheticImageOnlyDisplayPrompt(
displayPrompt: string,
content: readonly unknown[]
): boolean {
if (displayPrompt !== "[Image]" && displayPrompt !== "[Images]") {
return false;
}
let imageCount = 0;
for (const raw of content) {
const block =
raw && typeof raw === "object" && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: null;
if (!block) continue;
if (
block.type === "text" &&
typeof block.text === "string" &&
block.text.trim()
) {
return false;
}
if (block.type === "image") {
imageCount += 1;
}
}
return displayPrompt === "[Image]" ? imageCount === 1 : imageCount > 1;
}
function optionalString(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function firstString(values: readonly string[]): string {
for (const value of values) {
const trimmed = value.trim();
if (trimmed) return trimmed;
}
return "";
}
@@ -0,0 +1,98 @@
import type { AgentActivityInteraction } from "@tutti-os/agent-activity-core";
import type { AgentConversationPromptVM } from "../contracts/agentConversationVM";
import { normalizeAgentApprovalPurpose } from "../agentApprovalPurpose";
import { normalizeAskUserQuestions } from "../askUserQuestions";
import {
extractExitPlanKeepPlanningOptionId,
extractExitPlanModeOptions
} from "../exitPlanOptions";
import { normalizeAgentApprovalOptions } from "./agentApprovalProjection";
type ApprovalPrompt = Extract<AgentConversationPromptVM, { kind: "approval" }>;
type InteractivePrompt = Exclude<
AgentConversationPromptVM,
ApprovalPrompt | { kind: "plan-implementation" }
>;
export function projectAgentConversationPromptFromInteraction(
interaction: AgentActivityInteraction
): ApprovalPrompt | InteractivePrompt | null {
return interaction.kind === "approval"
? projectAgentApprovalPromptFromInteraction(interaction)
: projectAgentInteractivePromptFromInteraction(interaction);
}
export function projectAgentApprovalPromptFromInteraction(
interaction: AgentActivityInteraction | null
): ApprovalPrompt | null {
if (!interaction || interaction.kind !== "approval") return null;
const callId =
typeof interaction.input?.callId === "string" &&
interaction.input.callId.trim()
? interaction.input.callId.trim()
: interaction.requestId.trim();
const options = normalizeAgentApprovalOptions(interaction.input?.options);
if (!callId || options.length === 0) return null;
const approvalPurpose = normalizeAgentApprovalPurpose(
interaction.metadata?.approvalPurpose
);
return {
kind: "approval",
id: `approval:${callId}`,
agentSessionId: interaction.agentSessionId,
turnId: interaction.turnId,
requestId: interaction.requestId,
callId,
...(approvalPurpose ? { approvalPurpose } : {}),
title: interaction.toolName?.trim() || "",
status: "waiting_approval",
toolName: interaction.toolName?.trim() || null,
input: interaction.input ?? null,
options,
output: interaction.output ?? null,
occurredAtUnixMs: interaction.createdAtUnixMs
};
}
export function projectAgentInteractivePromptFromInteraction(
interaction: AgentActivityInteraction | null
): InteractivePrompt | null {
if (!interaction || interaction.kind === "approval") return null;
const toolName = normalizeInteractiveToolName(
interaction.toolName ?? undefined
);
if (interaction.kind === "plan" || toolName === "exitplanmode") {
const keepPlanningOptionId = extractExitPlanKeepPlanningOptionId(
interaction.input
);
return {
kind: "exit-plan",
agentSessionId: interaction.agentSessionId,
turnId: interaction.turnId,
requestId: interaction.requestId,
title: interaction.toolName?.trim() || "",
options: extractExitPlanModeOptions(interaction.input),
...(keepPlanningOptionId ? { keepPlanningOptionId } : {})
};
}
if (interaction.kind !== "question" || toolName !== "askuserquestion") {
return null;
}
const questions = normalizeAskUserQuestions(interaction.input?.questions, {
missingText: ""
});
return questions.length > 0
? {
kind: "ask-user",
agentSessionId: interaction.agentSessionId,
turnId: interaction.turnId,
requestId: interaction.requestId,
title: interaction.toolName?.trim() || "",
questions
}
: null;
}
function normalizeInteractiveToolName(toolName: string | undefined): string {
return (toolName?.trim() ?? "").replace(/[_\s-]+/g, "").toLowerCase();
}
@@ -0,0 +1,160 @@
import type { WorkspaceAgentSessionDetailToolCall } from "../../workspaceAgentSessionDetailViewModel";
import type { AgentAskUserQuestionItemVM } from "../contracts/agentAskUserQuestionItemVM";
import type { AgentPlanModeItemVM } from "../contracts/agentPlanModeItemVM";
import { normalizeAskUserQuestions } from "../askUserQuestions";
import {
extractExitPlanKeepPlanningOptionId,
extractExitPlanModeOptions,
isExitPlanSwitchModeInput
} from "../exitPlanOptions";
export function projectAgentAskUserQuestionItem(
call: WorkspaceAgentSessionDetailToolCall,
input: Record<string, unknown> | null,
output: Record<string, unknown> | null
): AgentAskUserQuestionItemVM | null {
if (normalizeToolName(call.toolName) !== "askuserquestion") {
return null;
}
const questions = normalizeAskUserQuestions(input?.questions);
if (questions.length === 0) {
return null;
}
const answersByQuestionId = objectValue(output?.answersByQuestionId) ?? {};
return {
kind: "ask-user",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
requestId:
stringValue(input?.requestId) ??
stringValue(call.payload?.requestId) ??
call.id.replace(/^call:/, ""),
title: call.name,
status: call.status,
questions: questions.map((question) => ({
...question,
answer: answerForQuestion(question.id, answersByQuestionId, output)
})),
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
export function projectAgentPlanModeItem(
call: WorkspaceAgentSessionDetailToolCall,
input: Record<string, unknown> | null
): AgentPlanModeItemVM | null {
if (isExitPlanSwitchModeInput(input)) {
return {
itemKind: "plan-mode",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
requestId:
stringValue(input?.requestId) ??
stringValue(call.payload?.requestId) ??
call.id.replace(/^call:/, ""),
kind: "exit",
title: stringValue(objectValue(input?.toolCall)?.title) ?? call.name,
status: call.status,
plan:
stringValue(input?.plan) ??
stringValue(call.payload?.plan) ??
(call.summary.trim() || null),
filePath:
stringValue(input?.filePath) ?? stringValue(call.payload?.filePath),
options: extractExitPlanModeOptions(input),
...keepPlanningOption(extractExitPlanKeepPlanningOptionId(input)),
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
const toolName = normalizeToolName(call.toolName);
if (toolName === "enterplanmode") {
return {
itemKind: "plan-mode",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
kind: "enter",
title: call.name,
status: call.status,
plan: stringValue(input?.content) ?? (call.summary.trim() || null),
filePath: stringValue(input?.filePath),
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
if (toolName !== "exitplanmode") {
return null;
}
return {
itemKind: "plan-mode",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
requestId:
stringValue(input?.requestId) ??
stringValue(call.payload?.requestId) ??
call.id.replace(/^call:/, ""),
kind: "exit",
title: call.name,
status: call.status,
plan:
stringValue(input?.plan) ??
stringValue(call.payload?.plan) ??
(call.summary.trim() || null),
filePath:
stringValue(input?.filePath) ?? stringValue(call.payload?.filePath),
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
function answerForQuestion(
questionId: string,
answersByQuestionId: Record<string, unknown>,
output: Record<string, unknown> | null
): string | string[] | null {
const responsePayload = objectValue(output?.payload);
const responseAnswersByQuestionId =
objectValue(responsePayload?.answersByQuestionId) ?? {};
const value =
answersByQuestionId[questionId] ?? responseAnswersByQuestionId[questionId];
if (Array.isArray(value)) {
return value.flatMap((item) =>
typeof item === "string" && item.trim() ? [item.trim()] : []
);
}
if (typeof value === "string" && value.trim()) {
return value.trim();
}
const answers =
arrayValue(output?.answers) ?? arrayValue(responsePayload?.answers);
return answers && answers.length > 0
? answers.filter(
(item): item is string =>
typeof item === "string" && item.trim().length > 0
)
: null;
}
function keepPlanningOption(optionId: string | null): {
keepPlanningOptionId?: string;
} {
return optionId ? { keepPlanningOptionId: optionId } : {};
}
function normalizeToolName(value: string | null | undefined): string {
return (value ?? "")
.replace(/[_\s-]+/g, "")
.trim()
.toLowerCase();
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function objectValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function arrayValue(value: unknown): unknown[] | null {
return Array.isArray(value) ? value : null;
}
@@ -0,0 +1,165 @@
import type { WorkspaceAgentSessionDetailViewModel } from "../../workspaceAgentSessionDetailViewModel";
import type {
AgentMessageContentVM,
AgentMessageRowVM
} from "../contracts/agentMessageRowVM";
import type { AgentTranscriptRowVM } from "../contracts/agentTranscriptRowVM";
export function projectAgentMessageFinalText(
rows: readonly AgentTranscriptRowVM[],
detail: WorkspaceAgentSessionDetailViewModel
): AgentTranscriptRowVM[] {
const finalTextTargetKeys = findLatestAssistantFinalTextTargetKeys(
rows,
buildAssistantFinalTextEligibleTurnIds(detail)
);
return rows.map((row) => {
if (row.kind !== "message") {
return row;
}
let changed = false;
const messages = row.messages.map((message) => {
const isTurnFinalText =
row.speaker === "assistant" &&
finalTextTargetKeys.has(messagePresentationTargetKey(row, message));
const copyText =
row.speaker === "user"
? copyTextForUserMessage(message)
: isTurnFinalText
? message.body
: null;
if (
(message.copyText ?? null) === copyText &&
message.isTurnFinalText === (isTurnFinalText ? true : undefined)
) {
return message;
}
changed = true;
const nextMessage = isTurnFinalText
? { ...message, isTurnFinalText: true as const }
: omitTurnFinalText(message);
if (copyText) {
return { ...nextMessage, copyText };
}
const { copyText: _copyText, ...withoutCopyText } = nextMessage;
return withoutCopyText;
});
return changed ? { ...row, messages } : row;
});
}
function omitTurnFinalText(
message: AgentMessageContentVM
): AgentMessageContentVM {
const { isTurnFinalText: _isTurnFinalText, ...withoutTurnFinalText } =
message;
return withoutTurnFinalText;
}
function buildAssistantFinalTextEligibleTurnIds(
detail: WorkspaceAgentSessionDetailViewModel
): ReadonlySet<string> {
const ids = new Set<string>();
detail.turns.forEach((turn, index) => {
if (
index < detail.turns.length - 1 ||
isLatestTranscriptTurnSettled(detail)
) {
ids.add(turn.id);
}
});
return ids;
}
function isLatestTranscriptTurnSettled(
detail: WorkspaceAgentSessionDetailViewModel
): boolean {
const latestTranscriptTurnId = detail.turns.at(-1)?.id;
const canonicalTurn = detail.sessionTurns?.find(
(turn) => turn.turnId === latestTranscriptTurnId
);
const activeTurn = detail.session.activeTurn;
if (
activeTurn &&
activeTurn.turnId === latestTranscriptTurnId &&
activeTurn.phase !== "settled"
) {
return false;
}
if (canonicalTurn) {
return (
canonicalTurn.phase === "settled" &&
detail.showProcessingIndicator !== true
);
}
const activePhase = activeTurn?.phase ?? "";
return (
detail.showProcessingIndicator !== true &&
!["submitted", "running", "waiting", "settling"].includes(activePhase)
);
}
function findLatestAssistantFinalTextTargetKeys(
rows: readonly AgentTranscriptRowVM[],
eligibleTurnIds: ReadonlySet<string>
): ReadonlySet<string> {
const targetKeys = new Set<string>();
const coveredTurnIds = new Set<string>();
for (let rowIndex = rows.length - 1; rowIndex >= 0; rowIndex -= 1) {
const row = rows[rowIndex];
if (
row?.kind !== "message" ||
row.speaker !== "assistant" ||
coveredTurnIds.has(row.turnId) ||
!eligibleTurnIds.has(row.turnId)
) {
continue;
}
for (
let messageIndex = row.messages.length - 1;
messageIndex >= 0;
messageIndex -= 1
) {
const message = row.messages[messageIndex];
if (message && isSettledAssistantFinalTextCandidate(message)) {
targetKeys.add(messagePresentationTargetKey(row, message));
coveredTurnIds.add(row.turnId);
break;
}
}
}
return targetKeys;
}
function messagePresentationTargetKey(
row: AgentMessageRowVM,
message: AgentMessageContentVM
): string {
return `${row.id}\u0000${message.id}`;
}
function copyTextForUserMessage(message: AgentMessageContentVM): string | null {
return isVisibleTextMessage(message) ? message.body : null;
}
function isSettledAssistantFinalTextCandidate(
message: AgentMessageContentVM
): boolean {
return (
isVisibleTextMessage(message) &&
message.statusKind !== "working" &&
message.statusKind !== "waiting"
);
}
function isVisibleTextMessage(message: AgentMessageContentVM): boolean {
return (
message.body.trim() !== "" &&
message.contentKind !== "image-grid" &&
message.contentKind !== "collaboration" &&
!message.visibleError &&
!message.systemNotice
);
}
@@ -0,0 +1,71 @@
import type { WorkspaceAgentSessionDetailViewModel } from "../../workspaceAgentSessionDetailViewModel";
import type { AgentProcessingRowVM } from "../contracts/agentProcessingRowVM";
import type { AgentTranscriptRowVM } from "../contracts/agentTranscriptRowVM";
import { agentTranscriptRowHasPresentationKind } from "./agentTranscriptPresentation";
export function projectAgentProcessingRow(
detail: WorkspaceAgentSessionDetailViewModel,
rows: readonly AgentTranscriptRowVM[]
): AgentProcessingRowVM | null {
if (!detail.showProcessingIndicator) {
return null;
}
const activeTurnId = detail.session.activeTurnId;
const canonicalTurn = detail.sessionTurns?.find(
(turn) => turn.turnId === activeTurnId
);
if (
canonicalTurn &&
canonicalTurn.phase !== "settled" &&
Number.isFinite(canonicalTurn.startedAtUnixMs)
) {
if (activeTurnId && hasTurnTimingHostRow(rows, activeTurnId)) {
return null;
}
return processingRow(detail, activeTurnId);
}
const fallbackTurnId = activeTurnId ?? detail.turns.at(-1)?.id ?? null;
if (fallbackTurnId && hasSpecificProgressRow(rows, fallbackTurnId)) {
return null;
}
return processingRow(detail, fallbackTurnId);
}
function processingRow(
detail: WorkspaceAgentSessionDetailViewModel,
turnId: string | null
): AgentProcessingRowVM {
return {
kind: "processing",
id: `processing:${turnId ?? "session"}`,
turnId,
occurredAtUnixMs:
detail.session.updatedAtUnixMs ?? detail.session.createdAtUnixMs ?? null
};
}
function hasTurnTimingHostRow(
rows: readonly AgentTranscriptRowVM[],
activeTurnId: string
): boolean {
return rows.some((row) => row.turnId === activeTurnId);
}
function hasSpecificProgressRow(
rows: readonly AgentTranscriptRowVM[],
activeTurnId: string
): boolean {
return rows.some((row) => {
if (row.turnId !== activeTurnId) {
return false;
}
return (
agentTranscriptRowHasPresentationKind(row, "specific-progress") ||
(row.kind === "tool-group" &&
row.calls.some(
(call) =>
call.statusKind === "working" || call.statusKind === "waiting"
))
);
});
}
@@ -0,0 +1,127 @@
import type { AgentSessionEvent } from "../../agentSessionTypes";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import type { BuildWorkspaceAgentSessionDetailInput } from "../../workspaceAgentSessionDetailViewModel";
import { projectWorkspaceAgentTimelineToConversationVM } from "./workspaceAgentTimelineProjection";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
export function projectAgentSessionEventsToTimelineItems(
events: readonly AgentSessionEvent[]
): WorkspaceAgentActivityTimelineItem[] {
return mergeSessionEvents(events).map((event, index) =>
sessionEventToTimelineItem(event, index + 1)
);
}
export function projectAgentSessionEventsToConversationVM(
input: Omit<BuildWorkspaceAgentSessionDetailInput, "timelineItems"> & {
events: readonly AgentSessionEvent[];
}
): AgentConversationVM {
return projectWorkspaceAgentTimelineToConversationVM({
...input,
timelineItems: projectAgentSessionEventsToTimelineItems(input.events)
});
}
function mergeSessionEvents(
events: readonly AgentSessionEvent[]
): AgentSessionEvent[] {
const byKey = new Map<string, AgentSessionEvent>();
for (const event of [...events].sort(compareSessionEvents)) {
byKey.set(sessionEventMergeKey(event), event);
}
return [...byKey.values()].sort(compareSessionEvents);
}
function sessionEventMergeKey(event: AgentSessionEvent): string {
const callId = stringPayload(event.payload?.callId);
if (callId) {
return `call:${event.turnId?.trim() ?? ""}:${callId}`;
}
if (event.type === "message") {
return `message:${event.id}`;
}
return `event:${event.id}`;
}
function sessionEventToTimelineItem(
event: AgentSessionEvent,
seq: number
): WorkspaceAgentActivityTimelineItem {
const callId = stringPayload(event.payload?.callId);
const callType = stringPayload(event.payload?.callType);
const name = stringPayload(event.payload?.name);
const workspaceId = workspaceIdFromSessionEvent(event);
return {
id: hashStringToPositiveInt(event.id),
...workspaceTimelineFields(workspaceId),
agentSessionId: event.agentSessionId,
turnId: event.turnId,
seq,
eventId: event.id,
actorType: event.role === "user" ? "user" : "agent",
actorId: event.provider,
itemType: timelineItemTypeFromSessionEvent(event),
role: event.role,
callId: callId || undefined,
callType: callType || undefined,
name: name || undefined,
status: event.status,
content: event.content,
payload: {
...event.payload,
content: event.content ?? event.payload?.content,
text: event.payload?.text
},
occurredAtUnixMs: event.occurredAtUnixMs,
createdAtUnixMs: event.occurredAtUnixMs
};
}
function workspaceIdFromSessionEvent(event: AgentSessionEvent): string {
return event.workspaceId.trim();
}
function workspaceTimelineFields(
workspaceId: string
): Pick<WorkspaceAgentActivityTimelineItem, "workspaceId"> {
return {
workspaceId
};
}
function timelineItemTypeFromSessionEvent(event: AgentSessionEvent): string {
if (event.type === "message") {
return event.role === "user" ? "message.user" : "message.assistant";
}
if (
event.type === "call.started" ||
event.type === "call.completed" ||
event.type === "call.failed"
) {
return "call";
}
return "event";
}
function compareSessionEvents(
left: AgentSessionEvent,
right: AgentSessionEvent
): number {
return (
(left.occurredAtUnixMs ?? 0) - (right.occurredAtUnixMs ?? 0) ||
left.id.localeCompare(right.id)
);
}
function hashStringToPositiveInt(value: string): number {
let hash = 0;
for (let index = 0; index < value.length; index += 1) {
hash = (hash * 31 + value.charCodeAt(index)) | 0;
}
return Math.abs(hash) || 1;
}
function stringPayload(value: unknown): string {
return typeof value === "string" ? value.trim() : "";
}
@@ -0,0 +1,323 @@
import type { WorkspaceAgentSessionDetailToolCall } from "../../workspaceAgentSessionDetailViewModel";
import type {
AgentTaskItemVM,
AgentTaskStepVM
} from "../contracts/agentTaskItemVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import { projectAgentApprovalItem } from "./agentApprovalProjection";
import {
projectAgentAskUserQuestionItem,
projectAgentPlanModeItem
} from "./agentInteractiveProjection";
import {
inferToolCallType,
isApprovalToolCall,
normalizeToolName,
resolveAgentToolRendererKind
} from "./agentToolRendererKind";
export function projectAgentTaskItem(
call: WorkspaceAgentSessionDetailToolCall,
input: Record<string, unknown> | null,
output: Record<string, unknown> | null,
metadata: Record<string, unknown> | null
): AgentTaskItemVM | null {
const toolName = normalizeToolName(call.toolName);
if (
!["task", "subagent", "delegatetask", "delegateagent", "agent"].includes(
toolName
)
) {
return null;
}
const steps = normalizeTaskSteps(
arrayValue(metadata?.steps) ??
arrayValue(output?.steps) ??
arrayValue(call.payload?.steps) ??
[],
call.turnId ?? "turn:unknown"
);
return {
kind: "task",
id: call.id,
turnId: call.turnId ?? "turn:unknown",
title: call.summary.trim() || call.name,
status:
stringValue(metadata?.taskStatus) ??
stringValue(metadata?.subagentStatus) ??
call.status,
prompt:
stringValue(input?.prompt) ??
stringValue(input?.description) ??
stringValue(call.payload?.description),
delegateSessionId:
stringValue(metadata?.childSessionID) ??
stringValue(metadata?.child_session_id) ??
stringValue(metadata?.subagentSessionID) ??
stringValue(metadata?.subagent_session_id) ??
stringValue(metadata?.subagentAgentId) ??
stringValue(metadata?.agentId),
steps,
result: firstNonEmptyText(output),
resultMarkdown: firstNonEmptyText(output),
durationMs:
numberValue(metadata?.durationMs) ?? numberValue(output?.durationMs),
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
}
function normalizeTaskSteps(
values: readonly unknown[],
turnId: string
): AgentTaskStepVM[] {
return values.flatMap((value, index) => {
const step = objectValue(value);
if (!step) {
return [];
}
const toolName =
stringValue(step.toolName) ??
stringValue(step.tool_name) ??
stringValue(step.name);
const callType = stringValue(step.callType) ?? stringValue(step.call_type);
if (isApprovalToolCall({ toolName, callType })) {
return [];
}
const inputPayload =
objectValue(step.toolInput) ?? objectValue(step.tool_input);
const outputPayload =
objectValue(step.toolResult) ?? objectValue(step.tool_result);
const errorPayload =
objectValue(step.toolError) ?? objectValue(step.tool_error);
const metadata = objectValue(step.metadata);
const locations = arrayValue(step.locations);
return [
{
id:
stringValue(step.toolUseId) ??
stringValue(step.id) ??
`step-${index + 1}`,
turnId,
name: toolName ? humanizeToolLabel(toolName) : `Step ${index + 1}`,
toolName: toolName ?? null,
status:
stringValue(step.status) ??
stringValue(objectValue(step.toolResult)?.status) ??
stringValue(objectValue(step.tool_result)?.status),
summary: firstNonEmptyText(outputPayload, inputPayload) ?? "",
payload: {
input: inputPayload,
output: outputPayload,
error: errorPayload
},
tool: projectAgentTaskStepTool({
id:
stringValue(step.toolUseId) ??
stringValue(step.id) ??
`step-${index + 1}`,
turnId,
toolName,
name: stringValue(step.name),
callType,
status:
stringValue(step.status) ?? stringValue(outputPayload?.status),
summary: firstNonEmptyText(outputPayload, inputPayload) ?? "",
payload: {
input: inputPayload,
output: outputPayload,
error: errorPayload,
metadata,
...(step.fileChanges !== undefined
? { fileChanges: step.fileChanges }
: {})
},
metadata,
input: inputPayload,
output: outputPayload,
error: errorPayload,
locations,
occurredAtUnixMs: numberValue(step.occurredAtUnixMs)
}),
occurredAtUnixMs: numberValue(step.occurredAtUnixMs) ?? null
}
];
});
}
export function projectAgentTaskStepTool(step: {
id: string;
turnId: string;
toolName: string | null;
name: string | null;
callType: string | null;
status: string | null;
summary: string;
payload: Record<string, unknown> | null;
metadata: Record<string, unknown> | null;
input: Record<string, unknown> | null;
output: Record<string, unknown> | null;
error: Record<string, unknown> | null;
locations: unknown[] | null;
occurredAtUnixMs: number | null;
}): AgentToolCallVM {
const call: WorkspaceAgentSessionDetailToolCall = {
id: `call:${step.id}`,
turnId: step.turnId,
name:
step.name ?? (step.toolName ? humanizeToolLabel(step.toolName) : "Tool"),
toolName: step.toolName,
callType: step.callType ?? inferToolCallType(step.toolName),
status: step.status,
statusKind: normalizeTaskStepStatus(step.status),
summary: step.summary,
compactSummary: step.summary || null,
payload: step.payload,
occurredAtUnixMs: step.occurredAtUnixMs
};
const approval = projectAgentApprovalItem(call, step.input, step.output);
const askUserQuestion = projectAgentAskUserQuestionItem(
call,
step.input,
step.output
);
const planMode = projectAgentPlanModeItem(call, step.input);
const task = projectAgentTaskItem(
call,
step.input,
step.output,
step.metadata
);
const rendererKind = resolveAgentToolRendererKind(
{
toolName: call.toolName,
displayName: call.name,
callType: call.callType,
input: step.input,
output: step.output,
metadata: step.metadata
},
approval,
askUserQuestion,
planMode,
task
);
return {
kind: "tool-call",
...call,
turnId: step.turnId,
compactSummary: call.compactSummary ?? null,
payload: step.payload,
input: step.input,
output: step.output,
error: step.error,
metadata: step.metadata,
locations: step.locations,
occurredAtUnixMs: call.occurredAtUnixMs ?? null,
rendererKind,
approval,
planMode,
askUserQuestion,
task
};
}
function humanizeToolLabel(value: string): string {
return value
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
.replace(/[_-]+/g, " ")
.replace(/\s+/g, " ")
.trim()
.replace(/^\w/, (match) => match.toUpperCase());
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function numberValue(value: unknown): number | null {
return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function normalizeTaskStepStatus(
value: string | null
): AgentToolCallVM["statusKind"] {
switch ((value ?? "").trim().toLowerCase()) {
case "completed":
case "done":
case "success":
case "succeeded":
return "completed";
case "failed":
case "error":
case "errored":
return "failed";
case "waiting":
case "waiting_input":
case "waiting_approval":
return "waiting";
case "running":
case "working":
case "active":
return "working";
default:
return null;
}
}
function objectValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function arrayValue(value: unknown): unknown[] | null {
return Array.isArray(value) ? value : null;
}
function firstNonEmptyText(
...values: Array<Record<string, unknown> | string | null | undefined>
): string | null {
for (const value of values) {
const text = extractText(value);
if (text) {
return text;
}
}
return null;
}
function extractText(value: unknown, depth = 0): string | null {
if (depth > 4) {
return null;
}
if (typeof value === "string" && value.trim()) {
return value.trim();
}
if (Array.isArray(value)) {
for (const item of value) {
const text = extractText(item, depth + 1);
if (text) {
return text;
}
}
return null;
}
if (value && typeof value === "object") {
const record = value as Record<string, unknown>;
for (const key of [
"text",
"output",
"summary",
"message",
"patch",
"result"
]) {
const text = extractText(record[key], depth + 1);
if (text) {
return text;
}
}
return null;
}
return null;
}
@@ -0,0 +1,208 @@
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import type {
AgentToolGroupEntryVM,
AgentToolGroupRowVM
} from "../contracts/agentToolGroupRowVM";
import type { AgentTurnSequenceItemVM } from "./agentTurnSequenceProjection";
const AVOID_GROUPING_EDITS = false;
export interface AgentComputedToolGroupVM {
startIndex: number;
endIndex: number;
calls: AgentToolCallVM[];
entries: AgentToolGroupEntryVM[];
}
export interface AgentComputedToolGroupInfoVM {
groups: Map<number, AgentComputedToolGroupVM>;
groupedIndices: Set<number>;
suppressedIndices: Set<number>;
}
export function computeAgentToolGroups(
sequence: readonly AgentTurnSequenceItemVM[],
{
avoidGroupingEdits = AVOID_GROUPING_EDITS
}: {
avoidGroupingEdits?: boolean;
}
): AgentComputedToolGroupInfoVM {
const groups = new Map<number, AgentComputedToolGroupVM>();
const groupedIndices = new Set<number>();
const suppressedIndices = new Set<number>();
let currentCalls: AgentToolCallVM[] = [];
let currentEntries: AgentToolGroupEntryVM[] = [];
let currentIndices: number[] = [];
let pendingBridgeEntries: AgentToolGroupEntryVM[] = [];
let pendingBridgeIndices: number[] = [];
let startIndex = -1;
const finalizeGroup = () => {
if (
currentCalls.length >= 1 &&
startIndex >= 0 &&
currentIndices.length > 0
) {
const endIndex = currentIndices[currentIndices.length - 1] ?? startIndex;
groups.set(startIndex, {
startIndex,
endIndex,
calls: [...currentCalls],
entries: [...currentEntries]
});
currentIndices.forEach((index) => groupedIndices.add(index));
}
currentCalls = [];
currentEntries = [];
currentIndices = [];
pendingBridgeEntries = [];
pendingBridgeIndices = [];
startIndex = -1;
};
for (let index = 0; index < sequence.length; index += 1) {
const item = sequence[index];
if (!item) {
continue;
}
if (item.kind === "tool-call" && isGroupableToolCall(item.call)) {
if (avoidGroupingEdits && isEditBoundaryToolCall(item.call)) {
finalizeGroup();
continue;
}
if (startIndex < 0) {
startIndex = index;
}
if (pendingBridgeEntries.length > 0) {
currentEntries.push(...pendingBridgeEntries);
currentIndices.push(...pendingBridgeIndices);
pendingBridgeEntries = [];
pendingBridgeIndices = [];
}
currentCalls.push(item.call);
currentEntries.push({ kind: "tool-call", call: item.call });
currentIndices.push(index);
continue;
}
if (
item.kind === "thinking" &&
startIndex >= 0 &&
currentCalls.length > 0
) {
pendingBridgeEntries.push({ kind: "thinking", thinking: item.thinking });
pendingBridgeIndices.push(index);
continue;
}
finalizeGroup();
}
finalizeGroup();
return {
groups,
groupedIndices,
suppressedIndices
};
}
export function projectAgentToolGroupRowFromGroup(
turnId: string,
group: AgentComputedToolGroupVM,
agentSessionId?: string
): AgentToolGroupRowVM {
const firstCallId = group.calls[0]?.id ?? "unknown";
return {
kind: "tool-group",
id: `tool-group:${turnId}:${group.calls.map((call) => call.id).join("+")}`,
expansionKey: ["tool-group", agentSessionId, turnId, firstCallId]
.filter(Boolean)
.join(":"),
turnId,
grouped: true,
calls: group.calls,
summary: summarizeToolCallGroup(group.calls),
entries: group.entries,
occurredAtUnixMs:
group.calls
.map((call) => call.occurredAtUnixMs ?? 0)
.reduce((latest, value) => (value > latest ? value : latest), 0) || null
};
}
export function projectAgentSingleToolRow(
call: AgentToolCallVM,
turnId = call.turnId
): AgentToolGroupRowVM {
return {
kind: "tool-group",
id: `tool-row:${call.id}`,
expansionKey: `tool-group:${turnId}:${call.id}`,
turnId,
grouped: false,
calls: [call],
summary: null,
entries: [{ kind: "tool-call", call }],
occurredAtUnixMs: call.occurredAtUnixMs
};
}
function isGroupableToolCall(call: AgentToolCallVM): boolean {
switch (call.rendererKind) {
case "approval":
case "ask-user":
case "plan-enter":
case "plan-exit":
case "task":
return false;
default:
return true;
}
}
function isEditBoundaryToolCall(call: AgentToolCallVM): boolean {
return call.rendererKind === "edit" || call.rendererKind === "write";
}
function summarizeToolCallGroup(
calls: readonly AgentToolCallVM[]
): string | null {
if (calls.length < 2) {
return null;
}
const changedTargets = dedupeStrings(
calls
.filter(
(call) => call.rendererKind === "edit" || call.rendererKind === "write"
)
.map((call) => summarizeCallTarget(call.compactSummary ?? call.summary))
.filter((value): value is string => value !== null)
);
if (changedTargets.length === 0) {
return null;
}
if (changedTargets.length === 1) {
return `Changed ${changedTargets[0]}`;
}
return `Changed ${changedTargets[0]} and ${changedTargets.length - 1} more files`;
}
function summarizeCallTarget(summary: string): string | null {
const normalized = summary.trim();
if (!normalized) {
return null;
}
const firstLine = normalized.split("\n")[0]?.trim() ?? normalized;
if (!firstLine) {
return null;
}
const segments = firstLine.split(/[\\/]/).filter(Boolean);
return segments.at(-1) ?? firstLine;
}
function dedupeStrings(values: readonly string[]): string[] {
return [...new Set(values.map((value) => value.trim()).filter(Boolean))];
}
@@ -0,0 +1,411 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceAgentSessionDetailToolCall } from "../../workspaceAgentSessionDetailViewModel";
import { projectAgentToolCall } from "./agentToolProjection";
describe("projectAgentToolCall", () => {
it.each([
["Bash", "tool", "bash"],
["Read", "tool", "read"],
["Write", "tool", "write"],
["Edit", "tool", "edit"],
["Grep", "tool", "search"],
["Glob", "tool", "search"],
["WebSearch", "tool", "web-search"],
["WebFetch", "tool", "web-fetch"],
["ImageGeneration", "tool", "image-generation"],
["TodoWrite", "tool", "todo-write"],
["Task", "tool", "task"]
] satisfies Array<[string, string, string]>)(
"maps canonical tool name %s/%s to %s",
(toolName, callType, rendererKind) => {
expect(
projectAgentToolCall({
...baseCall(),
toolName,
callType
}).rendererKind
).toBe(rendererKind);
}
);
it.each([
["read_file", "tool", "read"],
["write_file", "tool", "write"],
["edit_file", "tool", "edit"],
["bash", "tool", "bash"],
["grep", "tool", "search"],
["websearch", "tool", "web-search"],
["webfetch", "tool", "web-fetch"],
["todowrite", "tool", "todo-write"],
["toolsearch", "tool", "tool-search"],
["skill", "tool", "skill"],
["closeAgent", "tool", "default"],
["wait", "tool", "default"],
["custom_mcp_tool", "mcp", "mcp"],
["Approval", "approval", "approval"],
["EnterPlanMode", "interactive", "plan-enter"],
["ExitPlanMode", "interactive", "plan-exit"],
["AskUserQuestion", "interactive", "ask-user"],
["Task", "tool", "task"],
["Agent", "tool", "task"],
["delegate_agent", "tool", "task"]
] satisfies Array<[string, string, string]>)(
"maps %s/%s to %s",
(toolName, callType, rendererKind) => {
expect(
projectAgentToolCall({
...baseCall(),
toolName,
callType
}).rendererKind
).toBe(rendererKind);
}
);
it("projects approval, ask-user, plan, and task structured payloads", () => {
const approval = projectAgentToolCall({
...baseCall(),
toolName: "Approval",
callType: "approval",
payload: {
input: {
requestId: "approval-1",
options: [{ optionId: "yes", label: "Allow", description: "Proceed" }]
}
}
});
expect(approval.approval?.requestId).toBe("approval-1");
const switchModeApproval = projectAgentToolCall({
...baseCall(),
toolName: "Approval",
callType: "approval",
status: "waiting_approval",
payload: {
input: {
requestId: "0",
toolCall: {
kind: "switch_mode",
title: "Ready to code?",
toolCallId: "call-1"
},
options: [
{ optionId: "default", name: "Yes, and manually approve edits" },
{ optionId: "plan", name: "No, keep planning" }
]
}
}
});
expect(switchModeApproval.approval).toBeNull();
expect(switchModeApproval.planMode).toEqual(
expect.objectContaining({
kind: "exit",
requestId: "0",
title: "Ready to code?"
})
);
expect(switchModeApproval.rendererKind).toBe("plan-exit");
const askUser = projectAgentToolCall({
...baseCall(),
toolName: "AskUserQuestion",
callType: "interactive",
payload: {
input: {
requestId: "prompt-1",
questions: [
{
id: "q1",
header: "Choice",
question: "Pick one",
options: [{ label: "A", description: "Option A" }]
}
]
}
}
});
expect(askUser.askUserQuestion?.questions[0]?.question).toBe("Pick one");
const answeredAskUser = projectAgentToolCall({
...baseCall(),
toolName: "AskUserQuestion",
callType: "interactive",
status: "completed",
payload: {
input: {
requestId: "prompt-2",
questions: [
{
header: "Test scope",
question: "Which modules should we test?",
options: [{ label: "Code editing", description: "Edit code" }]
}
]
},
output: {
action: "submit",
payload: {
answers: ["Code editing"],
answersByQuestionId: {
"question-1": ["Code editing"]
}
},
requestId: "prompt-2",
text: "Your questions have been answered."
}
}
});
expect(answeredAskUser.askUserQuestion?.questions[0]?.answer).toEqual([
"Code editing"
]);
const task = projectAgentToolCall({
...baseCall(),
toolName: "Task",
callType: "tool",
payload: {
input: {
prompt: "Fix the build"
},
output: {
steps: [
{
id: "step-1",
toolName: "Read",
status: "completed",
toolResult: { text: "done" }
}
]
},
metadata: {
childSessionID: "child-1"
}
}
});
expect(task.task?.delegateSessionId).toBe("child-1");
expect(task.task?.steps).toHaveLength(1);
});
it("uses canonical input and output for specialized tool renderers", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "Edit",
callType: "tool",
payload: {
input: {
kind: "edit",
title: "apply_patch",
patchText: "*** Begin Patch"
},
output: {
diff: "Index: /workspace/index.html\n--- /workspace/index.html\n+++ /workspace/index.html",
files: [
{
filePath: "/workspace/index.html",
patch: "Index: /workspace/index.html"
}
]
}
}
});
expect(projected.rendererKind).toBe("edit");
expect(projected.input?.patchText).toBe("*** Begin Patch");
expect(projected.output?.diff).toContain("/workspace/index.html");
expect(projected.output?.files).toEqual([
expect.objectContaining({ filePath: "/workspace/index.html" })
]);
});
it("prefers canonical payload input/output over tool_state when both exist", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "Bash",
payload: {
input: { command: "pwd" },
output: { stdout: "/workspace\n" },
tool_state: {
input: { command: "legacy pwd" },
output: { stdout: "legacy output\n" }
}
}
});
expect(projected.input?.command).toBe("pwd");
expect(projected.output?.stdout).toBe("/workspace\n");
});
it("uses explicit MCP target fields for approval-wrapped tool names", () => {
const projected = projectAgentToolCall({
...baseCall(),
name: "Approval",
toolName: "Approval",
callType: "tool",
payload: {
input: {
requestId: "request-1",
server: "playwright",
tool: "browser_close",
options: [{ optionId: "approved", name: "Allow" }]
}
}
});
expect(projected.name).toBe("playwright / browser_close");
expect(projected.approval?.title).toBe("playwright / browser_close");
});
it("projects canonical locations into the tool vm", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "Read",
payload: {
locations: [{ path: "/workspace/src/app.ts", line: 4 }]
}
});
expect(projected.locations).toEqual([
{ path: "/workspace/src/app.ts", line: 4 }
]);
});
it("detects opaque image generation aliases from canonical output fields", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "ig_05eb62dbe723c910016a1336ad3de881919216a6f64051a5e2",
name: "ig_05eb62dbe723c910016a1336ad3de881919216a6f64051a5e2",
payload: {
input: { prompt: "a joyful little girl dancing" },
output: {
savedPath: "/workspace/output/generated.png",
imageMimeType: "image/png"
}
}
});
expect(projected.rendererKind).toBe("image-generation");
});
it("projects canonical text for task results and step summaries", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "Task",
callType: "tool",
payload: {
output: {
text: "Task finished successfully",
steps: [
{
id: "step-1",
toolName: "Read",
status: "completed",
toolResult: { text: "Loaded docs chunk" }
}
]
}
}
});
expect(projected.task?.resultMarkdown).toBe("Task finished successfully");
expect(projected.task?.steps[0]?.summary).toBe("Loaded docs chunk");
});
it("does not project task summary or prompt as output when result payload is missing", () => {
const prompt =
"Generate one random integer from 1 to 10 inclusive. Use your own randomness.";
const projected = projectAgentToolCall({
...baseCall(),
name: "Agent",
toolName: "Agent",
callType: "tool",
status: "failed",
statusKind: "failed",
summary: prompt,
payload: {
input: {
prompt,
task: prompt
}
}
});
expect(projected.task?.prompt).toBe(prompt);
expect(projected.task?.resultMarkdown).toBeNull();
});
it("projects canonical subagent prompt, duration, result, and steps", () => {
const projected = projectAgentToolCall({
...baseCall(),
name: "Task: Search today top news",
toolName: "Agent",
callType: "tool",
payload: {
input: {
prompt: "Search for today's top news (2026年5月24日)."
},
output: {
text: "Here is a summary of today's top news (2026年5月24日):"
},
metadata: {
agentId: "child-agent-1",
durationMs: 42_400,
steps: [
{
id: "step-1",
toolName: "WebSearch",
status: "completed",
toolResult: {
text: "Searched web"
}
}
]
}
}
});
expect(projected.task?.prompt).toBe(
"Search for today's top news (2026年5月24日)."
);
expect(projected.task?.delegateSessionId).toBe("child-agent-1");
expect(projected.task?.durationMs).toBe(42_400);
expect(projected.task?.resultMarkdown).toBe(
"Here is a summary of today's top news (2026年5月24日):"
);
expect(projected.task?.steps).toHaveLength(1);
expect(projected.task?.steps[0]?.summary).toBe("Searched web");
});
it("projects async subagent agent id from metadata", () => {
const projected = projectAgentToolCall({
...baseCall(),
toolName: "Agent",
callType: "subagent",
payload: {
input: {
prompt: "Inspect workspace"
},
metadata: {
subagentAsync: true,
taskStatus: "running",
subagentAgentId: "a33f4e9013dedffe8"
}
}
});
expect(projected.task?.delegateSessionId).toBe("a33f4e9013dedffe8");
expect(projected.task?.status).toBe("running");
});
});
function baseCall(): WorkspaceAgentSessionDetailToolCall {
return {
id: "call:1",
name: "Tool",
toolName: null,
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "",
payload: null
};
}
@@ -0,0 +1,78 @@
import type { WorkspaceAgentSessionDetailToolCall } from "../../workspaceAgentSessionDetailViewModel";
import { extractAgentMcpToolTarget } from "../../agentMcpToolTarget";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import { projectAgentApprovalItem } from "./agentApprovalProjection";
import {
projectAgentAskUserQuestionItem,
projectAgentPlanModeItem
} from "./agentInteractiveProjection";
import { projectAgentTaskItem } from "./agentTaskProjection";
import { resolveAgentToolRendererKind } from "./agentToolRendererKind";
export function projectAgentToolCall(
call: WorkspaceAgentSessionDetailToolCall
): AgentToolCallVM {
const input = objectValue(call.payload?.input);
const output = objectValue(call.payload?.output);
const error = objectValue(call.payload?.error);
const metadata = objectValue(call.payload?.metadata);
const locations = arrayValue(call.payload?.locations);
const approval = projectAgentApprovalItem(call, input, output);
const askUserQuestion = projectAgentAskUserQuestionItem(call, input, output);
const planMode = projectAgentPlanModeItem(call, input);
const task = projectAgentTaskItem(call, input, output, metadata);
const mcpTarget = extractAgentMcpToolTarget({
input,
metadata,
payload: call.payload,
toolName: call.toolName,
name: call.name
});
const rendererKind = resolveAgentToolRendererKind(
{
toolName: call.toolName,
displayName: call.name,
callType: call.callType,
input,
output,
metadata
},
approval,
askUserQuestion,
planMode,
task
);
const projectedCall: AgentToolCallVM = {
kind: "tool-call",
...call,
turnId: call.turnId ?? "turn:unknown",
name: mcpTarget?.displayName ?? call.name,
compactSummary: call.compactSummary ?? call.summary,
payload: call.payload ?? null,
input,
output,
error,
metadata,
locations,
rendererKind,
approval,
askUserQuestion,
planMode,
task,
occurredAtUnixMs: call.occurredAtUnixMs ?? null
};
if (call.sourceTimelineItems) {
projectedCall.sourceTimelineItems = call.sourceTimelineItems;
}
return projectedCall;
}
function objectValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function arrayValue(value: unknown): unknown[] | null {
return Array.isArray(value) ? value : null;
}
@@ -0,0 +1,169 @@
import type { AgentAskUserQuestionItemVM } from "../contracts/agentAskUserQuestionItemVM";
import type { AgentPlanModeItemVM } from "../contracts/agentPlanModeItemVM";
import type { AgentTaskItemVM } from "../contracts/agentTaskItemVM";
import type {
AgentToolCallVM,
AgentToolRendererKind
} from "../contracts/agentToolCallVM";
import { isImageGenerationToolCall } from "../../imageGenerationTool";
interface AgentToolRendererProbe {
toolName: string | null | undefined;
displayName?: string | null | undefined;
callType: string | null | undefined;
input?: Record<string, unknown> | null;
output?: Record<string, unknown> | null;
metadata?: Record<string, unknown> | null;
}
export function resolveAgentToolRendererKind(
call: AgentToolRendererProbe,
approval: AgentToolCallVM["approval"] = null,
askUserQuestion: AgentAskUserQuestionItemVM | null = null,
planMode: AgentPlanModeItemVM | null = null,
task: AgentTaskItemVM | null = null
): AgentToolRendererKind {
const normalizedToolName = normalizeToolName(call.toolName);
const normalizedCallType = normalizeCallType(call.callType);
if (approval) {
return "approval";
}
if (askUserQuestion) {
return "ask-user";
}
if (normalizedToolName === "askuserquestion") {
return "ask-user";
}
if (planMode?.kind === "enter") {
return "plan-enter";
}
if (normalizedToolName === "enterplanmode") {
return "plan-enter";
}
if (planMode?.kind === "exit") {
return "plan-exit";
}
if (normalizedToolName === "exitplanmode") {
return "plan-exit";
}
if (normalizedCallType === "approval" || normalizedToolName === "approval") {
return "approval";
}
if (task) {
return "task";
}
if (
["task", "subagent", "delegatetask", "delegateagent", "agent"].includes(
normalizedToolName
)
) {
return "task";
}
if (
isImageGenerationToolCall({
toolName: call.toolName,
displayName: call.displayName,
outputSavedPath: call.output?.savedPath,
outputSavedPaths: call.output?.savedPaths,
outputMimeType: call.output?.imageMimeType,
outputText: call.output?.text,
inputPrompt: call.input?.prompt
})
) {
return "image-generation";
}
switch (normalizedToolName) {
case "read":
case "readfile":
return "read";
case "write":
case "writefile":
return "write";
case "edit":
case "editfile":
case "multiedit":
return "edit";
case "bash":
case "shell":
case "exec":
case "execcommand":
return "bash";
case "grep":
case "glob":
case "search":
case "searchfiles":
return "search";
case "websearch":
return "web-search";
case "webfetch":
return "web-fetch";
case "todowrite":
return "todo-write";
case "toolsearch":
return "tool-search";
case "skill":
return "skill";
default:
if (
normalizedCallType === "mcp" ||
normalizedToolName.startsWith("mcp") ||
hasMcpMetadata(call.metadata)
) {
return "mcp";
}
return "default";
}
}
export function inferToolCallType(toolName: string | null | undefined): string {
const normalizedToolName = normalizeToolName(toolName);
if (normalizedToolName === "approval") {
return "approval";
}
if (
["askuserquestion", "enterplanmode", "exitplanmode"].includes(
normalizedToolName
)
) {
return "interactive";
}
if (normalizedToolName.startsWith("mcp")) {
return "mcp";
}
return "tool";
}
export function isApprovalToolCall(call: {
toolName: string | null | undefined;
callType: string | null | undefined;
}): boolean {
return (
normalizeCallType(call.callType) === "approval" ||
normalizeToolName(call.toolName) === "approval"
);
}
export function normalizeToolName(value: string | null | undefined): string {
return (value ?? "")
.replace(/[_\s-]+/g, "")
.trim()
.toLowerCase();
}
function hasMcpMetadata(
metadata: Record<string, unknown> | null | undefined
): boolean {
return Boolean(
stringValue(metadata?.server) ??
stringValue(metadata?.serverName) ??
stringValue(metadata?.mcpServer)
);
}
function normalizeCallType(value: string | null | undefined): string {
return (value ?? "").trim().toLowerCase();
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { resolveAgentTranscriptPresentationKind } from "./agentTranscriptPresentation";
describe("resolveAgentTranscriptPresentationKind", () => {
it.each([
["running", "specific-progress"],
["completed", "turn-boundary"],
["failed", "turn-boundary"],
["canceled", "turn-boundary"]
] as const)("maps compact %s to %s", (commandStatus, expected) => {
expect(
resolveAgentTranscriptPresentationKind({
command: "compact",
commandStatus
})
).toBe(expected);
});
it("fails open for unrelated or incomplete notice semantics", () => {
expect(
resolveAgentTranscriptPresentationKind({
command: "review",
commandStatus: "running"
})
).toBe("content");
expect(
resolveAgentTranscriptPresentationKind({
command: "compact",
commandStatus: null
})
).toBe("content");
expect(resolveAgentTranscriptPresentationKind(null)).toBe("content");
});
});
@@ -0,0 +1,36 @@
import type { AgentMessageContentVM } from "../contracts/agentMessageRowVM";
import type { AgentTranscriptPresentationKind } from "../contracts/agentTranscriptPresentation";
import type { AgentTranscriptRowVM } from "../contracts/agentTranscriptRowVM";
type AgentSystemNoticeVM = NonNullable<AgentMessageContentVM["systemNotice"]>;
export function resolveAgentTranscriptPresentationKind(
notice: Pick<AgentSystemNoticeVM, "command" | "commandStatus"> | null
): AgentTranscriptPresentationKind {
if (notice?.command !== "compact") {
return "content";
}
if (notice.commandStatus === "running") {
return "specific-progress";
}
if (
notice.commandStatus === "completed" ||
notice.commandStatus === "failed" ||
notice.commandStatus === "canceled"
) {
return "turn-boundary";
}
return "content";
}
export function agentTranscriptRowHasPresentationKind(
row: AgentTranscriptRowVM | undefined,
presentationKind: AgentTranscriptPresentationKind
): boolean {
return Boolean(
row?.kind === "message" &&
row.messages.some(
(message) => message.presentationKind === presentationKind
)
);
}
@@ -0,0 +1,377 @@
import { describe, expect, it } from "vitest";
import type {
AgentMessageContentVM,
AgentThinkingContentVM
} from "../contracts/agentMessageRowVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import {
computeAgentToolGroups,
type AgentComputedToolGroupVM
} from "./agentToolGroupingProjection";
import type { AgentTurnSequenceItemVM } from "./agentTurnSequenceProjection";
import {
renderRun,
tagOf,
thinkingAbsorbedByMessage,
toRenderUnits,
projectTurnRows,
type AgentRenderUnit
} from "./agentTurnRowProjection";
const TURN = "turn-1";
function thinking(
id: string,
ts: number | null = null
): AgentThinkingContentVM {
return {
kind: "thinking-content",
id,
turnId: TURN,
body: id,
occurredAtUnixMs: ts
};
}
function message(id: string, ts: number | null = null): AgentMessageContentVM {
return {
kind: "message-content",
id,
turnId: TURN,
body: id,
presentationKind: "content",
occurredAtUnixMs: ts
};
}
function toolCall(id: string): AgentToolCallVM {
return {
kind: "tool-call",
id,
turnId: TURN,
rendererKind: "default",
summary: id,
compactSummary: null,
occurredAtUnixMs: null
} as AgentToolCallVM;
}
const thinkingItem = (id: string): AgentTurnSequenceItemVM => ({
kind: "thinking",
thinking: thinking(id)
});
const messageItem = (id: string): AgentTurnSequenceItemVM => ({
kind: "assistant-message",
message: message(id)
});
const userMessageItem = (id: string): AgentTurnSequenceItemVM => ({
kind: "user-message",
row: {
kind: "message",
id: `message:user:${id}`,
turnId: TURN,
speaker: "user",
messages: [message(id)],
thinking: [],
occurredAtUnixMs: null
}
});
const toolItem = (id: string): AgentTurnSequenceItemVM => ({
kind: "tool-call",
call: toolCall(id)
});
const noGroups = new Map<number, AgentComputedToolGroupVM>();
const noSkips = new Set<number>();
describe("tagOf", () => {
const table: { item: AgentTurnSequenceItemVM; expected: string }[] = [
{ item: userMessageItem("u"), expected: "user-message" },
{ item: messageItem("m"), expected: "message" },
{ item: thinkingItem("t"), expected: "thinking" },
{ item: toolItem("c"), expected: "tool" }
];
for (const { item, expected } of table) {
it(`classifies ${item.kind} as ${expected}`, () => {
expect(tagOf(item)).toBe(expected);
});
}
});
describe("thinkingAbsorbedByMessage", () => {
const u = {
thinking: { tag: "thinking", thinking: thinking("t") } as AgentRenderUnit,
message: { tag: "message", message: message("m") } as AgentRenderUnit,
tool: { tag: "tool", call: toolCall("c") } as AgentRenderUnit
};
const table: {
previous: AgentRenderUnit;
current: AgentRenderUnit;
expected: boolean;
}[] = [
{ previous: u.thinking, current: u.message, expected: true },
{ previous: u.thinking, current: u.thinking, expected: false },
{ previous: u.thinking, current: u.tool, expected: false },
{ previous: u.message, current: u.message, expected: false },
{ previous: u.tool, current: u.message, expected: false }
];
for (const { previous, current, expected } of table) {
it(`${previous.tag} -> ${current.tag} = ${expected}`, () => {
expect(thinkingAbsorbedByMessage(previous, current)).toBe(expected);
});
}
});
describe("toRenderUnits", () => {
it("tags message/thinking/tool items in order", () => {
const units = toRenderUnits(
[thinkingItem("t"), messageItem("m"), toolItem("c")],
noGroups,
noSkips
);
expect(units.map((unit) => unit.tag)).toEqual([
"thinking",
"message",
"tool"
]);
});
it("keeps user messages in the turn sequence", () => {
const units = toRenderUnits(
[messageItem("m1"), userMessageItem("u"), messageItem("m2")],
noGroups,
noSkips
);
expect(units.map((unit) => unit.tag)).toEqual([
"message",
"user-message",
"message"
]);
});
it("emits one unit per group and skips its span", () => {
const sequence = [toolItem("c0"), toolItem("c1"), messageItem("m")];
const group: AgentComputedToolGroupVM = {
startIndex: 0,
endIndex: 1,
calls: [toolCall("c0"), toolCall("c1")],
entries: []
};
const units = toRenderUnits(
sequence,
new Map([[0, group]]),
new Set([0, 1])
);
expect(units.map((unit) => unit.tag)).toEqual(["tool-group", "message"]);
});
it("drops suppressed indices so neighbours become adjacent", () => {
// thinking, <suppressed tool>, message -> thinking is now adjacent to message
const units = toRenderUnits(
[thinkingItem("t"), toolItem("c"), messageItem("m")],
noGroups,
new Set([1])
);
expect(units.map((unit) => unit.tag)).toEqual(["thinking", "message"]);
});
});
describe("computeAgentToolGroups", () => {
it("does not group tool calls across a mid-turn user message", () => {
const result = computeAgentToolGroups(
[
toolItem("c0"),
toolItem("c1"),
userMessageItem("u"),
toolItem("c2"),
toolItem("c3")
],
{}
);
expect(
[...result.groups.values()].map((group) =>
group.calls.map((call) => call.id)
)
).toEqual([
["c0", "c1"],
["c2", "c3"]
]);
});
});
describe("renderRun", () => {
it("renders a tool group row", () => {
const group: AgentComputedToolGroupVM = {
startIndex: 0,
endIndex: 1,
calls: [toolCall("c0"), toolCall("c1")],
entries: []
};
const row = renderRun([{ tag: "tool-group", group }], TURN);
expect(row.kind).toBe("tool-group");
expect(row.id).toBe(`tool-group:${TURN}:c0+c1`);
});
it("renders a single tool row", () => {
const row = renderRun([{ tag: "tool", call: toolCall("c") }], TURN);
expect(row.kind).toBe("tool-group");
expect(row.id).toBe("tool-row:c");
});
it("renders a lone thinking row carrying its thinking", () => {
const row = renderRun(
[{ tag: "thinking", thinking: thinking("t", 5) }],
TURN
);
expect(row).toMatchObject({
kind: "message",
id: `message:thinking:${TURN}:t`,
messages: [],
occurredAtUnixMs: 5
});
expect(
row.kind === "message" && row.thinking.map((entry) => entry.id)
).toEqual(["t"]);
});
it("renders a message row that absorbs preceding thinking", () => {
const row = renderRun(
[
{ tag: "thinking", thinking: thinking("t") },
{ tag: "message", message: message("m", 9) }
],
TURN
);
expect(row).toMatchObject({
kind: "message",
id: "message:assistant:m",
occurredAtUnixMs: 9
});
expect(
row.kind === "message" && row.thinking.map((entry) => entry.id)
).toEqual(["t"]);
expect(
row.kind === "message" && row.messages.map((entry) => entry.id)
).toEqual(["m"]);
});
it("renders a message row with empty thinking when none precedes it", () => {
const row = renderRun([{ tag: "message", message: message("m") }], TURN);
expect(row.kind === "message" && row.thinking).toEqual([]);
});
it("renders a user message row without changing its identity", () => {
const item = userMessageItem("u");
if (item.kind !== "user-message") throw new Error("expected user message");
expect(renderRun([{ tag: "user-message", row: item.row }], TURN)).toBe(
item.row
);
});
});
describe("projectTurnRows (behaviour preserved end-to-end)", () => {
const rowShape = (rows: ReturnType<typeof projectTurnRows>) =>
rows.map((row) => ({
kind: row.kind,
id: row.id,
thinking:
row.kind === "message"
? row.thinking.map((entry) => entry.id)
: undefined
}));
it("absorbs a thinking immediately followed by a message", () => {
const rows = projectTurnRows(
[thinkingItem("t"), messageItem("m")],
noGroups,
noSkips,
TURN
);
expect(rowShape(rows)).toEqual([
{ kind: "message", id: "message:assistant:m", thinking: ["t"] }
]);
});
it("only the immediately-preceding thinking is absorbed; earlier ones stand alone", () => {
const rows = projectTurnRows(
[thinkingItem("t1"), thinkingItem("t2"), messageItem("m")],
noGroups,
noSkips,
TURN
);
expect(rowShape(rows)).toEqual([
{ kind: "message", id: `message:thinking:${TURN}:t1`, thinking: ["t1"] },
{ kind: "message", id: "message:assistant:m", thinking: ["t2"] }
]);
});
it("a thinking followed by a tool becomes its own row", () => {
const rows = projectTurnRows(
[thinkingItem("t"), toolItem("c")],
noGroups,
noSkips,
TURN
);
expect(rowShape(rows)).toEqual([
{ kind: "message", id: `message:thinking:${TURN}:t`, thinking: ["t"] },
{ kind: "tool-group", id: "tool-row:c", thinking: undefined }
]);
});
it("a group between thinking and message breaks absorption", () => {
const sequence = [
thinkingItem("t"),
toolItem("c0"),
toolItem("c1"),
messageItem("m")
];
const group: AgentComputedToolGroupVM = {
startIndex: 1,
endIndex: 2,
calls: [toolCall("c0"), toolCall("c1")],
entries: []
};
const rows = projectTurnRows(
sequence,
new Map([[1, group]]),
new Set([1, 2]),
TURN
);
expect(rowShape(rows)).toEqual([
{ kind: "message", id: `message:thinking:${TURN}:t`, thinking: ["t"] },
{
kind: "tool-group",
id: `tool-group:${TURN}:c0+c1`,
thinking: undefined
},
{ kind: "message", id: "message:assistant:m", thinking: [] }
]);
});
it("a suppressed tool between thinking and message keeps absorption", () => {
const rows = projectTurnRows(
[thinkingItem("t"), toolItem("c"), messageItem("m")],
noGroups,
new Set([1]),
TURN
);
expect(rowShape(rows)).toEqual([
{ kind: "message", id: "message:assistant:m", thinking: ["t"] }
]);
});
it("a user message is a visible boundary between assistant rows", () => {
const rows = projectTurnRows(
[messageItem("m1"), userMessageItem("u"), messageItem("m2")],
noGroups,
noSkips,
TURN
);
expect(rows.map((row) => row.id)).toEqual([
"message:assistant:m1",
"message:user:u",
"message:assistant:m2"
]);
});
});
@@ -0,0 +1,176 @@
import type {
AgentMessageContentVM,
AgentThinkingContentVM
} from "../contracts/agentMessageRowVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import type { AgentTranscriptRowVM } from "../contracts/agentTranscriptRowVM";
import type { AgentComputedToolGroupVM } from "./agentToolGroupingProjection";
import type { AgentTurnSequenceItemVM } from "./agentTurnSequenceProjection";
import {
projectAgentSingleToolRow,
projectAgentToolGroupRowFromGroup
} from "./agentToolGroupingProjection";
import { chunkBy } from "./chunkBy";
/**
* A render unit is one item that will become (part of) a single transcript
* row. Unlike the raw turn sequence, tool groups have already been resolved to
* one unit spanning their calls, and grouped/suppressed indices have been
* dropped. This flattening is what lets the row pass reason about immediate
* neighbours instead of looking ahead across skipped indices.
*/
export type AgentRenderUnit =
| { tag: "tool-group"; group: AgentComputedToolGroupVM }
| { tag: "tool"; call: AgentToolCallVM }
| {
tag: "user-message";
row: Extract<AgentTranscriptRowVM, { kind: "message" }>;
}
| { tag: "thinking"; thinking: AgentThinkingContentVM }
| { tag: "message"; message: AgentMessageContentVM };
export type AgentRenderUnitTag = AgentRenderUnit["tag"];
/** Pure classifier for a raw turn sequence item. */
export function tagOf(
item: AgentTurnSequenceItemVM
): "user-message" | "message" | "thinking" | "tool" {
switch (item.kind) {
case "user-message":
return "user-message";
case "assistant-message":
return "message";
case "thinking":
return "thinking";
case "tool-call":
return "tool";
}
}
/**
* Run predicate: a thinking unit is absorbed into the assistant message that
* immediately follows it (rendered as that message's `thinking`). Every other
* adjacency starts a new run, so tools, tool groups and lone thinking each
* become their own row.
*/
export function thinkingAbsorbedByMessage(
previous: AgentRenderUnit,
current: AgentRenderUnit
): boolean {
return previous.tag === "thinking" && current.tag === "message";
}
/**
* Resolve the raw turn sequence into render units: emit one unit per tool
* group (skipping its span), drop grouped/suppressed indices, and tag the
* remaining message/thinking/tool items. Removing skipped items here is what
* makes a thinking and a later message become adjacent units when only
* suppressed tools sat between them.
*/
export function toRenderUnits(
sequence: readonly AgentTurnSequenceItemVM[],
groups: ReadonlyMap<number, AgentComputedToolGroupVM>,
skippedIndices: ReadonlySet<number>
): AgentRenderUnit[] {
const units: AgentRenderUnit[] = [];
for (let index = 0; index < sequence.length; index += 1) {
const group = groups.get(index);
if (group) {
units.push({ tag: "tool-group", group });
index = group.endIndex;
continue;
}
if (skippedIndices.has(index)) {
continue;
}
const item = sequence[index];
if (!item) {
continue;
}
switch (item.kind) {
case "user-message":
units.push({ tag: "user-message", row: item.row });
break;
case "assistant-message":
units.push({ tag: "message", message: item.message });
break;
case "thinking":
units.push({ tag: "thinking", thinking: item.thinking });
break;
case "tool-call":
units.push({ tag: "tool", call: item.call });
break;
}
}
return units;
}
/**
* Render one run into a transcript row. A run is either a singleton
* (tool group / tool / lone thinking) or leading thinking units followed by a
* single assistant message that absorbs them.
*/
export function renderRun(
run: readonly AgentRenderUnit[],
turnId: string,
agentSessionId?: string
): AgentTranscriptRowVM {
const last = run.at(-1);
if (!last) {
throw new Error("renderRun received an empty run");
}
if (last.tag === "tool-group") {
return projectAgentToolGroupRowFromGroup(
turnId,
last.group,
agentSessionId
);
}
if (last.tag === "tool") {
return projectAgentSingleToolRow(last.call, turnId);
}
if (last.tag === "user-message") {
return last.row;
}
const thinking = run
.filter(
(unit): unit is Extract<AgentRenderUnit, { tag: "thinking" }> =>
unit.tag === "thinking"
)
.map((unit) => unit.thinking);
if (last.tag === "message") {
return {
kind: "message",
id: `message:assistant:${last.message.id}`,
turnId: last.message.turnId,
speaker: "assistant",
messages: [last.message],
thinking,
occurredAtUnixMs: last.message.occurredAtUnixMs
};
}
return {
kind: "message",
id: `message:thinking:${turnId}:${thinking.map((entry) => entry.id).join("+")}`,
turnId,
speaker: "assistant",
messages: [],
thinking,
occurredAtUnixMs:
thinking.at(-1)?.occurredAtUnixMs ?? thinking[0]?.occurredAtUnixMs ?? null
};
}
/** Project a turn's sequence (with computed groups/skips) into transcript rows. */
export function projectTurnRows(
sequence: readonly AgentTurnSequenceItemVM[],
groups: ReadonlyMap<number, AgentComputedToolGroupVM>,
skippedIndices: ReadonlySet<number>,
turnId: string,
agentSessionId?: string
): AgentTranscriptRowVM[] {
const units = toRenderUnits(sequence, groups, skippedIndices);
return chunkBy(units, thinkingAbsorbedByMessage).map((run) =>
renderRun(run, turnId, agentSessionId)
);
}
@@ -0,0 +1,126 @@
import { describe, expect, it } from "vitest";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import type { WorkspaceAgentSessionDetailTurn } from "../../workspaceAgentSessionDetailViewModel";
import { buildAgentTurnSequenceItems } from "./agentTurnSequenceProjection";
function timelineItem(
id: number,
seq: number,
occurredAtUnixMs: number
): WorkspaceAgentActivityTimelineItem {
return {
id,
actorId: "agent",
actorType: "agent",
agentSessionId: "session-1",
eventId: `event-${id}`,
itemType: "event",
seq,
occurredAtUnixMs
};
}
function makeTurn(): WorkspaceAgentSessionDetailTurn {
return {
id: "turn-1",
userMessage: null,
userMessages: [],
agentMessages: [],
toolCalls: [],
toolCallCount: 1,
hasFailedToolCall: false,
agentItems: [
{
kind: "message",
message: {
id: "assistant-1",
body: "assistant reply",
occurredAtUnixMs: 200,
sourceTimelineItems: [timelineItem(2, 2, 200)]
}
},
{
kind: "tool-calls",
id: "tool-group",
toolCallCount: 1,
hasFailedToolCall: false,
toolCalls: [
{
id: "tool-1",
name: "Bash",
toolName: "bash",
callType: "tool",
status: "completed",
statusKind: "completed",
summary: "",
payload: null,
occurredAtUnixMs: 100,
sourceTimelineItems: [timelineItem(1, 1, 100)]
}
]
},
{
kind: "thinking",
thinking: {
id: "thinking-1",
body: "thinking"
}
}
]
};
}
describe("buildAgentTurnSequenceItems", () => {
it("uses known pairwise positions when another row has no position", () => {
const sequence = buildAgentTurnSequenceItems(makeTurn());
expect(sequence.map((item) => item.kind)).toEqual([
"tool-call",
"assistant-message",
"thinking"
]);
expect(sequence[0]?.kind === "tool-call" && sequence[0].call.id).toBe(
"tool-1"
);
});
it("keeps a transitive order when sequence and timestamp metadata are mixed", () => {
const sequence = buildAgentTurnSequenceItems({
...makeTurn(),
agentItems: [
toolGroup("seq-1", 1, 300),
toolGroup("timestamp-only", 0, 200),
toolGroup("seq-2", 2, 100)
]
});
expect(
sequence.map((item) =>
item.kind === "tool-call" ? item.call.id : "unexpected"
)
).toEqual(["seq-1", "seq-2", "timestamp-only"]);
});
});
function toolGroup(id: string, seq: number, occurredAtUnixMs: number) {
return {
kind: "tool-calls" as const,
id: `group-${id}`,
toolCallCount: 1,
hasFailedToolCall: false,
toolCalls: [
{
id,
name: "Bash",
toolName: "bash",
callType: "tool" as const,
status: "completed" as const,
statusKind: "completed" as const,
summary: "",
payload: null,
occurredAtUnixMs,
sourceTimelineItems: [timelineItem(id.length, seq, occurredAtUnixMs)]
}
]
};
}
@@ -0,0 +1,282 @@
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import type {
WorkspaceAgentSessionDetailMessage,
WorkspaceAgentSessionDetailThinking,
WorkspaceAgentSessionDetailTurn
} from "../../workspaceAgentSessionDetailViewModel";
import type {
AgentMessageContentVM,
AgentMessageRowVM,
AgentThinkingContentVM
} from "../contracts/agentMessageRowVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import { isApprovalToolCall } from "./agentToolRendererKind";
import { resolveAgentTranscriptPresentationKind } from "./agentTranscriptPresentation";
import { projectAgentToolCall } from "./agentToolProjection";
import {
isCollaborationTimelineItem,
projectAgentCollaborationVM
} from "./agentCollaborationProjection";
import { projectConversationUserRow } from "./agentConversationUserProjection";
import { parseTuttiPlanIssueLink } from "../tuttiModePlanIssueLinkMarker";
export type AgentTurnSequenceItemVM =
| {
kind: "user-message";
row: AgentMessageRowVM;
}
| {
kind: "assistant-message";
message: AgentMessageContentVM;
}
| {
kind: "thinking";
thinking: AgentThinkingContentVM;
}
| {
kind: "tool-call";
call: AgentToolCallVM;
};
export function buildAgentTurnSequenceItems(
turn: WorkspaceAgentSessionDetailTurn,
workspaceId?: string | null
): AgentTurnSequenceItemVM[] {
const items = turn.rawAgentItems ?? turn.agentItems;
const sequence: AgentTurnSequenceItemVM[] = turn.userMessages.map(
(message) => ({
kind: "user-message",
row: projectConversationUserRow(message, turn.id, workspaceId)
})
);
items.forEach((item) => {
if (item.kind === "message") {
sequence.push({
kind: "assistant-message",
message: projectMessage(item.message, turn.id)
});
return;
}
if (item.kind === "thinking") {
sequence.push({
kind: "thinking",
thinking: projectThinking(item.thinking, turn.id)
});
return;
}
const sourceEntries =
item.groupEntries ??
item.toolCalls.map((call) => ({ kind: "tool-call", call }) as const);
sourceEntries.forEach((entry) => {
if (entry.kind === "thinking") {
sequence.push({
kind: "thinking",
thinking: projectThinking(entry.thinking, turn.id)
});
return;
}
if (isApprovalToolCall(entry.call)) {
return;
}
sequence.push({
kind: "tool-call",
call: projectAgentToolCall(entry.call)
});
});
});
return sortTurnSequenceItems(sequence);
}
type PositionedTurnSequenceEntry = {
item: AgentTurnSequenceItemVM;
sourceIndex: number;
position: {
seq: number;
occurredAtUnixMs: number;
};
};
function sortTurnSequenceItems(
sequence: readonly AgentTurnSequenceItemVM[]
): AgentTurnSequenceItemVM[] {
const positioned: PositionedTurnSequenceEntry[] = sequence.map(
(item, sourceIndex) => ({
item,
sourceIndex,
position: turnSequencePosition(item)
})
);
const sorted: typeof positioned = [];
let comparableSegment: typeof positioned = [];
const flushComparableSegment = () => {
sorted.push(...comparableSegment.sort(compareTurnSequenceEntries));
comparableSegment = [];
};
for (const entry of positioned) {
if (turnSequencePositionRank(entry.position) === 2) {
// An unpositioned row is a hard boundary. Its relation to either side
// is unknown, so moving known rows across it would change adjacency.
flushComparableSegment();
sorted.push(entry);
continue;
}
comparableSegment.push(entry);
}
flushComparableSegment();
return sorted.map((entry) => entry.item);
}
function compareTurnSequenceEntries(
left: PositionedTurnSequenceEntry,
right: PositionedTurnSequenceEntry
): number {
const leftRank = turnSequencePositionRank(left.position);
const rightRank = turnSequencePositionRank(right.position);
if (leftRank !== rightRank) {
return leftRank - rightRank;
}
if (leftRank === 0 && left.position.seq !== right.position.seq) {
return left.position.seq - right.position.seq;
}
if (
leftRank === 1 &&
left.position.occurredAtUnixMs !== right.position.occurredAtUnixMs
) {
return left.position.occurredAtUnixMs - right.position.occurredAtUnixMs;
}
return left.sourceIndex - right.sourceIndex;
}
function turnSequencePositionRank(position: {
seq: number;
occurredAtUnixMs: number;
}): 0 | 1 | 2 {
if (position.seq > 0) {
return 0;
}
if (position.occurredAtUnixMs > 0) {
return 1;
}
return 2;
}
function turnSequencePosition(item: AgentTurnSequenceItemVM): {
seq: number;
occurredAtUnixMs: number;
} {
const sourceItems = turnSequenceSourceItems(item);
const seq = minimumPositive(
sourceItems.map((sourceItem) => sourceItem.seq ?? 0)
);
const occurredAtUnixMs = minimumPositive(
sourceItems.map(
(sourceItem) =>
sourceItem.occurredAtUnixMs ?? sourceItem.createdAtUnixMs ?? 0
)
);
if (occurredAtUnixMs > 0) {
return { seq, occurredAtUnixMs };
}
switch (item.kind) {
case "user-message":
return { seq, occurredAtUnixMs: item.row.occurredAtUnixMs ?? 0 };
case "assistant-message":
return { seq, occurredAtUnixMs: item.message.occurredAtUnixMs ?? 0 };
case "thinking":
return { seq, occurredAtUnixMs: item.thinking.occurredAtUnixMs ?? 0 };
case "tool-call":
return { seq, occurredAtUnixMs: item.call.occurredAtUnixMs ?? 0 };
}
}
function turnSequenceSourceItems(
item: AgentTurnSequenceItemVM
): WorkspaceAgentActivityTimelineItem[] {
switch (item.kind) {
case "user-message":
return item.row.messages.flatMap(
(message) => message.sourceTimelineItems ?? []
);
case "assistant-message":
return item.message.sourceTimelineItems ?? [];
case "thinking":
return item.thinking.sourceTimelineItems ?? [];
case "tool-call":
return item.call.sourceTimelineItems ?? [];
}
}
function minimumPositive(values: readonly number[]): number {
return values.reduce(
(minimum, value) =>
value > 0 && (minimum === 0 || value < minimum) ? value : minimum,
0
);
}
function projectMessage(
message: WorkspaceAgentSessionDetailMessage,
turnId: string
): AgentMessageContentVM {
const projected: AgentMessageContentVM = {
kind: "message-content",
id: message.id,
turnId: message.turnId ?? turnId,
body: message.body,
presentationKind: resolveAgentTranscriptPresentationKind(
message.systemNotice ?? null
),
statusKind: message.statusKind ?? null,
occurredAtUnixMs: message.occurredAtUnixMs ?? null,
visibleError: message.visibleError ?? null,
systemNotice: message.systemNotice ?? null
};
if (message.sourceTimelineItems) {
projected.sourceTimelineItems = message.sourceTimelineItems;
if (
message.sourceTimelineItems.some(
(item) => item.payload?.messageKind === "plan"
)
) {
projected.contentKind = "plan";
}
const collaborationItem = message.sourceTimelineItems.find(
isCollaborationTimelineItem
);
if (collaborationItem) {
const collaboration = projectAgentCollaborationVM(collaborationItem);
if (collaboration) {
projected.contentKind = "collaboration";
projected.collaboration = collaboration;
}
}
}
// Message id carries the stable "plan-issue:<issueID>" identity (it is the
// daemon messageId via the timeline eventId). A malformed body parses to
// null and stays a plain assistant markdown message.
const planIssueLink = parseTuttiPlanIssueLink(message.id, message.body);
if (planIssueLink) {
projected.contentKind = "tutti-plan-issue-link";
projected.planIssueLink = planIssueLink;
}
return projected;
}
function projectThinking(
thinking: WorkspaceAgentSessionDetailThinking,
turnId: string
): AgentThinkingContentVM {
const projected: AgentThinkingContentVM = {
kind: "thinking-content",
id: thinking.id,
turnId: thinking.turnId ?? turnId,
body: thinking.body,
statusKind: thinking.statusKind ?? null,
occurredAtUnixMs: thinking.occurredAtUnixMs ?? null
};
if (thinking.sourceTimelineItems) {
projected.sourceTimelineItems = thinking.sourceTimelineItems;
}
return projected;
}
@@ -0,0 +1,217 @@
import { resolveWorkspaceFilePathCandidate } from "../../../actions/workspaceFilePathCandidate";
import type { AgentTurnSummaryFileVM } from "../contracts/agentTurnSummaryRowVM";
export type AgentTurnSummaryChangeType = AgentTurnSummaryFileVM["changeType"];
export interface AgentTurnSummaryProjectionOptions {
defaultCwd?: string | null;
workspaceRoot?: string | null;
}
export function normalizedFilePath(
value: string | null,
options: AgentTurnSummaryProjectionOptions = {}
): string | null {
const path = value?.trim() ?? "";
if (!path || isStructuredPayloadPath(path) || isIgnoredFilePath(path)) {
return null;
}
const candidate = resolveWorkspaceFilePathCandidate({
path,
workspaceRoot: options.workspaceRoot,
basePath: options.defaultCwd
});
return candidate?.path ?? null;
}
function isIgnoredFilePath(path: string): boolean {
const normalizedPath = path.replace(/\\/g, "/").replace(/\/+$/, "");
return normalizedPath === "/dev/null" || normalizedPath === "NUL";
}
function isStructuredPayloadPath(path: string): boolean {
if (/[\r\n]/.test(path)) {
return true;
}
if (!path.startsWith("{") && !path.startsWith("[")) {
return false;
}
try {
JSON.parse(path);
return true;
} catch {
return false;
}
}
export function applyShortestUniqueFileLabels(
files: AgentTurnSummaryFileVM[]
): AgentTurnSummaryFileVM[] {
const suffixByPath = shortestUniquePathSuffixByPath(
files.map((file) => file.path)
);
return files.map((file) => ({
...file,
label: suffixByPath.get(file.path) ?? file.label
}));
}
function shortestUniquePathSuffixByPath(paths: string[]): Map<string, string> {
const partsByPath = new Map(
paths.map((path) => [path, splitPathSegments(path)])
);
const labels = new Map<string, string>();
const unresolved = new Set(paths);
for (let depth = 1; unresolved.size > 0; depth += 1) {
const grouped = new Map<string, string[]>();
for (const path of unresolved) {
const parts = partsByPath.get(path) ?? [];
const label =
parts.slice(-Math.min(depth, parts.length)).join("/") ||
parts.at(-1) ||
path;
grouped.set(label, [...(grouped.get(label) ?? []), path]);
}
let resolvedCount = 0;
for (const [label, group] of grouped) {
if (group.length !== 1 || !group[0]) {
continue;
}
labels.set(group[0], label);
unresolved.delete(group[0]);
resolvedCount += 1;
}
if (resolvedCount === 0) {
for (const path of unresolved) {
labels.set(path, path);
}
break;
}
}
return labels;
}
export function splitFilePath(path: string): {
fileName: string;
directory: string | null;
} {
const normalized = path.trim();
const parts = splitPathSegments(normalized);
if (parts.length <= 1) {
return { fileName: parts[0] ?? normalized, directory: null };
}
return {
fileName: parts.at(-1) ?? normalized,
directory: parts.slice(0, -1).join("/")
};
}
function splitPathSegments(path: string): string[] {
return path.trim().split(/[\\/]/).filter(Boolean);
}
export function normalizeChangeType(
value: string | null
): AgentTurnSummaryChangeType | null {
switch ((value ?? "").trim().toLowerCase()) {
case "add":
case "added":
case "create":
case "created":
case "new":
return "created";
case "modify":
case "modified":
case "edit":
case "edited":
case "change":
case "changed":
case "update":
case "updated":
return "modified";
case "delete":
case "deleted":
case "remove":
case "removed":
return "deleted";
default:
return null;
}
}
export function isFailedToolStatus(value: string | null): boolean {
const normalized = (value ?? "").trim().toLowerCase();
return ["failed", "error", "errored", "canceled", "cancelled"].includes(
normalized
);
}
export function objectValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
export function firstFileChangeValue(...values: unknown[]): unknown {
for (const value of values) {
if (Array.isArray(value) || objectValue(value)) {
return value;
}
}
return null;
}
export function arrayValue(value: unknown): unknown[] | null {
return Array.isArray(value) ? value : null;
}
export function nestedTaskStepsFromPayload(
payload: Record<string, unknown> | null,
output: Record<string, unknown> | null
): unknown[] {
const candidates = [
arrayValue(payload?.steps),
arrayValue(output?.steps),
arrayValue(objectValue(payload?.metadata)?.steps),
arrayValue(objectValue(output?.metadata)?.steps)
];
return candidates.find((value) => value && value.length > 0) ?? [];
}
export function nestedTaskStepStatusKind(
step: Record<string, unknown>,
fallback: string | null
): string | null {
return (
stringValue(step.statusKind) ?? stringValue(step.status) ?? fallback ?? null
);
}
export function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function literalStringValue(value: unknown): string | null {
return typeof value === "string" ? value : null;
}
export function firstNonEmptyString(
...values: Array<string | null | undefined>
): string | null {
for (const value of values) {
if (typeof value === "string" && value.trim()) {
return value.trim();
}
}
return null;
}
export function firstPresentString(
...values: Array<string | null | undefined>
): string | null {
for (const value of values) {
if (typeof value === "string") {
return value;
}
}
return null;
}
@@ -0,0 +1,557 @@
import { describe, expect, it } from "vitest";
import { normalizeAgentActivitySession } from "@tutti-os/agent-activity-core";
import type { WorkspaceAgentActivityCard } from "../../workspaceAgentActivityListViewModel";
import type {
WorkspaceAgentSessionDetailTurn,
WorkspaceAgentSessionDetailViewModel
} from "../../workspaceAgentSessionDetailViewModel";
import {
projectAgentTurnSummaryRowForTurn,
projectAgentTurnSummaryRows
} from "./agentTurnSummaryProjection";
describe("agent turn summary canonical projection", () => {
it("canonicalizes Windows drive aliases in changed-file paths", () => {
const rows = projectAgentTurnSummaryRowForTurn(
turn("turn-windows"),
{
files: [
{
path: "/c/Users/demo/project/0817.txt",
change: "added"
}
]
},
{
workspaceRoot: "C:\\Users\\demo\\project",
defaultCwd: "C:\\Users\\demo\\project"
}
);
expect(rows[0]?.files[0]?.path).toBe("/C:/Users/demo/project/0817.txt");
});
it("projects create, modify, and delete semantics from turn.fileChanges", () => {
const rows = projectAgentTurnSummaryRowForTurn(
turn("turn-1"),
{
files: [
{
path: "/workspace/src/app.ts",
change: "modified",
diff: "@@ -1 +1 @@\n-old\n+new"
},
{
path: "/workspace/src/routes.ts",
change: "added",
oldString: "",
newString: "export const routes = []"
},
{
path: "/workspace/obsolete.txt",
change: "deleted",
oldString: "obsolete\n",
newString: ""
}
]
},
{ workspaceRoot: "/workspace", occurredAtUnixMs: 40 }
);
expect(rows).toHaveLength(1);
expect(rows[0]).toMatchObject({
fileCount: 3,
createdCount: 1,
modifiedCount: 2,
occurredAtUnixMs: 40
});
expect(
rows[0]?.files.map(({ path, changeType, label }) => ({
path,
changeType,
label
}))
).toEqual([
{
path: "/workspace/src/app.ts",
changeType: "modified",
label: "app.ts"
},
{
path: "/workspace/src/routes.ts",
changeType: "created",
label: "routes.ts"
},
{
path: "/workspace/obsolete.txt",
changeType: "deleted",
label: "obsolete.txt"
}
]);
});
it("does not expose invalid file bodies as unified diffs", () => {
const body = "# README\n\n- bullet\n";
const rows = projectAgentTurnSummaryRowForTurn(
turn("turn-invalid-diff"),
{
files: [
{
path: "/workspace/README.md",
change: "created",
diff: body
},
{
path: "/workspace/obsolete.md",
change: "deleted",
unifiedDiff: body
}
]
},
{ workspaceRoot: "/workspace" }
);
expect(rows[0]?.files).toEqual([
expect.objectContaining({
path: "/workspace/README.md",
unifiedDiff: null,
content: body
}),
expect.objectContaining({
path: "/workspace/obsolete.md",
unifiedDiff: null,
oldString: body,
newString: ""
})
]);
});
it("keeps executable patch batches separate from canonical presentation", () => {
const sourceTurn = turn("turn-patch", [
{
id: "call-patch",
name: "Edit",
toolName: "Edit",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "Edit two files",
occurredAtUnixMs: 20,
payload: {
input: {
cwd: "/workspace",
changes: [
{
path: "/workspace/src/app.ts",
type: "update",
oldString: "old",
newString: "new"
},
{
path: "/workspace/not-in-turn.ts",
type: "update",
oldString: "old",
newString: "new"
}
]
}
}
}
]);
const rows = projectAgentTurnSummaryRowForTurn(
sourceTurn,
{
files: [
{
path: "/workspace/src/app.ts",
change: "modified"
},
{
path: "/workspace/not-in-turn.ts",
change: "modified"
}
]
},
{ workspaceRoot: "/workspace", defaultCwd: "/workspace" }
);
expect(rows[0]?.patchBatches).toEqual([
{
cwd: "/workspace",
toolCallId: "call-patch",
changes: [
expect.objectContaining({
path: "/workspace/src/app.ts",
changeType: "modified",
oldString: "old",
newString: "new"
}),
expect.objectContaining({
path: "/workspace/not-in-turn.ts",
changeType: "modified",
oldString: "old",
newString: "new"
})
]
}
]);
});
it("prefers canonical fileChanges over contradictory raw Kimi changes", () => {
const content =
"这是一个示例文本文件。\n\n当前时间:2026-08-20\n用途:测试文件创建\n\n你可以随时修改或删除此文件。";
const sourceTurn = turn("turn-kimi-create", [
{
id: "call-kimi-create",
name: "Write",
toolName: "Write",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "Create note.txt",
occurredAtUnixMs: 20,
payload: {
cwd: "C:/Users/17940/Documents/tutti/test_git",
fileChanges: {
files: [
{
path: "C:/Users/17940/Documents/tutti/test_git/note.txt",
change: "added",
oldString: "",
newString: content
}
]
},
output: {
changes: [
{
path: "C:/Users/17940/Documents/tutti/test_git/note.txt",
type: "update",
oldString: "",
newString: content
}
]
}
}
}
]);
const rows = projectAgentTurnSummaryRowForTurn(
sourceTurn,
{
files: [
{
path: "C:/Users/17940/Documents/tutti/test_git/note.txt",
change: "added",
oldString: "",
newString: content
}
]
},
{
workspaceRoot: "C:/Users/17940/Documents/tutti/test_git",
defaultCwd: "C:/Users/17940/Documents/tutti/test_git"
}
);
expect(rows[0]?.patchBatches).toEqual([
{
cwd: "C:/Users/17940/Documents/tutti/test_git",
toolCallId: "call-kimi-create",
changes: [
expect.objectContaining({
path: "/C:/Users/17940/Documents/tutti/test_git/note.txt",
changeType: "created",
oldString: "",
newString: content
})
]
}
]);
});
it("drops historical one-sided modified raw changes without a canonical batch", () => {
const sourceTurn = turn("turn-legacy-one-sided", [
{
id: "call-legacy-one-sided",
name: "Write",
toolName: "Write",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "Write note.txt",
occurredAtUnixMs: 20,
payload: {
input: {
cwd: "/workspace",
changes: [
{
path: "/workspace/note.txt",
type: "update",
newString: "after"
}
]
}
}
}
]);
const rows = projectAgentTurnSummaryRowForTurn(
sourceTurn,
{
files: [{ path: "/workspace/note.txt", change: "modified" }]
},
{ workspaceRoot: "/workspace", defaultCwd: "/workspace" }
);
expect(rows[0]?.patchBatches).toBeUndefined();
});
it("fails the whole batch closed when one canonical sibling is incomplete", () => {
const sourceTurn = turn("turn-mixed-coverage", [
{
id: "call-mixed-coverage",
name: "Write",
toolName: "Write",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "Write two files",
occurredAtUnixMs: 20,
payload: {
cwd: "/workspace",
fileChanges: {
files: [
{
path: "/workspace/created.txt",
change: "added",
oldString: "",
newString: "created"
},
{
path: "/workspace/incomplete.txt",
change: "modified",
newString: "after"
}
]
}
}
}
]);
const rows = projectAgentTurnSummaryRowForTurn(
sourceTurn,
{
files: [
{ path: "/workspace/created.txt", change: "added" },
{ path: "/workspace/incomplete.txt", change: "modified" }
]
},
{ workspaceRoot: "/workspace", defaultCwd: "/workspace" }
);
expect(rows[0]?.patchBatches).toBeUndefined();
});
it("fails closed for historical rename metadata without an executable diff", () => {
const sourceTurn = turn("turn-legacy-rename", [
{
id: "call-legacy-rename",
name: "Move",
toolName: "Move",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: "Rename note.txt",
occurredAtUnixMs: 20,
payload: {
cwd: "/workspace",
changes: [
{
path: "/workspace/new-name.txt",
oldPath: "/workspace/note.txt",
type: "move"
}
]
}
}
]);
const rows = projectAgentTurnSummaryRowForTurn(
sourceTurn,
{
files: [{ path: "/workspace/new-name.txt", change: "modified" }]
},
{ workspaceRoot: "/workspace", defaultCwd: "/workspace" }
);
expect(rows[0]?.patchBatches).toBeUndefined();
});
it("projects every canonical settled turn and ignores legacy tool inference", () => {
const older = turn("turn-old", [legacyWrite("old.txt")]);
const latest = turn("turn-latest", [legacyWrite("wrong.txt")]);
const source = detail([older, latest], {
files: [{ path: "/workspace/current.txt", change: "modified" }]
});
source.sessionTurns = [
{
agentSessionId: "session-1",
turnId: "turn-old",
phase: "settled",
origin: "user_prompt",
outcome: "completed",
startedAtUnixMs: 1,
settledAtUnixMs: 20,
updatedAtUnixMs: 20,
fileChanges: {
files: [
{
path: "/workspace/obsolete.txt",
change: "deleted",
oldString: "obsolete",
newString: ""
}
]
}
},
{
agentSessionId: "session-1",
turnId: "turn-latest",
phase: "settled",
origin: "user_prompt",
outcome: "completed",
startedAtUnixMs: 21,
settledAtUnixMs: 40,
updatedAtUnixMs: 40,
fileChanges: {
files: [
{
path: "/workspace/current.txt",
change: "modified"
}
]
}
}
];
const rows = projectAgentTurnSummaryRows(source);
expect(rows).toHaveLength(2);
expect(rows.map((row) => row.turnId)).toEqual(["turn-old", "turn-latest"]);
expect(rows[0]?.files).toEqual([
expect.objectContaining({
path: "/workspace/obsolete.txt",
changeType: "deleted"
})
]);
});
it("does not backfill missing turn.fileChanges from current or historical payloads", () => {
const source = detail([turn("turn-latest", [legacyWrite("legacy.txt")])]);
source.activity.changedFiles = [
{ path: "/workspace/activity.txt", label: "activity.txt" }
];
expect(projectAgentTurnSummaryRows(source)).toEqual([]);
});
});
function turn(
id: string,
toolCalls: WorkspaceAgentSessionDetailTurn["toolCalls"] = []
): WorkspaceAgentSessionDetailTurn {
return {
id,
userMessage: null,
userMessages: [],
agentMessages: [],
toolCalls,
toolCallCount: toolCalls.length,
hasFailedToolCall: false,
agentItems: []
};
}
function legacyWrite(
fileName: string
): WorkspaceAgentSessionDetailTurn["toolCalls"][number] {
return {
id: `call:${fileName}`,
name: "Write",
toolName: "Write",
callType: "tool",
status: "Completed",
statusKind: "completed",
summary: fileName,
occurredAtUnixMs: 10,
payload: {
input: {
file_path: `/workspace/${fileName}`,
content: "legacy"
}
}
};
}
function detail(
turns: WorkspaceAgentSessionDetailTurn[],
fileChanges?: Record<string, unknown>
): WorkspaceAgentSessionDetailViewModel {
const latestTurnId = turns.at(-1)?.id ?? "turn-latest";
return {
activity: {
id: "activity-1",
sessionId: "session-1",
userId: "user-1",
userName: "User",
agentProvider: "cursor",
agentName: "Cursor",
title: "Edit files",
latestActivitySummary: "Completed",
status: "completed",
changedFiles: [],
sortTimeUnixMs: 40
} satisfies WorkspaceAgentActivityCard,
session: normalizeAgentActivitySession({
workspaceId: "workspace-1",
agentSessionId: "session-1",
provider: "cursor",
providerSessionId: "provider-1",
cwd: "/workspace",
title: "Edit files",
activeTurnId: null,
latestTurnInteractions: [],
pendingInteractions: [],
latestTurn: {
agentSessionId: "session-1",
turnId: latestTurnId,
phase: "settled",
origin: "user_prompt",
outcome: "completed",
startedAtUnixMs: 1,
settledAtUnixMs: 40,
updatedAtUnixMs: 40,
...(fileChanges ? { fileChanges } : {})
}
}),
cwd: "/workspace",
workspaceRoot: "/workspace",
sessionTurns: fileChanges
? [
{
agentSessionId: "session-1",
turnId: latestTurnId,
phase: "settled",
origin: "user_prompt",
outcome: "completed",
startedAtUnixMs: 1,
settledAtUnixMs: 40,
updatedAtUnixMs: 40,
fileChanges
}
]
: [],
turns
};
}
@@ -0,0 +1,409 @@
import type {
WorkspaceAgentSessionDetailToolCall,
WorkspaceAgentSessionDetailTurn,
WorkspaceAgentSessionDetailViewModel
} from "../../workspaceAgentSessionDetailViewModel";
import type {
AgentTurnSummaryPatchBatchVM,
AgentTurnSummaryPatchChangeVM,
AgentTurnSummaryFileVM,
AgentTurnSummaryRowVM
} from "../contracts/agentTurnSummaryRowVM";
import { inferAgentPatchChangeType } from "../rules/agentPatchMetadata";
import { isAgentUnifiedDiffText } from "../rules/agentUnifiedDiffValidation";
import {
fileChangeEntriesFromChanges,
fileChangeTypeValue
} from "../../workspaceAgentFileChangePayload";
import {
applyShortestUniqueFileLabels,
arrayValue,
firstFileChangeValue,
firstNonEmptyString,
firstPresentString,
isFailedToolStatus,
literalStringValue,
nestedTaskStepsFromPayload,
nestedTaskStepStatusKind,
normalizedFilePath,
normalizeChangeType,
objectValue,
splitFilePath,
stringValue
} from "./agentTurnSummaryFileProjection";
interface AgentTurnSummaryProjectionOptions {
defaultCwd?: string | null;
workspaceRoot?: string | null;
occurredAtUnixMs?: number | null;
}
/**
* Projects the response-tail file list from durable turn state. Tool calls are
* consulted only for executable Undo/Reapply patch batches; they never infer
* which files changed or whether a change was create/modify/delete.
*/
export function projectAgentTurnSummaryRows(
detail: WorkspaceAgentSessionDetailViewModel
): AgentTurnSummaryRowVM[] {
const transcriptTurnsById = new Map(
detail.turns.map((turn) => [turn.id, turn])
);
return (detail.sessionTurns ?? []).flatMap((turn) => {
const transcriptTurn = transcriptTurnsById.get(turn.turnId);
if (
!isSettledTurnSummaryVisible(detail, turn.turnId, turn.phase) ||
!turn.fileChanges ||
!transcriptTurn
) {
return [];
}
return projectAgentTurnSummaryRowForTurn(transcriptTurn, turn.fileChanges, {
defaultCwd: detail.cwd,
workspaceRoot: detail.workspaceRoot,
occurredAtUnixMs: turn.updatedAtUnixMs
});
});
}
function isSettledTurnSummaryVisible(
detail: WorkspaceAgentSessionDetailViewModel,
turnId: string,
phase: string
): boolean {
if (phase !== "settled") return false;
const activeTurn = detail.session.activeTurn;
if (activeTurn?.turnId === turnId && activeTurn.phase !== "settled") {
return false;
}
return (
detail.showProcessingIndicator !== true ||
detail.turns.at(-1)?.id !== turnId
);
}
export function projectAgentTurnSummaryRowForTurn(
turn: WorkspaceAgentSessionDetailTurn,
fileChanges: Record<string, unknown> | null,
options: AgentTurnSummaryProjectionOptions = {}
): AgentTurnSummaryRowVM[] {
const files = canonicalTurnFiles(turn.id, fileChanges, options);
if (files.length === 0) {
return [];
}
const visiblePaths = new Set(files.map((file) => file.path));
const candidatePatchBatches = patchBatchesFromCalls(
turnToolCallsForSummary(turn),
options
);
const coveredPaths = new Set(
candidatePatchBatches.flatMap((batch) =>
batch.changes.map((change) => change.path)
)
);
const hasCompletePatchCoverage =
candidatePatchBatches.length > 0 &&
candidatePatchBatches.every((batch) =>
batch.changes.every((change) => visiblePaths.has(change.path))
) &&
files.every((file) => coveredPaths.has(file.path));
const patchBatches = hasCompletePatchCoverage ? candidatePatchBatches : [];
const createdCount = files.filter(
(file) => file.changeType === "created"
).length;
return [
{
kind: "turn-summary",
id: `turn-summary:${turn.id}`,
turnId: turn.id,
files,
...(patchBatches.length > 0 ? { patchBatches } : {}),
fileCount: files.length,
modifiedCount: files.length - createdCount,
createdCount,
occurredAtUnixMs: options.occurredAtUnixMs ?? null
}
];
}
function canonicalTurnFiles(
turnId: string,
fileChanges: Record<string, unknown> | null,
options: AgentTurnSummaryProjectionOptions
): AgentTurnSummaryFileVM[] {
const byPath = new Map<string, AgentTurnSummaryFileVM>();
for (const [index, value] of (
arrayValue(objectValue(fileChanges)?.files) ?? []
).entries()) {
const file = objectValue(value);
const path = normalizedFilePath(
firstNonEmptyString(
stringValue(file?.path),
stringValue(file?.filePath),
stringValue(file?.file_path)
),
options
);
if (!file || !path) {
continue;
}
const parts = splitFilePath(path);
const rawDiff = firstRawString(
file?.diff,
file?.patch,
file?.unifiedDiff,
file?.unified_diff
);
const unifiedDiff = firstValidUnifiedDiff(
file?.diff,
file?.patch,
file?.unifiedDiff,
file?.unified_diff
);
const explicitChangeType = normalizeChangeType(fileChangeTypeValue(file));
let oldString = firstPresentString(
literalStringValue(file.oldString),
literalStringValue(file.old_string)
);
let newString = firstPresentString(
literalStringValue(file.newString),
literalStringValue(file.new_string)
);
let content = literalStringValue(file.content);
const changeType =
explicitChangeType ??
(unifiedDiff ? inferAgentPatchChangeType(unifiedDiff) : "modified");
if (unifiedDiff === null && rawDiff !== null) {
if (changeType === "created") {
content ??= rawDiff;
newString ??= rawDiff;
} else if (changeType === "deleted") {
oldString ??= rawDiff;
newString ??= "";
content = null;
} else if (oldString === null && newString === null && content === null) {
content = rawDiff;
}
}
byPath.set(path, {
label: path,
path,
fileName: parts.fileName,
directory: parts.directory,
changeType,
toolName: null,
messageId: `turn-summary:${turnId}:file:${index + 1}`,
unifiedDiff,
oldString,
newString,
content,
occurredAtUnixMs: options.occurredAtUnixMs ?? null
});
}
return applyShortestUniqueFileLabels([...byPath.values()]);
}
function turnToolCallsForSummary(
turn: WorkspaceAgentSessionDetailTurn
): WorkspaceAgentSessionDetailToolCall[] {
const callsById = new Map<string, WorkspaceAgentSessionDetailToolCall>();
for (const call of turn.toolCalls) {
callsById.set(call.id, call);
}
for (const item of turn.agentItems) {
if (item.kind !== "tool-calls") {
continue;
}
for (const call of item.toolCalls) {
callsById.set(call.id, call);
}
for (const entry of item.groupEntries ?? []) {
if (entry.kind === "tool-call") {
callsById.set(entry.call.id, entry.call);
}
}
}
return [...callsById.values()];
}
function patchBatchesFromCalls(
calls: readonly WorkspaceAgentSessionDetailToolCall[],
options: AgentTurnSummaryProjectionOptions
): AgentTurnSummaryPatchBatchVM[] {
return calls.flatMap((call) => patchBatchesFromCall(call, options));
}
function patchBatchesFromCall(
call: WorkspaceAgentSessionDetailToolCall,
options: AgentTurnSummaryProjectionOptions
): AgentTurnSummaryPatchBatchVM[] {
const directBatch = isFailedToolStatus(call.statusKind ?? null)
? []
: patchBatchFromPayload(call.id, call.payload ?? null, null, null, options);
const output = objectValue(call.payload?.output);
const nestedBatches = nestedTaskStepsFromPayload(
call.payload,
output
).flatMap((value, index) => {
const step = objectValue(value);
if (
!step ||
isFailedToolStatus(
nestedTaskStepStatusKind(step, call.statusKind ?? null)
)
) {
return [];
}
return patchBatchFromPayload(
stringValue(step.toolUseId) ??
stringValue(step.id) ??
`${call.id}:step:${index + 1}`,
objectValue(step.payload),
objectValue(step.toolInput) ?? objectValue(step.tool_input),
objectValue(step.toolResult) ?? objectValue(step.tool_result),
options
);
});
return [...directBatch, ...nestedBatches];
}
function patchBatchFromPayload(
id: string,
payload: Record<string, unknown> | null,
toolInput: Record<string, unknown> | null,
toolOutput: Record<string, unknown> | null,
options: AgentTurnSummaryProjectionOptions
): AgentTurnSummaryPatchBatchVM[] {
const metadata = objectValue(payload?.metadata);
const input = toolInput ?? objectValue(payload?.input);
const output = toolOutput ?? objectValue(payload?.output);
const canonicalFileChanges = objectValue(payload?.fileChanges);
const changes = firstFileChangeValue(
canonicalFileChanges?.files,
output?.changes,
payload?.changes,
input?.changes
);
const sourcePatchChanges = patchChangesFromChangeMap(changes);
const patchChanges = sourcePatchChanges.flatMap((change) => {
const path = normalizedFilePath(change.path, options);
return path ? [{ ...change, path }] : [];
});
if (
patchChanges.length === 0 ||
patchChanges.length !== sourcePatchChanges.length
) {
return [];
}
return [
{
cwd:
firstNonEmptyString(
stringValue(payload?.cwd),
stringValue(input?.cwd),
stringValue(output?.cwd),
stringValue(metadata?.cwd),
options.defaultCwd ?? null
) ?? null,
toolCallId: id,
changes: patchChanges
}
];
}
function patchChangesFromChangeMap(
changes: unknown
): AgentTurnSummaryPatchChangeVM[] {
const entries = fileChangeEntriesFromChanges(changes);
const patchChanges = entries.flatMap((entry) => {
const change = entry.change;
const path = entry.path.trim();
if (!path) {
return [];
}
const changeType = normalizeChangeType(fileChangeTypeValue(change));
const rawDiff = firstRawString(
change.unified_diff,
change.unifiedDiff,
change.diff,
change.patch
);
const unifiedDiff = firstValidUnifiedDiff(
change.unified_diff,
change.unifiedDiff,
change.diff,
change.patch
);
let oldString = firstPresentString(
literalStringValue(change.old_string),
literalStringValue(change.oldString)
);
const explicitContent = literalStringValue(change.content);
let newString = firstPresentString(
literalStringValue(change.new_string),
literalStringValue(change.newString),
explicitContent
);
if (changeType === "created" && oldString === null && newString !== null) {
oldString = "";
}
if (changeType === "deleted" && oldString === null && newString !== null) {
oldString = newString;
newString = "";
}
if (changeType === "deleted" && newString === null && oldString !== null) {
newString = "";
}
const content = firstPresentString(
changeType === "deleted" ? null : explicitContent,
changeType === "created" ? (newString ?? rawDiff) : null
);
const resolvedChangeType =
changeType ??
(unifiedDiff ? inferAgentPatchChangeType(unifiedDiff) : "modified");
if (
resolvedChangeType === "modified" &&
!unifiedDiff &&
(oldString === null || newString === null)
) {
return [];
}
if (
!unifiedDiff &&
oldString === null &&
newString === null &&
content === null
) {
return [];
}
return [
{
path,
changeType: resolvedChangeType,
unifiedDiff,
oldString,
newString,
content
}
];
});
return patchChanges.length === entries.length ? patchChanges : [];
}
function firstRawString(...values: unknown[]): string | null {
for (const value of values) {
if (typeof value === "string") {
return value;
}
}
return null;
}
function firstValidUnifiedDiff(...values: unknown[]): string | null {
for (const value of values) {
if (typeof value === "string" && isAgentUnifiedDiffText(value)) {
return value;
}
}
return null;
}
@@ -0,0 +1,381 @@
import { describe, expect, it } from "vitest";
import {
normalizeAgentActivitySession,
type AgentActivityMessage,
type AgentActivitySession,
type AgentActivityTurn
} from "@tutti-os/agent-activity-core";
import {
buildChildSessionLanesByParentToolCallId,
deriveSubAgentNameFromTask
} from "./childSessionLanes";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
describe("buildChildSessionLanesByParentToolCallId", () => {
it("attaches a child session by its immutable parent tool call", () => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
title: "API reviewer",
turn: turn("child-1", "running", null)
});
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [
spawnCall("root-1", "spawn-1", "You are API reviewer.")
],
childSessions: [child],
messagesBySessionId: {
"child-1": [message("child-1", "Checking request validation", 20)]
}
});
expect(lanes.get("spawn-1")?.[0]).toMatchObject({
childSessionId: "child-1",
parentToolCallId: "spawn-1",
status: "running",
name: "API reviewer",
task: "You are API reviewer.",
latestActivity: "Checking request validation"
});
});
it("uses the child turn outcome and keeps nested children under their direct parent", () => {
const parent = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "settled", "completed")
});
const nested = childSession({
id: "child-2",
parentSessionId: "child-1",
parentToolCallId: "task-2",
turn: turn("child-2", "settled", "failed", "nested failed")
});
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Review the API")],
childSessions: [parent, nested],
messagesBySessionId: {
"child-1": [toolCallMessage("child-1", "task-2", 30)]
}
});
expect(lanes.get("spawn-1")?.[0]).toMatchObject({
childSessionId: "child-1",
status: "completed",
childSessions: [
{
childSessionId: "child-2",
parentToolCallId: "task-2",
status: "failed",
failureDetail: "nested failed"
}
]
});
});
it("preserves a completed child result as full Markdown", () => {
const markdown = `## Result\n\n[report](/workspace/report.pdf)\n\n${"detail ".repeat(40)}`;
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "settled", "completed")
});
const lane = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Prepare report")],
childSessions: [child],
messagesBySessionId: { "child-1": [message("child-1", markdown, 30)] }
}).get("spawn-1")?.[0];
expect(lane?.assistantMarkdown).toBe(markdown);
expect(lane?.latestActivity).not.toBe(markdown);
});
it.each([
["running", turn("child-1", "running", null)],
["completed", turn("child-1", "settled", "completed")]
] as const)(
"preserves the complete assistant Markdown while %s",
(_label, childTurn) => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: childTurn
});
const markdown = `Important opening context ${"detail ".repeat(24)}[PDF](C:/Reports/final%20report.pdf)`;
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Build report")],
childSessions: [child],
messagesBySessionId: {
"child-1": [message("child-1", markdown, 20)]
}
});
expect(lanes.get("spawn-1")?.[0]?.assistantMarkdown).toBe(markdown);
expect(lanes.get("spawn-1")?.[0]?.latestActivity).toHaveLength(141);
}
);
it("preserves leading indentation and surrounding blank lines in assistant Markdown", () => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "settled", "completed")
});
const markdown = "\n console.log('preserved')\n\n";
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Build report")],
childSessions: [child],
messagesBySessionId: {
"child-1": [message("child-1", markdown, 20)]
}
});
expect(lanes.get("spawn-1")?.[0]?.assistantMarkdown).toBe(markdown);
});
it("uses bounded activity only before an assistant message exists", () => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "running", null)
});
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Build report")],
childSessions: [child],
messagesBySessionId: {
"child-1": [toolCallMessage("child-1", "inspect-1", 20)]
}
});
expect(lanes.get("spawn-1")?.[0]?.latestActivity).toBe("Agent");
expect(lanes.get("spawn-1")?.[0]?.assistantMarkdown).toBeNull();
});
it("does not replace assistant Markdown with a later status notice", () => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "settled", "failed", "provider failed")
});
const assistant = message("child-1", "Partial **report**", 20);
const notice: AgentActivityMessage = {
...message("child-1", "Connection failed", 30),
messageId: "child-1-error",
kind: "error"
};
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Build report")],
childSessions: [child],
messagesBySessionId: { "child-1": [assistant, notice] }
});
expect(lanes.get("spawn-1")?.[0]?.assistantMarkdown).toBe(
"Partial **report**"
);
expect(lanes.get("spawn-1")?.[0]?.failureDetail).toBe("provider failed");
});
it("does not replace assistant Markdown with a later plan issue annotation", () => {
const child = childSession({
id: "child-1",
parentSessionId: "root-1",
parentToolCallId: "spawn-1",
turn: turn("child-1", "running", null)
});
const assistant = message("child-1", "Current **report**", 20);
const annotation: AgentActivityMessage = {
...message("child-1", "[Issue](mention://workspace-issue/issue-1)", 30),
messageId: "plan-issue:issue-1",
kind: "session_audit"
};
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Build report")],
childSessions: [child],
messagesBySessionId: { "child-1": [assistant, annotation] }
});
expect(lanes.get("spawn-1")?.[0]?.assistantMarkdown).toBe(
"Current **report**"
);
});
it("does not reconstruct legacy owner fields without a child session", () => {
const legacyItem: WorkspaceAgentActivityTimelineItem = {
id: 2,
eventId: "legacy-child-message",
seq: 2,
agentSessionId: "root-1",
actorType: "agent",
actorId: "root-1",
itemType: "message.assistant",
role: "assistant",
payload: {
text: "legacy child output",
ownerThreadId: "legacy-child",
ownerCallId: "spawn-1"
}
};
const lanes = buildChildSessionLanesByParentToolCallId({
rootSession: rootSession(),
rootTimelineItems: [spawnCall("root-1", "spawn-1", "Review"), legacyItem],
childSessions: [],
messagesBySessionId: {}
});
expect(lanes.size).toBe(0);
});
});
describe("deriveSubAgentNameFromTask", () => {
it("uses only an explicit self-addressed opening", () => {
expect(
deriveSubAgentNameFromTask("You are API reviewer. Check routes")
).toBe("API reviewer");
expect(deriveSubAgentNameFromTask("Check the API routes")).toBeNull();
});
});
function rootSession(): AgentActivitySession {
return normalizeAgentActivitySession({
workspaceId: "workspace-1",
agentSessionId: "root-1",
kind: "root",
provider: "codex",
cwd: "/workspace",
title: "Root",
activeTurnId: "root-turn-1",
activeTurn: turn("root-1", "running", null, null, "root-turn-1"),
latestTurn: turn("root-1", "running", null, null, "root-turn-1"),
latestTurnInteractions: [],
pendingInteractions: []
});
}
function childSession(input: {
id: string;
parentSessionId: string;
parentToolCallId: string;
title?: string;
turn: AgentActivityTurn;
}): AgentActivitySession {
return normalizeAgentActivitySession({
workspaceId: "workspace-1",
agentSessionId: input.id,
kind: "child",
rootAgentSessionId: "root-1",
rootTurnId: "root-turn-1",
parentAgentSessionId: input.parentSessionId,
parentTurnId:
input.parentSessionId === "root-1" ? "root-turn-1" : "child-turn-1",
parentToolCallId: input.parentToolCallId,
provider: "codex",
cwd: "/workspace",
title: input.title ?? "",
activeTurnId: input.turn.phase === "settled" ? null : input.turn.turnId,
activeTurn: input.turn.phase === "settled" ? null : input.turn,
latestTurn: input.turn,
latestTurnInteractions: [],
pendingInteractions: [],
createdAtUnixMs: 10,
updatedAtUnixMs: input.turn.updatedAtUnixMs
});
}
function turn(
agentSessionId: string,
phase: AgentActivityTurn["phase"],
outcome: AgentActivityTurn["outcome"],
errorMessage: string | null = null,
turnId = agentSessionId === "child-2" ? "child-turn-2" : "child-turn-1"
): AgentActivityTurn {
return {
agentSessionId,
turnId,
origin: "user_prompt",
phase,
outcome,
error: errorMessage ? { message: errorMessage } : null,
startedAtUnixMs: 10,
updatedAtUnixMs: 40,
settledAtUnixMs: phase === "settled" ? 40 : null
};
}
function message(
agentSessionId: string,
text: string,
occurredAtUnixMs: number
): AgentActivityMessage {
return {
workspaceId: "workspace-1",
agentSessionId,
messageId: `${agentSessionId}-message`,
version: 1,
turnId: `${agentSessionId}-turn`,
role: "assistant",
kind: "text",
payload: { text },
occurredAtUnixMs
};
}
function toolCallMessage(
agentSessionId: string,
callId: string,
occurredAtUnixMs: number
): AgentActivityMessage {
return {
workspaceId: "workspace-1",
agentSessionId,
messageId: callId,
version: 1,
turnId: "child-turn-1",
role: "assistant",
kind: "tool_call",
status: "running",
payload: {
callId,
toolName: "Task",
input: { task: "Inspect nested behavior" }
},
occurredAtUnixMs
};
}
function spawnCall(
agentSessionId: string,
callId: string,
task: string
): WorkspaceAgentActivityTimelineItem {
return {
id: 1,
eventId: `${callId}-started`,
seq: 1,
agentSessionId,
actorType: "agent",
actorId: agentSessionId,
itemType: "call.started",
role: "assistant",
callType: "subagent",
callId,
name: "Task",
status: "running",
payload: { callId, toolName: "Task", input: { task } },
occurredAtUnixMs: 10
};
}
@@ -0,0 +1,452 @@
import type {
AgentActivityMessage,
AgentActivitySession
} from "@tutti-os/agent-activity-core";
import type {
AgentTaskSubAgentActivityVM,
AgentTaskSubAgentStatus,
AgentTaskSubAgentVM
} from "../contracts/agentTaskItemVM";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import type { AgentToolCallVM } from "../contracts/agentToolCallVM";
import type { AgentToolGroupRowVM } from "../contracts/agentToolGroupRowVM";
import { projectWorkspaceAgentMessagesToTimelineItems } from "./workspaceAgentMessageProjection";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import {
isWorkspaceAgentToolCallItem,
resolveWorkspaceAgentToolName
} from "../../workspaceAgentToolCallDisplay";
export interface BuildChildSessionLanesInput {
rootSession: AgentActivitySession;
rootTimelineItems: readonly WorkspaceAgentActivityTimelineItem[];
childSessions: readonly AgentActivitySession[];
messagesBySessionId: Readonly<
Record<string, readonly AgentActivityMessage[] | undefined>
>;
}
export function buildChildSessionLanesByParentToolCallId(
input: BuildChildSessionLanesInput
): ReadonlyMap<string, AgentTaskSubAgentVM[]> {
const rootSessionId = input.rootSession.agentSessionId.trim();
const childrenByParentSessionId = new Map<string, AgentActivitySession[]>();
for (const childSession of input.childSessions) {
if (
childSession.kind !== "child" ||
childSession.rootAgentSessionId !== rootSessionId ||
!childSession.parentAgentSessionId?.trim() ||
!childSession.parentToolCallId?.trim()
) {
continue;
}
const parentSessionId = childSession.parentAgentSessionId.trim();
const siblings = childrenByParentSessionId.get(parentSessionId) ?? [];
siblings.push(childSession);
childrenByParentSessionId.set(parentSessionId, siblings);
}
for (const siblings of childrenByParentSessionId.values()) {
siblings.sort(compareChildSessions);
}
const lanesByParentToolCallId = new Map<string, AgentTaskSubAgentVM[]>();
const directChildren = childrenByParentSessionId.get(rootSessionId) ?? [];
const visited = new Set<string>();
for (const childSession of directChildren) {
const parentToolCallId = childSession.parentToolCallId?.trim();
if (!parentToolCallId) continue;
const lanes = lanesByParentToolCallId.get(parentToolCallId) ?? [];
lanes.push(
buildChildSessionLane({
childSession,
childrenByParentSessionId,
messagesBySessionId: input.messagesBySessionId,
parentTimelineItems: input.rootTimelineItems,
visited
})
);
lanesByParentToolCallId.set(parentToolCallId, lanes);
}
for (const lanes of lanesByParentToolCallId.values()) {
assignLanePositions(lanes);
}
return lanesByParentToolCallId;
}
export function attachChildSessionLanesToConversationVM(
conversation: AgentConversationVM | null,
lanesByParentToolCallId: ReadonlyMap<string, AgentTaskSubAgentVM[]>
): AgentConversationVM | null {
if (!conversation || lanesByParentToolCallId.size === 0) {
return conversation;
}
let changed = false;
const rows = conversation.rows.map((row) => {
if (row.kind !== "tool-group") return row;
const nextRow = toolGroupRowWithChildSessions(row, lanesByParentToolCallId);
if (nextRow !== row) changed = true;
return nextRow;
});
return changed ? { ...conversation, rows } : conversation;
}
export function deriveSubAgentNameFromTask(task: string | null): string | null {
if (!task) return null;
const firstSentence = task
.trim()
.split(/[。..!?!?,,\n]/, 1)[0]
?.trim();
if (!firstSentence) return null;
const selfAddress = /^(你现在是|你現在是|你是|you are|act as)\s*/i;
if (!selfAddress.test(firstSentence)) return null;
const stripped = firstSentence
.replace(selfAddress, "")
.replace(/\s+/g, " ")
.trim();
return stripped.length >= 2 && stripped.length <= 36 ? stripped : null;
}
function buildChildSessionLane(input: {
childSession: AgentActivitySession;
childrenByParentSessionId: ReadonlyMap<string, AgentActivitySession[]>;
messagesBySessionId: BuildChildSessionLanesInput["messagesBySessionId"];
parentTimelineItems: readonly WorkspaceAgentActivityTimelineItem[];
visited: Set<string>;
}): AgentTaskSubAgentVM {
const childSessionId = input.childSession.agentSessionId.trim();
if (input.visited.has(childSessionId)) {
return emptyCycleLane(input.childSession);
}
input.visited.add(childSessionId);
const childMessages = input.messagesBySessionId[childSessionId] ?? [];
const childTimelineItems =
projectWorkspaceAgentMessagesToTimelineItems(childMessages);
const parentToolCallId = input.childSession.parentToolCallId?.trim() ?? "";
const parentCall = parentToolCall(
input.parentTimelineItems,
parentToolCallId
);
const task = parentCall?.task ?? null;
const childSessions = (
input.childrenByParentSessionId.get(childSessionId) ?? []
).map((nestedChild) =>
buildChildSessionLane({
childSession: nestedChild,
childrenByParentSessionId: input.childrenByParentSessionId,
messagesBySessionId: input.messagesBySessionId,
parentTimelineItems: childTimelineItems,
visited: input.visited
})
);
assignSiblingLanePositions(childSessions);
input.visited.delete(childSessionId);
const activity = childSessionActivityLog(childTimelineItems);
const latestActivity = activity.entries.at(-1) ?? null;
const latestMessageAtUnixMs = childMessages.reduce(
(latest, message) => Math.max(latest, message.occurredAtUnixMs),
0
);
const latestTurn = input.childSession.latestTurn;
const status = childSessionStatus(input.childSession);
const assistantMarkdown = childSessionAssistantMarkdown(
childTimelineItems,
childMessages
);
const terminalAtUnixMs =
status === "running"
? null
: (latestTurn?.settledAtUnixMs ?? input.childSession.endedAtUnixMs);
return {
childSessionId,
parentToolCallId,
status,
name:
normalizedString(input.childSession.title) ??
deriveSubAgentNameFromTask(task),
task,
laneIndex: 1,
laneCount: 1,
latestActivity: latestActivity?.text ?? null,
latestActivityKind: latestActivity?.kind ?? null,
assistantMarkdown,
activityLog: activity.entries,
activityOmittedCount: activity.omittedCount,
queued: input.childSession.activeTurn?.phase === "submitted",
failureDetail:
status === "failed" ? (latestTurn?.error?.message?.trim() ?? null) : null,
startedAtUnixMs:
input.childSession.activeTurn?.startedAtUnixMs ??
latestTurn?.startedAtUnixMs ??
input.childSession.createdAtUnixMs,
latestActivityAtUnixMs: Math.max(
latestMessageAtUnixMs,
latestTurn?.updatedAtUnixMs ?? 0,
input.childSession.updatedAtUnixMs
),
terminalAtUnixMs,
childSessions
};
}
function emptyCycleLane(session: AgentActivitySession): AgentTaskSubAgentVM {
return {
childSessionId: session.agentSessionId,
parentToolCallId: session.parentToolCallId ?? "",
status: childSessionStatus(session),
name: normalizedString(session.title),
task: null,
laneIndex: 1,
laneCount: 1,
latestActivity: null,
latestActivityKind: null,
assistantMarkdown: null,
activityLog: [],
activityOmittedCount: 0,
failureDetail: session.latestTurn?.error?.message?.trim() ?? null,
startedAtUnixMs: session.createdAtUnixMs,
latestActivityAtUnixMs: session.updatedAtUnixMs,
terminalAtUnixMs:
session.latestTurn?.settledAtUnixMs ?? session.endedAtUnixMs,
childSessions: []
};
}
function childSessionStatus(
session: AgentActivitySession
): AgentTaskSubAgentStatus {
const activeTurn = session.activeTurn;
if (activeTurn && activeTurn.phase !== "settled") return "running";
const latestTurn = session.latestTurn;
if (!latestTurn || latestTurn.phase !== "settled") return "running";
switch (latestTurn.outcome) {
case "failed":
return "failed";
case "canceled":
case "interrupted":
return "canceled";
case "completed":
default:
return "completed";
}
}
function parentToolCall(
timelineItems: readonly WorkspaceAgentActivityTimelineItem[],
parentToolCallId: string
): { task: string | null } | null {
if (!parentToolCallId) return null;
for (const item of timelineItems) {
if (!isWorkspaceAgentToolCallItem(item)) continue;
const callId = firstString(item.callId, stringValue(item.payload?.callId));
if (callId !== parentToolCallId) continue;
const input = recordValue(item.payload?.input);
return {
task: firstString(
stringValue(input?.task),
stringValue(input?.prompt),
stringValue(input?.description)
)
};
}
return null;
}
function toolGroupRowWithChildSessions(
row: AgentToolGroupRowVM,
lanesByParentToolCallId: ReadonlyMap<string, AgentTaskSubAgentVM[]>
): AgentToolGroupRowVM {
let changed = false;
const callsById = new Map<string, AgentToolCallVM>();
const calls = row.calls.map((call) => {
const lanes = call.task
? lanesByParentToolCallId.get(toolCallRawId(call.id))
: null;
if (!lanes?.length || !call.task) return call;
changed = true;
const nextCall: AgentToolCallVM = {
...call,
task: { ...call.task, subAgents: lanes }
};
callsById.set(nextCall.id, nextCall);
return nextCall;
});
if (!changed) return row;
const entries = row.entries.map((entry) => {
if (entry.kind !== "tool-call") return entry;
const nextCall = callsById.get(entry.call.id);
return nextCall ? { ...entry, call: nextCall } : entry;
});
return { ...row, calls, entries };
}
function toolCallRawId(id: string): string {
return id.startsWith("call:") ? id.slice("call:".length) : id;
}
const CHILD_ACTIVITY_LOG_CAP = 20;
function childSessionActivityLog(
timelineItems: readonly WorkspaceAgentActivityTimelineItem[]
): { entries: AgentTaskSubAgentActivityVM[]; omittedCount: number } {
const entries = timelineItems
.map(displayableActivityEntry)
.filter((entry): entry is AgentTaskSubAgentActivityVM => entry !== null);
const omittedCount = Math.max(0, entries.length - CHILD_ACTIVITY_LOG_CAP);
return { entries: entries.slice(omittedCount), omittedCount };
}
function displayableActivityEntry(
item: WorkspaceAgentActivityTimelineItem
): AgentTaskSubAgentActivityVM | null {
const atUnixMs = timelineItemTime(item) || null;
if (isWorkspaceAgentToolCallItem(item)) {
const name = firstString(
resolveWorkspaceAgentToolName(item),
item.name,
stringValue(item.payload?.name)
);
return name ? { kind: "tool", text: name, atUnixMs } : null;
}
const text = snippet(timelineItemText(item));
if (!text) return null;
const itemType = item.itemType?.trim().toLowerCase() ?? "";
const role = item.role?.trim().toLowerCase() ?? "";
return itemType === "message.assistant_thinking" ||
role === "assistant_thinking"
? { kind: "reasoning", text, atUnixMs }
: { kind: "message", text, atUnixMs };
}
function timelineItemText(item: WorkspaceAgentActivityTimelineItem): string {
return (
stringValue(item.payload?.text) ??
stringValue(item.payload?.content) ??
stringValue(item.content) ??
""
)
.replace(/\s+/g, " ")
.trim();
}
function childSessionAssistantMarkdown(
timelineItems: readonly WorkspaceAgentActivityTimelineItem[],
messages: readonly AgentActivityMessage[]
): string | null {
const assistantTextMessageIds = new Set(
messages
.filter((message) => {
const kind = message.kind.trim().toLowerCase();
const role = message.role.trim().toLowerCase();
const payloadKind =
typeof message.payload?.kind === "string"
? message.payload.kind.trim().toLowerCase()
: "";
return (
kind === "text" &&
(role === "assistant" || role === "agent") &&
message.semantics?.noticeCommand !== "compact" &&
message.payload?.noticeCommand !== "compact" &&
payloadKind !== "agent_system_notice" &&
payloadKind !== "agent_visible_error"
);
})
.map((message) => message.messageId.trim())
.filter(Boolean)
);
for (let index = timelineItems.length - 1; index >= 0; index -= 1) {
const item = timelineItems[index];
if (!item) continue;
const itemType = item.itemType?.trim().toLowerCase() ?? "";
const role = item.role?.trim().toLowerCase() ?? "";
const payloadKind =
typeof item.payload?.kind === "string"
? item.payload.kind.trim().toLowerCase()
: "";
if (
role !== "assistant" ||
itemType !== "message.assistant" ||
!assistantTextMessageIds.has(item.eventId.trim()) ||
typeof item.payload?.noticeKind === "string" ||
payloadKind === "agent_visible_error" ||
payloadKind === "agent_system_notice"
) {
continue;
}
const markdown =
markdownStringValue(item.payload?.text) ??
markdownStringValue(item.payload?.content) ??
markdownStringValue(item.content);
if (markdown) return markdown;
}
return null;
}
function snippet(text: string): string {
return text.length <= 140
? text
: String.fromCodePoint(0x2026) + text.slice(-140);
}
function assignSiblingLanePositions(lanes: AgentTaskSubAgentVM[]): void {
const lanesByCallId = new Map<string, AgentTaskSubAgentVM[]>();
for (const lane of lanes) {
const siblings = lanesByCallId.get(lane.parentToolCallId) ?? [];
siblings.push(lane);
lanesByCallId.set(lane.parentToolCallId, siblings);
}
for (const siblings of lanesByCallId.values()) assignLanePositions(siblings);
}
function assignLanePositions(lanes: AgentTaskSubAgentVM[]): void {
for (let index = 0; index < lanes.length; index += 1) {
const lane = lanes[index];
if (!lane) continue;
lane.laneIndex = index + 1;
lane.laneCount = lanes.length;
}
}
function compareChildSessions(
left: AgentActivitySession,
right: AgentActivitySession
): number {
return (
left.createdAtUnixMs - right.createdAtUnixMs ||
left.agentSessionId.localeCompare(right.agentSessionId)
);
}
function timelineItemTime(
item: WorkspaceAgentActivityTimelineItem | undefined
): number {
return item?.occurredAtUnixMs ?? item?.createdAtUnixMs ?? 0;
}
function normalizedString(value: string | null | undefined): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function stringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
function markdownStringValue(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value : null;
}
function recordValue(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: null;
}
function firstString(
...values: Array<string | null | undefined>
): string | null {
for (const value of values) {
const normalized = normalizedString(value);
if (normalized) return normalized;
}
return null;
}
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { chunkBy } from "./chunkBy";
describe("chunkBy", () => {
const sameParity = (a: number, b: number) => a % 2 === b % 2;
const cases: {
name: string;
items: number[];
expected: number[][];
}[] = [
{ name: "empty input yields no runs", items: [], expected: [] },
{ name: "single item is one run", items: [1], expected: [[1]] },
{
name: "consecutive matches coalesce",
items: [1, 3, 5],
expected: [[1, 3, 5]]
},
{
name: "a mismatch starts a new run",
items: [1, 2],
expected: [[1], [2]]
},
{
name: "runs break and resume on parity flips",
items: [1, 3, 2, 4, 5],
expected: [[1, 3], [2, 4], [5]]
},
{
name: "alternating values are all singletons",
items: [1, 2, 3, 4],
expected: [[1], [2], [3], [4]]
}
];
for (const { name, items, expected } of cases) {
it(name, () => {
expect(chunkBy(items, sameParity)).toEqual(expected);
});
}
it("never drops or duplicates elements (partition property)", () => {
const items = [4, 4, 7, 9, 2, 2, 2, 5];
const runs = chunkBy(items, sameParity);
expect(runs.flat()).toEqual(items);
});
it("only ever compares the run's last element with the next item", () => {
const seen: [number, number][] = [];
chunkBy([10, 20, 30], (previous, current) => {
seen.push([previous, current]);
return true;
});
expect(seen).toEqual([
[10, 20],
[20, 30]
]);
});
});
@@ -0,0 +1,26 @@
/**
* Split a flat list into consecutive runs. A new run starts whenever
* `sameRun(previousItem, currentItem)` returns false. Total function: every
* input element lands in exactly one run, runs preserve order, and an empty
* input yields an empty result. No element is ever dropped or duplicated.
*
* This is the segmentation primitive behind neighbour-dependent projections
* (e.g. coalescing thinking into the message it precedes). Keeping it generic
* and pure means the grouping decision lives entirely in the `sameRun`
* predicate, which is trivially table-testable on its own.
*/
export function chunkBy<T>(
items: readonly T[],
sameRun: (previous: T, current: T) => boolean
): T[][] {
const runs: T[][] = [];
for (const item of items) {
const current = runs.at(-1);
if (current && sameRun(current.at(-1)!, item)) {
current.push(item);
continue;
}
runs.push([item]);
}
return runs;
}
@@ -0,0 +1,41 @@
import { useMemo, useRef } from "react";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import type { WorkspaceAgentSessionDetailViewModel } from "../../workspaceAgentSessionDetailViewModel";
import {
projectAgentConversationVM,
reconcileProjectedAgentConversationVM
} from "./agentConversationProjection";
export function useProjectedAgentConversation({
conversation,
detail,
avoidGroupingEdits = false
}: {
conversation?: AgentConversationVM | null;
detail?: WorkspaceAgentSessionDetailViewModel | null;
avoidGroupingEdits?: boolean;
}): AgentConversationVM | null {
const previousConversationRef = useRef<AgentConversationVM | null>(null);
return useMemo(() => {
if (!conversation && !detail) {
previousConversationRef.current = null;
return null;
}
const nextConversation =
conversation ??
projectAgentConversationVM(
detail as WorkspaceAgentSessionDetailViewModel,
{
avoidGroupingEdits
}
);
const reconciledConversation = reconcileProjectedAgentConversationVM(
previousConversationRef.current,
nextConversation
);
previousConversationRef.current = reconciledConversation;
return reconciledConversation;
}, [avoidGroupingEdits, conversation, detail]);
}
@@ -0,0 +1,695 @@
import type {
AgentActivityMessage,
AgentActivitySnapshot,
AgentActivityTurn
} from "@tutti-os/agent-activity-core";
import { isWorkspaceAgentActivityOptimisticMessage } from "../../workspaceAgentMessageOverlay";
import { buildWorkspaceAgentActivityListViewModel } from "../../workspaceAgentActivityListViewModel";
import type { BuildWorkspaceAgentSessionDetailInput } from "../../workspaceAgentSessionDetailViewModel";
import { buildCanonicalWorkspaceAgentDetailView } from "../../workspaceAgentTimelineCanonical";
import { resolveWorkspaceAgentNoticeCommandSemantics } from "../../workspaceAgentSystemNoticeSemantics";
import { isTuttiPlanIssueLinkMessageId } from "../tuttiModePlanIssueLinkMarker";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import {
projectAgentConversationVM,
type AgentConversationProjectionOptions
} from "./agentConversationProjection";
export interface ProjectWorkspaceAgentMessagesInput extends Omit<
BuildWorkspaceAgentSessionDetailInput,
"timelineItems"
> {
messages: AgentActivityMessage[];
}
export interface ProjectAgentActivitySessionConversationInput {
activitySnapshot: AgentActivitySnapshot;
agentSessionId: string;
sessionTurns?: readonly AgentActivityTurn[];
workspaceRoot?: string | null;
}
export function projectAgentActivitySessionToConversationVM({
activitySnapshot,
agentSessionId,
sessionTurns,
workspaceRoot
}: ProjectAgentActivitySessionConversationInput): AgentConversationVM | null {
const session =
activitySnapshot.sessions.find(
(candidate) => candidate.agentSessionId === agentSessionId
) ?? null;
if (!session) return null;
const messages = activitySnapshot.sessionMessagesById[agentSessionId] ?? [];
const activity =
buildWorkspaceAgentActivityListViewModel(activitySnapshot, {
sessionMessagesById: activitySnapshot.sessionMessagesById
}).activities.find(
(candidate) => candidate.sessionId === session.agentSessionId
) ?? null;
if (!activity) return null;
return projectWorkspaceAgentMessagesToConversationVM({
activity,
messages,
session,
sessionTurns,
workspaceRoot
});
}
export function projectWorkspaceAgentMessagesToConversationVM(
input: ProjectWorkspaceAgentMessagesInput,
options: AgentConversationProjectionOptions = {}
): AgentConversationVM {
const { messages, ...detailInput } = input;
const timelineItems = projectWorkspaceAgentMessagesToTimelineItems(messages);
const detail = buildCanonicalWorkspaceAgentDetailView({
...detailInput,
sessionTurns: detailInput.sessionTurns?.filter(
(turn) => turn.agentSessionId === detailInput.session.agentSessionId
),
timelineItems
});
return projectAgentConversationVM(detail, options);
}
const tuttiPlanIssueDispatchTriggerPrefix = "issue:tutti-mode-plan-";
/**
* Per-run delegate cards for tutti-plan Issue dispatch stay out of the
* timeline: the embedded plan-issue panel carries that state per task, and a
* duplicate card per run reads as unrelated noise. Collaboration records from
* any other source keep their cards.
*/
function isTuttiPlanIssueDispatchCollaboration(
message: AgentActivityMessage
): boolean {
if (message.kind?.trim() !== "collaboration") {
return false;
}
const triggerReason = message.payload?.triggerReason;
return (
typeof triggerReason === "string" &&
triggerReason.startsWith(tuttiPlanIssueDispatchTriggerPrefix)
);
}
export function projectWorkspaceAgentMessagesToTimelineItems(
messages: readonly AgentActivityMessage[]
): WorkspaceAgentActivityTimelineItem[] {
const sortedMessages = latestMessageSnapshots(messages)
.filter((message) => !isTuttiPlanIssueDispatchCollaboration(message))
.sort(compareMessagesByDisplayOrder);
const mergedToolPayloadByKey = new Map<string, Record<string, unknown>>();
return sortedMessages.map((message, index) => {
const kind = normalizeToken(message.kind);
const role = normalizeToken(message.role);
const payload = normalizedPayload(message.payload);
const goalControlAudit = isGoalControlAudit(message);
const id = normalizedMessageId(message.version, index);
const seq = index + 1;
const eventId = goalControlAudit
? firstNonEmptyString(
stringValue(payload.messageId),
message.messageId,
`message:${id}`
)
: message.messageId.trim() || `message:${id}`;
const turnId = message.turnId?.trim() || undefined;
const occurredAtUnixMs = messageDisplayOrderTime(message);
if (goalControlAudit) {
return messageTimelineItem({
message,
id,
seq,
eventId,
actorType: "user",
itemType: "goal.control",
role: "user",
content: messageText(message),
occurredAtUnixMs
});
}
if (kind === "tool_call") {
const callId = firstNonEmptyString(
messagePayloadString(message, "callId"),
message.messageId
);
const title = messagePayloadString(message, "title");
const toolKey = callId || eventId;
const payloadToolName = displayToolNameCandidate(
stringValue(payload.toolName),
callId
);
const titleToolName = displayToolNameCandidate(title, callId);
const toolName = firstNonEmptyString(payloadToolName, titleToolName);
const toolPayload = sanitizedToolPayload(payload, callId);
const mergedPayload = mergePayload(mergedToolPayloadByKey.get(toolKey), {
...toolPayload,
...(toolName ? { toolName } : {}),
...(message.status?.trim() ? { status: message.status.trim() } : {})
});
mergedToolPayloadByKey.set(toolKey, mergedPayload);
const callType =
firstNonEmptyString(stringValue(mergedPayload.callType)) || "tool";
const workspaceId = workspaceIdFromMessage(message);
return {
id,
...workspaceTimelineFields(workspaceId),
agentSessionId: message.agentSessionId,
seq,
...(turnId ? { turnId } : {}),
eventId,
actorType: "agent",
actorId: message.agentSessionId,
itemType: toolCallItemType(message.status ?? undefined),
role: "assistant",
callType,
callId,
name: firstNonEmptyString(toolName, titleToolName) || "Tool",
...(message.status !== undefined ? { status: message.status } : {}),
payload: mergedPayload,
...(occurredAtUnixMs !== undefined ? { occurredAtUnixMs } : {}),
...(message.startedAtUnixMs !== undefined
? { createdAtUnixMs: message.startedAtUnixMs }
: {})
};
}
if (kind === "collaboration") {
// Collaboration runs (model consult/fork/delegate/handoff) are durable
// assistant-side messages the daemon updates in place by messageId
// ("collab:<runId>"). Keep the full payload so the canonical detail view
// can project the typed collaboration card even while resultText is
// still empty (running consult).
return messageTimelineItem({
message,
id,
seq,
eventId,
turnId,
actorType: "agent",
itemType: "collaboration",
role: "assistant",
content: messagePayloadString(message, "resultText") ?? "",
occurredAtUnixMs
});
}
if (kind === "reasoning") {
return messageTimelineItem({
message,
id,
seq,
eventId,
turnId,
actorType: "agent",
itemType: "message.assistant_thinking",
role: "assistant_thinking",
content: messageText(message),
occurredAtUnixMs
});
}
if ((kind === "text" || kind === "session_audit") && role === "user") {
return messageTimelineItem({
message,
id,
seq,
eventId,
turnId,
actorType: "user",
itemType: "message.user",
role: "user",
content: messageText(message),
occurredAtUnixMs
});
}
// The durable plan→Issue reverse link (daemon ReportIssuePlanningLink) is
// a session-level annotation: kind "session_audit", assistant role,
// messageId "plan-issue:<issueID>". Keyed on that stable identity — never
// the prose — it projects as a normal assistant message so the
// workspace-issue mention renders through the standard chip pipeline
// instead of the notice/error fallback below. The daemon deliberately
// writes no TurnID, so the messageId doubles as a stable synthetic turn
// that keeps the row standalone.
if (
kind === "session_audit" &&
(role === "assistant" || role === "agent") &&
isTuttiPlanIssueLinkMessageId(message.messageId)
) {
return messageTimelineItem({
message,
id,
seq,
eventId,
turnId: turnId ?? eventId,
actorType: "agent",
itemType: "message.assistant",
role: "assistant",
content: messageText(message),
occurredAtUnixMs
});
}
if (kind === "text" && (role === "assistant" || role === "agent")) {
const projectedMessage = normalizeLegacyCompactNotice(message, payload);
return messageTimelineItem({
message: projectedMessage,
id,
seq,
eventId,
turnId,
actorType: "agent",
itemType: "message.assistant",
role: "assistant",
content: messageText(projectedMessage),
occurredAtUnixMs
});
}
const visibleError =
kind === "error" ||
normalizeToken(stringValue(payload.kind)) === "agent_visible_error";
const statusTurnId =
turnId ?? `session-status:${visibleError ? "error" : "notice"}`;
const statusMessage: AgentActivityMessage = {
...message,
payload: visibleError
? {
...payload,
detail: firstNonEmptyString(
stringValue(payload.detail),
messageText(message)
),
kind: "agent_visible_error"
}
: {
...payload,
detail: messageText(message),
kind: "agent_system_notice",
noticeKind: kind,
severity: "info"
}
};
return messageTimelineItem({
message: statusMessage,
id,
seq,
eventId,
turnId: statusTurnId,
actorType: role === "user" ? "user" : "agent",
itemType: role === "user" ? "message.user" : "message.assistant",
role: role === "user" ? "user" : "assistant",
content: statusMessageText(statusMessage),
occurredAtUnixMs
});
});
}
function isGoalControlAudit(message: AgentActivityMessage): boolean {
return (
normalizeToken(message.kind) === "session_audit" &&
normalizedPayload(message.payload).goalControl === true
);
}
function normalizeLegacyCompactNotice(
message: AgentActivityMessage,
payload: Record<string, unknown>
): AgentActivityMessage {
const commandSemantics = resolveWorkspaceAgentNoticeCommandSemantics({
eventId: message.messageId,
messageSemantics: message.semantics,
payload,
status: message.status
});
if (commandSemantics?.command !== "compact") {
return message;
}
const commandStatus = commandSemantics.commandStatus;
const title =
stringValue(payload.title) ||
(commandStatus === "completed"
? "Context compacted."
: commandStatus === "running"
? "Compacting context."
: "Context compaction interrupted.");
const originalText = messageText(message);
const detail =
stringValue(payload.detail) ||
(commandStatus === "failed" || commandStatus === "canceled"
? originalText.replace(/^Compacting failed:\s*/iu, "").trim()
: "");
return {
...message,
semantics: {
...message.semantics,
noticeCommand: "compact",
noticeCommandStatus: commandStatus
},
payload: {
...payload,
kind: "agent_system_notice",
noticeKind: stringValue(payload.noticeKind) || "system_notice",
noticeCommand: "compact",
noticeCommandStatus: commandStatus,
title,
text: title,
content: title,
...(detail ? { detail } : {})
}
};
}
function latestMessageSnapshots(
messages: readonly AgentActivityMessage[]
): AgentActivityMessage[] {
const latestByKey = new Map<string, AgentActivityMessage>();
const unkeyedMessages: AgentActivityMessage[] = [];
for (const message of messages) {
const key = messageSnapshotKey(message);
if (!key) {
unkeyedMessages.push(message);
continue;
}
const previous = latestByKey.get(key);
if (!previous || (message.version ?? 0) >= (previous.version ?? 0)) {
latestByKey.set(key, mergeMessageSnapshot(previous, message));
} else {
latestByKey.set(key, mergeMessageSnapshot(message, previous));
}
}
return [...unkeyedMessages, ...latestByKey.values()];
}
function mergeMessageSnapshot(
previous: AgentActivityMessage | undefined,
next: AgentActivityMessage
): AgentActivityMessage {
const semantics =
previous?.semantics || next.semantics
? { ...previous?.semantics, ...next.semantics }
: undefined;
return {
...previous,
...next,
sequence: next.sequence ?? previous?.sequence,
createdAtUnixMs: next.createdAtUnixMs ?? previous?.createdAtUnixMs,
...(semantics ? { semantics } : {}),
payload: {
...(previous?.payload ?? {}),
...(next.payload ?? {})
}
};
}
function messageSnapshotKey(message: AgentActivityMessage): string | null {
const messageId = message.messageId.trim();
if (!messageId) {
return null;
}
return `${message.agentSessionId.trim()}\u0000${messageId}`;
}
function messageTimelineItem({
message,
id,
seq,
eventId,
turnId,
actorType,
itemType,
role,
content,
occurredAtUnixMs
}: {
message: AgentActivityMessage;
id: number;
seq: number;
eventId: string;
turnId?: string;
actorType: string;
itemType: string;
role: string;
content: string;
occurredAtUnixMs?: number;
}): WorkspaceAgentActivityTimelineItem {
const workspaceId = workspaceIdFromMessage(message);
return {
id,
...workspaceTimelineFields(workspaceId),
agentSessionId: message.agentSessionId,
seq,
...(turnId ? { turnId } : {}),
eventId,
actorType,
actorId: actorType === "user" ? "user" : message.agentSessionId,
itemType,
role,
status: message.status,
...(message.semantics ? { messageSemantics: message.semantics } : {}),
content,
payload: normalizedPayload(message.payload),
...(occurredAtUnixMs !== undefined ? { occurredAtUnixMs } : {}),
...(message.startedAtUnixMs !== undefined
? { createdAtUnixMs: message.startedAtUnixMs }
: {})
};
}
function workspaceIdFromMessage(message: AgentActivityMessage): string {
return message.workspaceId?.trim() || "";
}
function workspaceTimelineFields(
workspaceId: string
): Pick<WorkspaceAgentActivityTimelineItem, "workspaceId"> {
return {
workspaceId
};
}
function compareMessagesByDisplayOrder(
left: AgentActivityMessage,
right: AgentActivityMessage
): number {
const leftOptimistic = isWorkspaceAgentActivityOptimisticMessage(left);
const rightOptimistic = isWorkspaceAgentActivityOptimisticMessage(right);
if (leftOptimistic !== rightOptimistic) {
return leftOptimistic ? 1 : -1;
}
// Durable sequence is assigned once when the message is first stored and is
// not changed by later streaming snapshots. Timestamps are compatibility
// fallbacks for messages produced by older runtimes.
const leftSequence = normalizedPositiveNumber(left.sequence);
const rightSequence = normalizedPositiveNumber(right.sequence);
if (leftSequence > 0 && rightSequence > 0 && leftSequence !== rightSequence) {
return leftSequence - rightSequence;
}
const leftTime = messageDisplayOrderTime(left);
const rightTime = messageDisplayOrderTime(right);
if (leftTime > 0 && rightTime > 0 && leftTime !== rightTime) {
return leftTime - rightTime;
}
const leftVersion = normalizedPositiveNumber(left.version);
const rightVersion = normalizedPositiveNumber(right.version);
if (leftVersion > 0 && rightVersion > 0 && leftVersion !== rightVersion) {
return leftVersion - rightVersion;
}
// Sorting opaque message ids would manufacture chronology and can move a
// user prompt behind the assistant output it initiated.
return 0;
}
function normalizedMessageId(id: number | undefined, index: number): number {
const normalizedId = typeof id === "number" ? id : 0;
return Number.isFinite(normalizedId) && normalizedId > 0
? normalizedId
: index + 1;
}
function normalizedPositiveNumber(value: number | undefined): number {
return typeof value === "number" && Number.isFinite(value) && value > 0
? value
: 0;
}
function messageDisplayOrderTime(message: AgentActivityMessage): number {
return (
normalizedPositiveNumber(message.startedAtUnixMs) ||
normalizedPositiveNumber(message.createdAtUnixMs) ||
normalizedPositiveNumber(message.occurredAtUnixMs) ||
normalizedPositiveNumber(message.completedAtUnixMs)
);
}
function toolCallItemType(status: string | undefined): string {
switch (normalizeToken(status)) {
case "running":
case "working":
case "active":
return "call.started";
case "completed":
case "complete":
case "done":
case "success":
case "succeeded":
return "call.completed";
case "failed":
case "error":
return "call.failed";
case "canceled":
return "call.canceled";
default:
return "call";
}
}
function messageText(message: AgentActivityMessage): string {
const payload = normalizedPayload(message.payload);
const title = messagePayloadString(message, "title");
return firstNonEmptyMessageText(
rawNonEmptyString(payload.displayPrompt),
rawNonEmptyString(payload.text),
rawNonEmptyString(payload.content),
rawNonEmptyString(payload.message),
rawNonEmptyString(payload.body),
title
);
}
function statusMessageText(message: AgentActivityMessage): string {
const title = messagePayloadString(message, "title") ?? "";
const text = messageText(message);
if (title && text && title !== text) {
return `${title}\n\n${text}`;
}
return title || text;
}
function messagePayloadString(
message: AgentActivityMessage,
key: string
): string | undefined {
return stringValue(normalizedPayload(message.payload)[key]);
}
function mergePayload(
previous: Record<string, unknown> | undefined,
next: Record<string, unknown>
): Record<string, unknown> {
if (!previous) {
return next;
}
const merged = { ...previous, ...next };
for (const key of ["input", "output", "error", "metadata"]) {
if (isRecord(previous[key]) || isRecord(next[key])) {
merged[key] = {
...(isRecord(previous[key]) ? previous[key] : {}),
...(isRecord(next[key]) ? next[key] : {})
};
}
}
return merged;
}
function normalizedPayload(
payload: Record<string, unknown> | undefined
): Record<string, unknown> {
return payload && typeof payload === "object" && !Array.isArray(payload)
? payload
: {};
}
function sanitizedToolPayload(
payload: Record<string, unknown>,
callId: string | undefined
): Record<string, unknown> {
if (!isOpaqueCallIdentifierString(stringValue(payload.toolName), callId)) {
return payload;
}
const { toolName: _toolName, ...rest } = payload;
return rest;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function stringValue(value: unknown): string {
return typeof value === "string" && value.trim() ? value.trim() : "";
}
function rawNonEmptyString(value: unknown): string {
return typeof value === "string" && value.trim() ? value : "";
}
function firstNonEmptyMessageText(
...values: Array<string | undefined | null>
): string {
for (const value of values) {
if (typeof value === "string" && value.trim()) {
return value;
}
}
return "";
}
function firstNonEmptyString(
...values: Array<string | undefined | null>
): string {
for (const value of values) {
if (typeof value === "string" && value.trim()) {
return value.trim();
}
}
return "";
}
function displayToolNameCandidate(
value: string | undefined,
callId: string | undefined
): string {
const trimmed = value?.trim() ?? "";
if (!trimmed || isOpaqueCallIdentifierString(trimmed, callId)) {
return "";
}
return trimmed;
}
function isOpaqueCallIdentifierString(
value: string,
callId: string | undefined
): boolean {
const trimmed = value.trim();
if (!trimmed) {
return false;
}
if (callId?.trim() && trimmed === callId.trim()) {
return true;
}
const lower = trimmed.toLowerCase();
if (lower.startsWith("call_")) {
return isOpaqueIdentifierTail(trimmed.slice("call_".length));
}
if (lower.startsWith("ws_")) {
return isOpaqueIdentifierTail(trimmed.slice("ws_".length));
}
return false;
}
function isOpaqueIdentifierTail(value: string): boolean {
return value.length >= 12 && /^[a-z0-9]+$/i.test(value);
}
function normalizeToken(value: string | undefined): string {
return value?.trim().toLowerCase() ?? "";
}
@@ -0,0 +1,786 @@
import { describe, expect, it } from "vitest";
import {
normalizeAgentActivitySession,
type AgentActivitySession
} from "@tutti-os/agent-activity-core";
import type { WorkspaceAgentActivityTimelineItem } from "../../workspaceAgentTimelineTypes";
import type { WorkspaceAgentActivityCard } from "../../workspaceAgentActivityListViewModel";
import { buildWorkspaceAgentSessionDetailViewModel } from "../../workspaceAgentSessionDetailViewModel";
import {
buildCanonicalWorkspaceAgentDetailView,
projectWorkspaceAgentTimelineToConversationVM
} from "./workspaceAgentTimelineProjection";
describe("projectWorkspaceAgentTimelineToConversationVM", () => {
it("groups adjacent tool calls and bridge thinking directly from timeline items", () => {
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
timelineItems: timelineItems()
});
expect(conversation.rows.map((row) => row.kind)).toEqual([
"message",
"message",
"tool-group",
"tool-group"
]);
const groupedRows = conversation.rows.filter(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "tool-group" }
> => row.kind === "tool-group" && row.grouped
);
expect(groupedRows).toHaveLength(1);
expect(groupedRows[0]?.entries.map((entry) => entry.kind)).toEqual([
"tool-call",
"thinking",
"tool-call"
]);
expect(groupedRows[0]?.entries[1]?.kind).toBe("thinking");
expect(
groupedRows[0]?.entries[1]?.kind === "thinking"
? groupedRows[0].entries[1].thinking.body
: null
).toBe("Need to inspect before editing.");
expect("pendingApproval" in conversation).toBe(false);
expect("pendingInteractivePrompt" in conversation).toBe(false);
const summaryRow = conversation.rows.find(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "turn-summary" }
> => row.kind === "turn-summary"
);
expect(summaryRow).toBeUndefined();
});
it("builds canonical detail turns directly from timeline items without the legacy detail builder", () => {
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: session({ effectiveStatus: "working", turnPhase: "working" }),
workspaceRoot: "/workspace/demo",
timelineItems: timelineItems()
});
expect(detail.turns).toHaveLength(1);
expect(detail.turns[0]?.rawAgentItems?.map((item) => item.kind)).toEqual([
"message",
"tool-calls",
"thinking",
"tool-calls",
"tool-calls",
"tool-calls"
]);
expect(detail.turns[0]?.agentItems.map((item) => item.kind)).toEqual([
"message",
"tool-calls",
"thinking",
"tool-calls",
"tool-calls",
"tool-calls"
]);
expect(detail.showProcessingIndicator).toBe(false);
});
it("omits Claude synthetic interrupt messages from left detail conversation rows", () => {
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: session({
provider: "claude-code",
title: "[Request interrupted by user]"
}),
workspaceRoot: "/workspace/demo",
timelineItems: [
{
...timelineItems()[0]!,
content: "[Request interrupted by user]"
},
{
...timelineItems()[0]!,
id: 11,
eventId: "event-11",
content: "[Request interrupted by user for tool use]",
occurredAtUnixMs: 11,
createdAtUnixMs: 11
},
{
...timelineItems()[0]!,
id: 12,
eventId: "event-12",
content: "继续正常请求",
occurredAtUnixMs: 12,
createdAtUnixMs: 12
},
timelineItems()[1]!
]
});
const userMessages = conversation.rows
.filter(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "message" }
> => row.kind === "message" && row.speaker === "user"
)
.flatMap((row) => row.messages.map((message) => message.body));
expect(userMessages).toEqual(["继续正常请求"]);
});
it("prefers durable sequence order over drifted timestamps", () => {
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
timelineItems: timelineItems().map((item) => ({
...item,
occurredAtUnixMs:
item.seq === 3
? 300
: item.seq === 4
? 40
: item.seq === 5
? 50
: item.seq,
createdAtUnixMs:
item.seq === 3
? 300
: item.seq === 4
? 40
: item.seq === 5
? 50
: item.seq
}))
});
expect(conversation.rows.map((row) => row.kind)).toEqual([
"message",
"message",
"tool-group",
"tool-group"
]);
});
it("keeps the legacy detail builder aligned with the canonical timeline projection helper", () => {
const input = {
activity: activity(),
session: session({ effectiveStatus: "working", turnPhase: "working" }),
workspaceRoot: "/workspace/demo",
timelineItems: timelineItems()
};
const canonical = buildCanonicalWorkspaceAgentDetailView(input);
const legacy = buildWorkspaceAgentSessionDetailViewModel(input);
expect(legacy).toEqual(canonical);
});
it("respects avoidGroupingEdits when rebuilding rows directly from timeline items", () => {
const conversation = projectWorkspaceAgentTimelineToConversationVM(
{
activity: activity(),
session: session({
effectiveStatus: "completed",
turnPhase: "completed"
}),
workspaceRoot: "/workspace/demo",
timelineItems: timelineItems()
},
{ avoidGroupingEdits: true }
);
const groupedRows = conversation.rows.filter(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "tool-group" }
> => row.kind === "tool-group" && row.grouped
);
expect(groupedRows).toHaveLength(1);
expect(groupedRows[0]?.calls.map((call) => call.id)).toEqual([
"call:read-1"
]);
expect(
conversation.rows.some(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "message" }
> =>
row.kind === "message" &&
row.speaker === "assistant" &&
row.thinking.some(
(thinking) => thinking.body === "Need to inspect before editing."
)
)
).toBe(true);
});
it("projects transport notices without merging them into assistant content", () => {
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
timelineItems: [
timelineItems()[0]!,
{
id: 98,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 98,
eventId: "notice:event-98",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
status: "completed",
payload: {
kind: "agent_system_notice",
noticeKind: "transport_retry",
severity: "warning",
title: "Codex connection interrupted. Reconnecting...",
detail:
"ResponseStreamDisconnected: websocket IO error: Broken pipe",
retryable: true,
content: "Codex connection interrupted. Reconnecting...",
text: "Codex connection interrupted. Reconnecting..."
},
occurredAtUnixMs: 98,
createdAtUnixMs: 98
},
{
id: 99,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 99,
eventId: "event-99",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
status: "completed",
content: "Done.",
occurredAtUnixMs: 99,
createdAtUnixMs: 99
}
]
});
const assistantRows = conversation.rows.filter(
(
row
): row is Extract<
(typeof conversation.rows)[number],
{ kind: "message" }
> => row.kind === "message" && row.speaker === "assistant"
);
expect(assistantRows).toHaveLength(2);
expect(assistantRows[0]?.messages[0]?.systemNotice).toEqual({
noticeKind: "transport_retry",
severity: "warning",
title: "Codex connection interrupted. Reconnecting...",
detail: "ResponseStreamDisconnected: websocket IO error: Broken pipe",
retryable: true
});
expect(assistantRows[1]?.messages[0]?.body).toBe("Done.");
});
it("maps review-process thinking timeline items to assistant message rows", () => {
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: session(),
workspaceRoot: "/workspace/demo",
timelineItems: [
{
id: 1,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-review",
seq: 1,
eventId: "event-1",
actorType: "user",
actorId: "user-1",
itemType: "message.user",
role: "user",
content: "/review",
occurredAtUnixMs: 1,
createdAtUnixMs: 1
},
{
id: 2,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-review",
seq: 2,
eventId: "event-2",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant_thinking",
role: "assistant_thinking",
status: "completed",
content:
"**Considering workspace registration order**\n\nInspecting the auth flow.",
payload: { messageKind: "review-process" },
occurredAtUnixMs: 2,
createdAtUnixMs: 2
}
]
});
expect(detail.turns[0]?.agentItems).toEqual([
expect.objectContaining({
kind: "message",
message: expect.objectContaining({
body: "Inspecting the auth flow."
})
})
]);
});
it("does not append processing after a terminal assistant message even if the session patch is still working", () => {
const completedReplyTimelineItems: WorkspaceAgentActivityTimelineItem[] = [
timelineItems()[0]!,
{
id: 99,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 99,
eventId: "event-99",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
status: "completed",
content: "Done.",
occurredAtUnixMs: 99,
createdAtUnixMs: 99
}
];
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: session({
effectiveStatus: "working",
turnPhase: "working"
}),
workspaceRoot: "/workspace/demo",
timelineItems: completedReplyTimelineItems
});
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: session({
effectiveStatus: "working",
turnPhase: "working"
}),
workspaceRoot: "/workspace/demo",
timelineItems: completedReplyTimelineItems
});
expect(detail.showProcessingIndicator).toBe(false);
expect(conversation.rows.some((row) => row.kind === "processing")).toBe(
false
);
});
it("keeps processing after an interim assistant message while the turn lifecycle reports an active turn", () => {
const interimReplyTimelineItems: WorkspaceAgentActivityTimelineItem[] = [
timelineItems()[0]!,
{
id: 99,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 99,
eventId: "event-99",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
status: "completed",
content: "I will now dispatch the sub-agents.",
occurredAtUnixMs: 99,
createdAtUnixMs: 99
}
];
const workingSession = {
...session({
effectiveStatus: "working",
turnPhase: "working"
}),
activeTurn: activeTurn("running")
};
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: workingSession,
workspaceRoot: "/workspace/demo",
timelineItems: interimReplyTimelineItems
});
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: workingSession,
workspaceRoot: "/workspace/demo",
timelineItems: interimReplyTimelineItems
});
expect(detail.showProcessingIndicator).toBe(true);
expect(conversation.rows.some((row) => row.kind === "processing")).toBe(
true
);
});
it("keeps processing when session status is stale ready but turn lifecycle is still running", () => {
const completedToolTimelineItems = timelineItems().slice(0, 5);
const staleReadySession = {
...session({
effectiveStatus: "ready",
turnPhase: "idle"
}),
activeTurn: activeTurn("running")
};
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: staleReadySession,
workspaceRoot: "/workspace/demo",
timelineItems: completedToolTimelineItems
});
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: staleReadySession,
workspaceRoot: "/workspace/demo",
timelineItems: completedToolTimelineItems
});
expect(detail.showProcessingIndicator).toBe(true);
expect(conversation.rows.some((row) => row.kind === "processing")).toBe(
true
);
});
it("does not append processing after a terminal assistant message once the turn lifecycle is settling", () => {
const settlingReplyTimelineItems: WorkspaceAgentActivityTimelineItem[] = [
timelineItems()[0]!,
{
id: 99,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 99,
eventId: "event-99",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
status: "completed",
content: "Done.",
occurredAtUnixMs: 99,
createdAtUnixMs: 99
}
];
const settlingSession = {
...session({
effectiveStatus: "working",
turnPhase: "working"
}),
activeTurn: activeTurn("settled")
};
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: settlingSession,
workspaceRoot: "/workspace/demo",
timelineItems: settlingReplyTimelineItems
});
expect(detail.showProcessingIndicator).toBe(false);
});
it("keeps processing after settle until authoritative terminal transcript content arrives", () => {
const userOnlyTimelineItems: WorkspaceAgentActivityTimelineItem[] = [
timelineItems()[0]!
];
const settledWithoutFinal = {
...session({
effectiveStatus: "working",
turnPhase: "working"
}),
activeTurn: activeTurn("settled")
};
const detail = buildCanonicalWorkspaceAgentDetailView({
activity: activity(),
session: settledWithoutFinal,
workspaceRoot: "/workspace/demo",
timelineItems: userOnlyTimelineItems
});
const conversation = projectWorkspaceAgentTimelineToConversationVM({
activity: activity(),
session: settledWithoutFinal,
workspaceRoot: "/workspace/demo",
timelineItems: userOnlyTimelineItems
});
expect(detail.showProcessingIndicator).toBe(true);
expect(conversation.rows.some((row) => row.kind === "processing")).toBe(
true
);
});
});
function activity(
overrides: Partial<WorkspaceAgentActivityCard> = {}
): WorkspaceAgentActivityCard {
return {
id: "activity-1",
sessionId: "session-1",
agentName: "Codex",
agentProvider: "codex",
status: "working",
title: "Codex",
latestActivitySummary: "Working",
sortTimeUnixMs: 10,
changedFiles: [],
userId: "user-1",
userName: "Taylor",
userAvatarUrl: "",
...overrides
};
}
function session(
overrides: Partial<AgentActivitySession> & {
effectiveStatus?: string;
turnPhase?: string;
} = {}
): AgentActivitySession {
const {
effectiveStatus: _effectiveStatus,
turnPhase: _turnPhase,
...canonical
} = overrides;
return normalizeAgentActivitySession({
...{
activeTurnId: null,
latestTurnInteractions: [],
pendingInteractions: []
},
workspaceId: "workspace-1",
agentSessionId: "session-1",
userId: "user-1",
provider: "codex",
providerSessionId: "provider-session-1",
cwd: "/workspace/demo",
title: "Codex",
createdAtUnixMs: 1,
updatedAtUnixMs: 10,
latestTurn: {
agentSessionId: "session-1",
turnId: "turn-1",
phase: "settled",
origin: "user_prompt",
outcome: "completed",
startedAtUnixMs: 1,
settledAtUnixMs: 10,
updatedAtUnixMs: 10,
fileChanges: {
files: [
{
path: "/workspace/demo/src/App.tsx",
change: "modified"
}
]
}
},
...canonical
});
}
function activeTurn(phase: "running" | "settled") {
return {
agentSessionId: "session-1",
origin: "user_prompt" as const,
phase,
startedAtUnixMs: 1,
turnId: "turn-1",
updatedAtUnixMs: 10
};
}
function timelineItems(): WorkspaceAgentActivityTimelineItem[] {
return [
{
id: 1,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 1,
eventId: "event-1",
actorType: "user",
actorId: "user-1",
itemType: "message.user",
role: "user",
content: "Ship the patch",
occurredAtUnixMs: 1,
createdAtUnixMs: 1
},
{
id: 2,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 2,
eventId: "event-2",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant",
role: "assistant",
content: "On it",
occurredAtUnixMs: 2,
createdAtUnixMs: 2
},
{
id: 3,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 3,
eventId: "event-3",
actorType: "agent",
actorId: "codex",
itemType: "call.completed",
role: "assistant",
callType: "tool",
callId: "read-1",
name: "read_file",
status: "completed",
payload: {
tool_state: {
name: "read_file",
input: { path: "/workspace/demo/README.md" },
output: { text: "Read README.md" }
}
},
occurredAtUnixMs: 3,
createdAtUnixMs: 3
},
{
id: 4,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 4,
eventId: "event-4",
actorType: "agent",
actorId: "codex",
itemType: "message.assistant_thinking",
role: "assistant_thinking",
content: "Need to inspect before editing.",
occurredAtUnixMs: 4,
createdAtUnixMs: 4
},
{
id: 5,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 5,
eventId: "event-5",
actorType: "agent",
actorId: "codex",
itemType: "call.completed",
role: "assistant",
callType: "tool",
callId: "edit-1",
name: "edit_file",
status: "completed",
payload: {
tool_state: {
name: "edit_file",
input: {
file_path: "/workspace/demo/src/App.tsx",
old_string: "old",
new_string: "new"
},
output: {}
}
},
occurredAtUnixMs: 5,
createdAtUnixMs: 5
},
{
id: 6,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 6,
eventId: "event-6",
actorType: "agent",
actorId: "codex",
itemType: "approval.requested",
role: "assistant",
callType: "approval",
callId: "approval-1",
name: "Approval",
status: "waiting_approval",
payload: {
input: {
requestId: "approval-request-1",
options: [
{ id: "allow_once", label: "Allow once", kind: "allow_once" }
]
}
},
occurredAtUnixMs: 6,
createdAtUnixMs: 6
},
{
id: 7,
workspaceId: "room-1",
agentSessionId: "session-1",
turnId: "turn-1",
seq: 7,
eventId: "event-7",
actorType: "agent",
actorId: "codex",
itemType: "interactive.requested",
role: "assistant",
callType: "interactive",
callId: "ask-1",
name: "AskUserQuestion",
status: "waiting_input",
payload: {
input: {
requestId: "ask-request-1",
questions: [
{
id: "approach",
header: "Approach",
question: "Which direction should we take?",
options: [
{ label: "Use typed renderer", description: "Keep going" }
]
}
]
}
},
occurredAtUnixMs: 7,
createdAtUnixMs: 7
}
];
}
@@ -0,0 +1,18 @@
import type { BuildWorkspaceAgentSessionDetailInput } from "../../workspaceAgentSessionDetailViewModel";
import { buildCanonicalWorkspaceAgentDetailView } from "../../workspaceAgentTimelineCanonical";
import type { AgentConversationVM } from "../contracts/agentConversationVM";
import {
projectAgentConversationVM,
type AgentConversationProjectionOptions
} from "./agentConversationProjection";
export function projectWorkspaceAgentTimelineToConversationVM(
input: BuildWorkspaceAgentSessionDetailInput,
options: AgentConversationProjectionOptions = {}
): AgentConversationVM {
const detail = buildCanonicalWorkspaceAgentDetailView(input);
const conversation = projectAgentConversationVM(detail, options);
return conversation;
}
export { buildCanonicalWorkspaceAgentDetailView };