Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
133 changes: 133 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
46 changes: 46 additions & 0 deletions apps/server/src/orchestration-v2/ProjectionStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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<string> = 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 {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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"];
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -6665,6 +6691,19 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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
Expand Down Expand Up @@ -7187,6 +7226,12 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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
Expand Down Expand Up @@ -7301,6 +7346,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
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,
Expand Down
25 changes: 22 additions & 3 deletions apps/server/src/orchestration-v2/ShellStream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"]);
Expand All @@ -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<string>();
const created = {
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 8 additions & 1 deletion apps/server/src/orchestration-v2/ShellStream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;
Expand Down Expand Up @@ -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<string> = 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
Expand Down
Loading
Loading