diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 9b8de7ea03cb7..c87b889ebdaf5 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -7384,6 +7384,139 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }), ); + it.effect("shells carry the latest tool action, from the list and from the projection", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const suffix = "shell-latest-action"; + const threadId = yield* addRolledBackRecoveryCandidate(suffix); + const runId = RunId.make(`run:${suffix}:live`); + const nodeId = NodeId.make(`node:${suffix}:live`); + const now = yield* DateTime.now; + yield* projectionStore.apply({ + id: EventId.make(`event:${suffix}:live-run`), + type: "run.created", + threadId, + runId, + nodeId, + driver, + providerInstanceId, + occurredAt: now, + payload: { + id: runId, + threadId, + ordinal: 2, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: MessageId.make(`message:${suffix}:live`), + rootNodeId: nodeId, + activeAttemptId: null, + status: "running", + requestedAt: now, + startedAt: now, + completedAt: null, + checkpointId: null, + contextHandoffId: null, + }, + }); + const base = { + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + status: "running" as const, + title: null, + completedAt: null, + }; + const addItem = ( + id: string, + ordinal: number, + item: + | { readonly type: "command_execution"; readonly input: string; readonly output?: string } + | { readonly type: "file_change"; readonly fileName: string; readonly diffStr?: string } + | { readonly type: "reasoning"; readonly text: string; readonly streaming: boolean }, + ) => + projectionStore.apply({ + id: EventId.make(`event:${suffix}:${id}`), + type: "turn-item.updated", + threadId, + runId, + nodeId, + driver, + occurredAt: now, + payload: { + ...base, + ...item, + id: TurnItemId.make(`item:${suffix}:${id}`), + ordinal, + startedAt: DateTime.add(now, { seconds: ordinal }), + updatedAt: DateTime.add(now, { seconds: ordinal + 30 }), + }, + }); + const latestActions = Effect.gen(function* () { + const listed = (yield* projectionStore.getShellSnapshot()).threads.find( + (thread) => thread.id === threadId, + ); + const projected = ProjectionStore.threadShellFromProjection( + yield* projectionStore.getThreadProjection(threadId), + ); + return [listed?.latestAction, projected.latestAction]; + }); + + // Only the rolled-back run's command so far. + assert.deepEqual(yield* latestActions, [null, null]); + + yield* addItem("command", 2, { + type: "command_execution", + input: "pnpm test", + output: "x".repeat(4096), + }); + const ranCommand = { + summary: "Ran command", + detail: "pnpm test", + at: DateTime.add(now, { seconds: 2 }), + }; + assert.deepEqual(yield* latestActions, [ranCommand, ranCommand]); + + yield* addItem("edit", 3, { + type: "file_change", + fileName: "src/auth/session.ts", + diffStr: "+".repeat(4096), + }); + const changedFile = { + summary: "Changed files", + detail: "src/auth/session.ts", + at: DateTime.add(now, { seconds: 3 }), + }; + assert.deepEqual(yield* latestActions, [changedFile, changedFile]); + + yield* addItem("thought", 4, { type: "reasoning", text: "Next, the tests", streaming: true }); + assert.deepEqual(yield* latestActions, [changedFile, changedFile]); + + const longCommand = `echo ${"a".repeat(300)}`; + yield* addItem("long", 5, { type: "command_execution", input: longCommand }); + const [listed] = yield* latestActions; + assert.lengthOf(listed?.detail ?? "", 120); + assert.isTrue(listed?.detail?.endsWith("…")); + + const { statements, tracer } = traceSqlStatements(); + yield* projectionStore.getShellSnapshot().pipe(Effect.withTracer(tracer)); + const statement = statements.find((query) => query.includes("AS latest_tool_payload_json")); + assert.isDefined(statement); + const plan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${statement}`, + )).map((row) => row.detail); + assert.isTrue( + plan.some((detail) => detail.includes("turn_items_latest_tool_idx (thread_id=?)")), + plan.join("\n"), + ); + }), + ); + it.effect("counts history inherited by fork shells, but not by side chats", () => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index e6707ccc0af6d..9d0941d02829d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -100,6 +100,7 @@ import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; +import { LATEST_ACTION_ITEM_TYPES, latestActionFromTurnItem } from "./latestAction.ts"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { readableSearchText } from "./messageSearchIndex.ts"; import { @@ -1072,6 +1073,7 @@ type ShellThreadRow = { readonly blocking_failure_payload_json: string | null; readonly pending_request_payload_json: string | null; readonly pending_secret_request_payload_json: string | null; + readonly latest_tool_payload_json: string | null; readonly pending_link_request_payload_json: string | null; readonly latest_user_message_at: string | null; readonly latest_user_authored_message_at: string | null; @@ -1574,6 +1576,27 @@ const linkCardStillAsks = ( latestUserAuthoredMessageAt === null || !DateTime.isGreaterThan(latestUserAuthoredMessageAt, item.startedAt ?? item.updatedAt); +function latestToolItem( + projection: OrchestrationV2ThreadProjection, +): OrchestrationV2TurnItem | null { + const rolledBack = new Set( + projection.runs.filter((run) => run.status === "rolled_back").map((run) => run.id), + ); + const types: ReadonlyArray = LATEST_ACTION_ITEM_TYPES; + let latest: OrchestrationV2TurnItem | null = null; + for (const item of projection.turnItems) { + if (!types.includes(item.type) || (item.runId !== null && rolledBack.has(item.runId))) continue; + if ( + latest === null || + item.ordinal > latest.ordinal || + (item.ordinal === latest.ordinal && item.id > latest.id) + ) { + latest = item; + } + } + return latest; +} + export function threadShellFromProjection( projection: OrchestrationV2ThreadProjection, ): OrchestrationV2ThreadShell { @@ -1709,6 +1732,7 @@ export function threadShellFromProjection( // Thread detail owns message bodies. Keeping them out of shell rows makes // initial hydration and streaming updates independent of transcript size. latestVisibleMessage: null, + latestAction: latestActionFromTurnItem(latestToolItem(projection)), latestUserMessageAt: latestUserMessage?.updatedAt ?? null, latestUserAuthoredMessageAt, hasActionableProposedPlan: projection.plans.some( @@ -1846,6 +1870,7 @@ type ShellThreadState = { readonly pendingBackgroundTasks: OrchestrationV2ThreadShell["pendingBackgroundTasks"]; readonly providerInstanceHistory: OrchestrationV2ThreadShell["providerInstanceHistory"]; readonly goal: OrchestrationV2ThreadShell["goal"]; + readonly latestAction: OrchestrationV2ThreadShell["latestAction"]; readonly itemCount: number; readonly runlessItemCount: number; readonly updatedAt: OrchestrationV2ThreadProjection["updatedAt"]; @@ -2004,6 +2029,7 @@ function shellFromState(input: { pendingRuntimeRequest: input.state.pendingRuntimeRequest, pendingGuestMessageCount: pendingGuestMessageCount(input.state.thread.guestShare), latestVisibleMessage: null, + latestAction: input.state.latestAction, latestUserMessageAt: input.state.latestUserMessageAt, latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt, hasActionableProposedPlan: input.state.hasActionableProposedPlan, @@ -6665,6 +6691,19 @@ export const layer: Layer.Layer = ORDER BY link.updated_at DESC, link.turn_item_id DESC LIMIT 1 ) AS pending_link_request_payload_json, + ( + -- Tool output and diffs can be megabytes; the label needs none of them. + SELECT json_remove(tool.payload_json, + '$.output', '$.diffStr', '$.oldStr', '$.newStr', '$.changes', '$.results') + FROM orchestration_v2_projection_turn_items tool + INDEXED BY orchestration_v2_projection_turn_items_latest_tool_idx + LEFT JOIN orchestration_v2_projection_runs tool_run ON tool_run.run_id = tool.run_id + WHERE tool.thread_id = t.thread_id + AND tool.type IN ('command_execution', 'file_change', 'file_search', 'web_search', 'dynamic_tool') + AND (tool.run_id IS NULL OR tool_run.status <> 'rolled_back') + ORDER BY tool.ordinal DESC, tool.turn_item_id DESC + LIMIT 1 + ) AS latest_tool_payload_json, ( SELECT message.updated_at FROM orchestration_v2_projection_messages message @@ -7187,6 +7226,12 @@ export const layer: Layer.Layer = pendingRuntimeRequest = waitingCard; } } + const latestToolItem = + row.latest_tool_payload_json === null + ? null + : yield* decodeTurnItemPayload(row.latest_tool_payload_json).pipe( + Effect.orElseSucceed(() => null), + ); let terminalFailureItem = row.terminal_failure_payload_json === null ? null @@ -7301,6 +7346,7 @@ export const layer: Layer.Layer = providerThreadsByThreadId.get(thread.id) ?? [], thread.activeProviderThreadId, ), + latestAction: latestActionFromTurnItem(latestToolItem), itemCount: shellItemCountsByThreadId.get(thread.id)?.itemCount ?? 0, runlessItemCount: shellItemCountsByThreadId.get(thread.id)?.runlessItemCount ?? 0, updatedAt: thread.updatedAt, diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.ts index 336f9b12f96bf..aa01ec9947f37 100644 --- a/apps/server/src/orchestration-v2/ShellStream.test.ts +++ b/apps/server/src/orchestration-v2/ShellStream.test.ts @@ -38,8 +38,11 @@ const emptyShellSnapshot = { } as OrchestrationV2ShellSnapshot; describe("subagent shell events", () => { - const stored = (threadId: string, type: string) => - ({ event: { threadId, type } }) as ApplicationStoredEvent; + const stored = ( + threadId: string, + type: string, + payload: object = { type: "assistant_message", status: "running" }, + ) => ({ event: { threadId, type, payload } }) as ApplicationStoredEvent; it("keeps regular threads and subagent state changes while omitting subagent transcript updates", () => { const subagents = new Set(["child"]); @@ -60,6 +63,16 @@ describe("subagent shell events", () => { ); }); + it("refreshes a subagent's latest action when one of its tools finishes", () => { + const subagents = new Set(["child"]); + const tool = (status: string) => + shouldPublishShellApplicationEvent( + stored("child", "turn-item.updated", { type: "command_execution", status }), + subagents, + ); + expect([tool("running"), tool("completed"), tool("failed")]).toEqual([false, true, true]); + }); + it("tracks subagents created after the subscription starts", () => { const subagents = new Set(); const created = { @@ -198,7 +211,13 @@ describe("omitIdleSubagentShells", () => { expect(omitted.threads.map((thread) => thread.id)).toEqual(["root"]); expect( shouldPublishShellApplicationEvent( - { event: { threadId: "idle", type: "turn-item.updated" } } as ApplicationStoredEvent, + { + event: { + threadId: "idle", + type: "turn-item.updated", + payload: { type: "reasoning", status: "running" }, + }, + } as ApplicationStoredEvent, omitted.subagentThreadIds, ), ).toBe(false); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 0fa5251a7ef73..3e9b74ebfb685 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -32,6 +32,7 @@ import type * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; import { bufferLatestLiveStream } from "./LiveStreamBudget.ts"; +import { LATEST_ACTION_ITEM_TYPES } from "./latestAction.ts"; import type { ActiveShellIndexEntry } from "./ProjectionStore.ts"; type ShellDelta = Extract; @@ -431,12 +432,18 @@ export function shouldPublishShellApplicationEvent( return !( subagentThreadIds.has(event.threadId) && (event.type === "node.updated" || - event.type === "turn-item.updated" || + (event.type === "turn-item.updated" && !changesChildShell(event.payload)) || event.type === "provider-turn.updated" || event.type === "message.updated") ); } +const LATEST_ACTION_TYPES: ReadonlySet = new Set(LATEST_ACTION_ITEM_TYPES); + +/** A finished tool moves the child's latest action; streaming tool output does not. */ +const changesChildShell = (item: { readonly type: string; readonly status: string }) => + LATEST_ACTION_TYPES.has(item.type) && item.status !== "running" && item.status !== "pending"; + /** Shell updates refetch an aggregate; drop transcript bodies before retaining an event. */ export function toShellApplicationEvent(stored: ApplicationStoredEvent): ShellApplicationEvent { return "aggregateKind" in stored diff --git a/apps/server/src/orchestration-v2/latestAction.test.ts b/apps/server/src/orchestration-v2/latestAction.test.ts new file mode 100644 index 0000000000000..06574b6f4f67d --- /dev/null +++ b/apps/server/src/orchestration-v2/latestAction.test.ts @@ -0,0 +1,79 @@ +import { + NodeId, + RunId, + ThreadId, + TurnItemId, + type OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; + +import { latestActionFromTurnItem } from "./latestAction.ts"; + +const at = DateTime.makeUnsafe("2026-11-10T10:00:00.000Z"); +const base = { + id: TurnItemId.make("item:latest-action"), + threadId: ThreadId.make("thread:latest-action"), + runId: RunId.make("run:latest-action"), + nodeId: NodeId.make("node:latest-action"), + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1, + status: "running", + title: null, + startedAt: at, + completedAt: null, + updatedAt: at, +} as const; + +describe("latestActionFromTurnItem", () => { + it.each([ + [{ type: "file_search", pattern: "useAuth" }, { summary: "Searched useAuth" }], + [{ type: "web_search", patterns: ["github oauth"] }, { summary: "Searched github oauth" }], + [ + { type: "dynamic_tool", toolName: "Read", input: { file_path: "src/auth/session.ts" } }, + { summary: "Read src/auth/session.ts" }, + ], + [ + { type: "dynamic_tool", toolName: "Grep", input: { pattern: "session", path: "src" } }, + { summary: "Searched session in src" }, + ], + [ + { type: "dynamic_tool", toolName: "t3_milestone", input: {} }, + { summary: "Marked a milestone" }, + ], + [ + { type: "dynamic_tool", toolName: "mcp__t3-code__request_secret", input: {} }, + { summary: "Asked for a secret" }, + ], + [ + { + type: "dynamic_tool", + toolName: "mcp__t3-code__delegate_task", + input: {}, + status: "failed", + }, + { summary: "Failed to delegate a child task" }, + ], + [ + { type: "dynamic_tool", toolName: "mcp__linear__create_issue", input: {} }, + { summary: "create_issue" }, + ], + [ + { + type: "dynamic_tool", + toolName: "mcp__linear__create_issue", + title: "mcp__linear__create_issue", + input: {}, + }, + { summary: "create_issue" }, + ], + [{ type: "reasoning", text: "Thinking", streaming: false }, null], + [{ type: "assistant_message", messageId: "message:x", text: "Done", streaming: false }, null], + ] as const)("labels %o", (item, expected) => { + const action = latestActionFromTurnItem({ ...base, ...item } as OrchestrationV2TurnItem); + expect(action).toEqual(expected === null ? null : { ...expected, at }); + }); +}); diff --git a/apps/server/src/orchestration-v2/latestAction.ts b/apps/server/src/orchestration-v2/latestAction.ts new file mode 100644 index 0000000000000..e6b345f0466f9 --- /dev/null +++ b/apps/server/src/orchestration-v2/latestAction.ts @@ -0,0 +1,91 @@ +import type { + OrchestrationV2LatestActionSummary, + OrchestrationV2TurnItem, +} from "@t3tools/contracts"; +import { + deriveToolActivityPresentation, + dynamicToolTitle, + type ToolActivityPresentation, +} from "@t3tools/shared/toolActivity"; +import { resolveT3McpToolDefinition } from "@t3tools/shared/t3McpToolPresentation"; + +/** Keep in sync with the latest-tool index and the shell row query in ProjectionStore. */ +export const LATEST_ACTION_ITEM_TYPES = [ + "command_execution", + "file_change", + "file_search", + "web_search", + "dynamic_tool", +] as const; + +const LATEST_ACTION_TEXT_LIMIT = 120; + +const clip = (text: string) => + text.length > LATEST_ACTION_TEXT_LIMIT + ? `${text.slice(0, LATEST_ACTION_TEXT_LIMIT - 1).trimEnd()}…` + : text; + +const withoutMcpPrefix = (name: string) => name.replace(/^mcp__.+?__(?=.)/, ""); + +function presentation(item: OrchestrationV2TurnItem): ToolActivityPresentation | null { + switch (item.type) { + case "command_execution": + return deriveToolActivityPresentation({ + itemType: "command_execution", + title: item.title, + data: { command: item.input }, + }); + case "file_change": + return deriveToolActivityPresentation({ + itemType: "file_change", + title: item.title, + data: { path: item.fileName }, + }); + case "file_search": + return deriveToolActivityPresentation({ + title: item.title, + data: { kind: "search", pattern: item.pattern }, + fallbackSummary: "Searched files", + }); + case "web_search": + return deriveToolActivityPresentation({ + itemType: "web_search", + title: item.title, + data: { query: item.patterns?.join(", ") }, + }); + case "dynamic_tool": { + const t3Tool = resolveT3McpToolDefinition(item.toolName, item.input); + if (t3Tool !== null) { + const [action, , completed, detail] = t3Tool.labels; + return { + summary: + item.status === "failed" + ? `Failed to ${action.toLowerCase()} ${detail}` + : `${completed} ${detail}`, + }; + } + const title = dynamicToolTitle(item.toolName, item.input, item.title) ?? item.title; + return deriveToolActivityPresentation({ + itemType: "dynamic_tool_call", + title: title && withoutMcpPrefix(title), + data: { toolName: item.toolName ?? undefined, input: item.input }, + fallbackSummary: item.toolName && withoutMcpPrefix(item.toolName), + }); + } + default: + return null; + } +} + +export function latestActionFromTurnItem( + item: OrchestrationV2TurnItem | null, +): OrchestrationV2LatestActionSummary | null { + if (item === null) return null; + const presented = presentation(item); + if (presented === null) return null; + return { + summary: clip(presented.summary), + ...(presented.detail ? { detail: clip(presented.detail) } : {}), + at: item.startedAt ?? item.updatedAt, + }; +} diff --git a/apps/server/src/persistence/ForkMigrations.test.ts b/apps/server/src/persistence/ForkMigrations.test.ts index 1ff1b636925fb..0b6ea5fb2239d 100644 --- a/apps/server/src/persistence/ForkMigrations.test.ts +++ b/apps/server/src/persistence/ForkMigrations.test.ts @@ -12,6 +12,7 @@ const forkHistory: Array = [ [1, "SandboxRecords"], [2, "SandboxPerThread"], [3, "ProjectionMilestones"], + [4, "LatestToolItemIndex"], ]; const history = (table: string) => diff --git a/apps/server/src/persistence/ForkMigrations.ts b/apps/server/src/persistence/ForkMigrations.ts index 849e5aed0cfda..fc7308ef69055 100644 --- a/apps/server/src/persistence/ForkMigrations.ts +++ b/apps/server/src/persistence/ForkMigrations.ts @@ -6,6 +6,7 @@ import { hasPendingMigrations, runMigrations, type RunMigrationsOptions } from " import Migration0001 from "./ForkMigrations/001_SandboxRecords.ts"; import Migration0002 from "./ForkMigrations/002_SandboxPerThread.ts"; import Migration0003 from "./ForkMigrations/003_ProjectionMilestones.ts"; +import Migration0004 from "./ForkMigrations/004_LatestToolItemIndex.ts"; // This fork's migrations keep their own history so upstream's numbered list stays identical to // upstream's and its future ids never collide with them. Add new fork migrations here only. @@ -13,6 +14,7 @@ const forkMigrationEntries = [ [1, "SandboxRecords", Migration0001], [2, "SandboxPerThread", Migration0002], [3, "ProjectionMilestones", Migration0003], + [4, "LatestToolItemIndex", Migration0004], ] as const; export const FORK_MIGRATIONS_TABLE = "t3_fork_migrations"; diff --git a/apps/server/src/persistence/ForkMigrations/004_LatestToolItemIndex.ts b/apps/server/src/persistence/ForkMigrations/004_LatestToolItemIndex.ts new file mode 100644 index 0000000000000..00f4dc96f3ac6 --- /dev/null +++ b/apps/server/src/persistence/ForkMigrations/004_LatestToolItemIndex.ts @@ -0,0 +1,13 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + // Keep this predicate aligned with the shell's latest tool action lookup in ProjectionStore. + yield* sql` + CREATE INDEX orchestration_v2_projection_turn_items_latest_tool_idx + ON orchestration_v2_projection_turn_items(thread_id, ordinal DESC, turn_item_id DESC) + WHERE type IN ('command_execution', 'file_change', 'file_search', 'web_search', 'dynamic_tool') + `; +}); diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 39607575627dd..d534b049274fc 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -574,7 +574,16 @@ describe("v2 thread shell lists", () => { const dispose = harness.registry.mount(quietAtom); try { const first = harness.registry.get(quietAtom); - setThread({ ...running, updatedAt: at(1), itemCount: 4, visibleItemCount: 3 }, 2); + setThread( + { + ...running, + updatedAt: at(1), + itemCount: 4, + visibleItemCount: 3, + latestAction: { summary: "Ran command", detail: "pnpm test", at: at(1) }, + }, + 2, + ); expect(harness.registry.get(quietAtom)).toBe(first); expect(harness.registry.get(harness.threads.threadShellAtom(ref))?.itemCount).toBe(4); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index f5ced761c5665..8b54db154c7ee 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -167,8 +167,8 @@ export function childThreadInputsTitle( const sameWireThreadShell = Schema.toEquivalence(OrchestrationV2ThreadShell); -// While a run streams, the server bumps the shell's timestamps, item counts and -// latest message several times a second. Only the zero crossing of the counts +// While a run streams, the server bumps the shell's timestamps, item counts, latest +// message and latest action several times a second. Only the zero crossing of the counts // says anything (whether the thread has started). Once the run stops every // field counts again, so snooze wakes and failure times read the current value. function sameApartFromStreaming( @@ -194,6 +194,8 @@ function sameApartFromStreaming( itemCount: after.itemCount, visibleItemCount: after.visibleItemCount, latestVisibleMessage: after.latestVisibleMessage, + // Optional on the wire: an explicit undefined would not equal an absent key. + ...("latestAction" in after ? { latestAction: after.latestAction } : {}), }, after, ) diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index db7178585b1bb..0b3009522b5cc 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2144,6 +2144,14 @@ export const OrchestrationV2LatestVisibleMessageSummary = Schema.Struct({ export type OrchestrationV2LatestVisibleMessageSummary = typeof OrchestrationV2LatestVisibleMessageSummary.Type; +/** The thread's most recent tool step, labeled as the chat's work log labels it. */ +export const OrchestrationV2LatestActionSummary = Schema.Struct({ + summary: Schema.String, + detail: Schema.optional(Schema.String), + at: Schema.DateTimeUtc, +}); +export type OrchestrationV2LatestActionSummary = typeof OrchestrationV2LatestActionSummary.Type; + export const OrchestrationV2ThreadShell = Schema.Struct({ ...OrchestrationV2CreationFields, id: ThreadId, @@ -2186,6 +2194,8 @@ export const OrchestrationV2ThreadShell = Schema.Struct({ /** Guest messages waiting for the owner to send or dismiss. Absent from older servers. */ pendingGuestMessageCount: Schema.optional(NonNegativeInt), latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummary), + /** Absent from older servers. */ + latestAction: Schema.optional(Schema.NullOr(OrchestrationV2LatestActionSummary)), latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtc), /** Excludes wakes and agent messages that advance latestUserMessageAt through the user role. */ latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)), @@ -2791,6 +2801,10 @@ export const OrchestrationV2LatestVisibleMessageSummaryJson = export type OrchestrationV2LatestVisibleMessageSummaryJson = typeof OrchestrationV2LatestVisibleMessageSummaryJson.Type; +export const OrchestrationV2LatestActionSummaryJson = OrchestrationV2LatestActionSummary.mapFields( + (fields) => ({ ...fields, at: Schema.DateTimeUtcFromString }), +); + export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFields((fields) => ({ ...fields, latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), @@ -2799,6 +2813,7 @@ export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFiel activityRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummaryJson), latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummaryJson), + latestAction: Schema.optional(Schema.NullOr(OrchestrationV2LatestActionSummaryJson)), latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtcFromString), latestUserAuthoredMessageAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)), createdAt: Schema.DateTimeUtcFromString,