diff --git a/apps/server/src/cli/thread.test.ts b/apps/server/src/cli/thread.test.ts index eafda7f3e9b69..2a76dc73056d0 100644 --- a/apps/server/src/cli/thread.test.ts +++ b/apps/server/src/cli/thread.test.ts @@ -27,6 +27,7 @@ import { latestRunError, launchModelSelection, readLatestMessages, + ThreadToolFailedError, readOutputSchema, resolveProject, threadCommand, @@ -316,7 +317,12 @@ it.effect("--wait follows the sent run to its continuation's terminal status", ( /** The reads that ask whether a run after `runId` holds a message someone sent. */ const laterRunReads = ( laterRun: RunId, - items: ReadonlyArray<{ readonly runId: RunId; readonly type: string }>, + items: ReadonlyArray<{ + readonly runId: RunId; + readonly type: string; + readonly position?: number; + }>, + earlierPosition: number | null = null, ) => [ { recentRuns: [ @@ -324,7 +330,7 @@ const laterRunReads = ( { runId: laterRun, ordinal: 2 }, ], }, - { thread: {}, items, nextPosition: null, hasMore: false }, + { thread: {}, items, nextPosition: null, hasMore: false, earlierPosition }, ]; it.effect("--wait lasts until background work the agent waits on wakes it and that run ends", () => @@ -378,7 +384,7 @@ it.effect( { runId: wakeRun, ordinal: 2, status }, ], }, - { thread: {}, items: [], nextPosition: null, hasMore: false }, + { thread: {}, items: [], nextPosition: null, hasMore: false, earlierPosition: null }, ]; const { tools } = scriptedTools({ t3_thread_wait: [ @@ -425,7 +431,7 @@ it.effect( () => Effect.gen(function* () { const sentRun = RunId.make("run-2"); - const { tools } = scriptedTools({ + const { tools, calls } = scriptedTools({ t3_thread_wait: [ { threadId, runId, status: "completed", timedOut: false }, { @@ -437,7 +443,12 @@ it.effect( output: { head: "abc" }, }, ], - t3_thread_read: laterRunReads(sentRun, [{ runId: sentRun, type: "user_message" }]), + // Older pages remain, but the newest already holds the sent message. + t3_thread_read: laterRunReads( + sentRun, + [{ runId: sentRun, type: "user_message", position: 9 }], + 5, + ), }); assert.deepStrictEqual(yield* waitForRun(tools, threadId, runId, true), { @@ -446,6 +457,12 @@ it.effect( status: "completed", output: { head: "abc" }, }); + assert.deepStrictEqual( + calls + .filter((entry) => entry.tool === "t3_thread_read") + .map((entry) => (entry.args as { readonly beforePosition?: number }).beforePosition), + [undefined, Number.MAX_SAFE_INTEGER], + ); }), ); @@ -540,16 +557,48 @@ it.effect("--output-schema reads a ~/ path from the home directory", () => }).pipe(Effect.provide(NodeServices.layer)), ); -/** Serves t3_thread_read pages the way the server does: positions count every item, and a cursorless read is the newest page. */ -const timelineTools = (types: ReadonlyArray) => { +/** + * Serves t3_thread_read pages the way the server does: positions count every + * item, and a cursorless read is the newest page. A legacy server's strict + * schema refuses `beforePosition`. + */ +const timelineTools = (types: ReadonlyArray, server: "current" | "legacy" = "current") => { const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type })); + const isMatch = (item: (typeof items)[number]) => + ["user_message", "assistant_message", "proposed_plan"].includes(item.type); const served: Array = []; const call = ((_tool: string, input: unknown) => { - const args = input as { readonly afterPosition?: number; readonly limit: number }; - const isMessage = (item: (typeof items)[number]) => - ["user_message", "assistant_message", "proposed_plan"].includes(item.type); + const args = input as { + readonly afterPosition?: number; + readonly beforePosition?: number; + readonly limit: number; + }; + if (args.beforePosition !== undefined) { + if (server === "legacy") { + return Effect.fail( + new ThreadToolFailedError({ + tool: "t3_thread_read", + detail: 'The server refused the arguments: Unknown argument "beforePosition".', + }), + ); + } + const newestFirst: typeof items = []; + const end = Math.min(args.beforePosition, items.length); + for (let position = end - 1; position >= 0 && newestFirst.length <= args.limit; position--) { + if (isMatch(items[position]!)) newestFirst.push(items[position]!); + } + const page = newestFirst.slice(0, args.limit).reverse(); + served.push(page.length); + return Effect.succeed({ + thread: { itemCount: items.length }, + items: page, + nextPosition: page.at(-1)?.position ?? null, + hasMore: false, + earlierPosition: newestFirst.length > page.length ? page[0]!.position : null, + }); + } if (args.afterPosition === undefined) { - const page = items.filter(isMessage).slice(-args.limit); + const page = items.filter(isMatch).slice(-args.limit); served.push(page.length); return Effect.succeed({ thread: { itemCount: items.length }, @@ -562,7 +611,7 @@ const timelineTools = (types: ReadonlyArray) => { const matching: typeof items = []; for (let position = args.afterPosition + 1; position < items.length; position++) { const item = items[position]!; - if (isMessage(item)) { + if (isMatch(item)) { matching.push(item); if (matching.length > args.limit) break; } @@ -585,6 +634,7 @@ const timelineTools = (types: ReadonlyArray) => { }; const tail = (tools: number) => [...Array(tools).fill("tool_call"), "assistant_message"]; +const SERVERS = ["current", "legacy"] as const; it.effect("show retains pull request metadata when reading a later message window", () => Effect.gen(function* () { @@ -620,55 +670,90 @@ it.effect("show retains pull request metadata when reading a later message windo }), ); -it.effect("show reads the end of a long thread, not its whole history", () => - Effect.gen(function* () { - const { tools, served, latest } = timelineTools([ - ...Array.from({ length: 1000 }, (_, index) => - index % 2 === 0 ? "user_message" : "assistant_message", - ), - ...Array.from({ length: 10 }, () => tail(30)).flat(), - "proposed_plan", - ]); +it.effect.each(SERVERS)( + "show reads the end of a long thread, not its whole history (%s)", + (server) => + Effect.gen(function* () { + const { tools, served, latest } = timelineTools( + [ + ...Array.from({ length: 1000 }, (_, index) => + index % 2 === 0 ? "user_message" : "assistant_message", + ), + ...Array.from({ length: 10 }, () => tail(30)).flat(), + "proposed_plan", + ], + server, + ); - const { messages } = yield* readLatestMessages(tools, threadId, 10); + const { messages } = yield* readLatestMessages(tools, threadId, 10); - assert.deepStrictEqual( - messages.map((item) => item.itemId), - latest(10), - ); - assert.isBelow( - served.reduce((sum, count) => sum + count, 0), - 100, - ); - }), + assert.deepStrictEqual( + messages.map((item) => item.itemId), + latest(10), + ); + assert.isBelow( + served.reduce((sum, count) => sum + count, 0), + 100, + ); + // Each call builds the whole thread's index on the server, so calls are the cost. + if (server === "current") assert.lengthOf(served, 2); + }), ); -it.effect("show widens back to the first item when the thread has fewer messages", () => - Effect.gen(function* () { - const { tools, latest } = timelineTools([ - "user_message", - ...Array.from({ length: 4 }, () => tail(150)).flat(), - ]); +it.effect.each(SERVERS)( + "show widens back to the first item when the thread has fewer messages (%s)", + (server) => + Effect.gen(function* () { + const { tools, latest } = timelineTools( + ["user_message", ...Array.from({ length: 4 }, () => tail(150)).flat()], + server, + ); - const { messages } = yield* readLatestMessages(tools, threadId, 10); + const { messages } = yield* readLatestMessages(tools, threadId, 10); - assert.deepStrictEqual( - messages.map((item) => item.itemId), - latest(10), - ); - assert.lengthOf(messages, 5); - }), + assert.deepStrictEqual( + messages.map((item) => item.itemId), + latest(10), + ); + assert.lengthOf(messages, 5); + }), ); -it.effect("show returns a --messages count larger than one call can spread", () => +it.effect.each(SERVERS)( + "show returns a --messages count larger than one call can spread (%s)", + (server) => + Effect.gen(function* () { + const { tools, latest } = timelineTools( + Array(200_000).fill("assistant_message"), + server, + ); + + const { messages } = yield* readLatestMessages(tools, threadId, 200_000); + + assert.deepStrictEqual( + messages.map((item) => item.itemId), + latest(200_000), + ); + }), +); + +it.effect("show stops when a server's earlierPosition does not move back", () => Effect.gen(function* () { - const { tools, latest } = timelineTools(Array(200_000).fill("assistant_message")); + const page = { + thread: { itemCount: 10 }, + items: [{ position: 5, itemId: "item-5", type: "assistant_message" }], + nextPosition: 5, + hasMore: false, + earlierPosition: 5, + }; + const { tools, calls } = scriptedTools({ t3_thread_read: [page, page] }); - const { messages } = yield* readLatestMessages(tools, threadId, 200_000); + const { messages } = yield* readLatestMessages(tools, threadId, 10); + assert.lengthOf(calls, 2); assert.deepStrictEqual( messages.map((item) => item.itemId), - latest(200_000), + ["item-5"], ); }), ); @@ -680,22 +765,38 @@ it.effect("show gives the latest run's last error only when that run did not com items: [ { itemId: "item-0", runId: RunId.make("run-0"), type: "error", text: "earlier run" }, { itemId: "item-1", runId, type: "error", text: "first try" }, - { itemId: "item-2", runId, type: "error", text: "Usage limit reached" }, + { + itemId: "item-2", + runId, + type: "error", + text: "U", + textTruncated: true, + nextTextOffset: 1, + }, ], nextPosition: null, hasMore: false, + earlierPosition: null, + }; + const rest = { + thread: {}, + items: [{ itemId: "item-2", runId, type: "error", text: "sage limit reached" }], + nextPosition: null, + hasMore: false, }; - const { tools, calls } = scriptedTools({ t3_thread_read: [page] }); + const { tools, calls } = scriptedTools({ t3_thread_read: [page, rest] }); assert.strictEqual( yield* latestRunError(tools, { threadId, status: "failed", latestRunId: runId }), "Usage limit reached", ); - assert.deepInclude(calls[0]?.args, { view: "activity" }); + // Searching with full text would fit one long item per read under the server's budget. + assert.deepInclude(calls[0]?.args, { view: "activity", maxCharsPerItem: 1 }); + assert.deepInclude(calls[1]?.args, { itemId: "item-2", textOffset: 1 }); for (const status of ["completed", "running", "queued", "idle"] as const) { assert.isNull(yield* latestRunError(tools, { threadId, status, latestRunId: runId }), status); } - assert.lengthOf(calls, 1); + assert.lengthOf(calls, 2); }), ); diff --git a/apps/server/src/cli/thread.ts b/apps/server/src/cli/thread.ts index 7ae729b391edb..6b34f699a5cea 100644 --- a/apps/server/src/cli/thread.ts +++ b/apps/server/src/cli/thread.ts @@ -52,6 +52,8 @@ const TERMINAL_RUN_STATUSES = new Set([ ]); const READ_PAGE_LIMIT = 100; const READ_ITEM_MAX_CHARS = 20_000; +/** A `beforePosition` past every item, so the read starts at the newest. */ +const NEWEST_POSITION = Number.MAX_SAFE_INTEGER; const TITLE_MAX_CHARS = 80; export class ThreadServerNotRunningError extends Schema.TaggedError()( @@ -447,11 +449,61 @@ const readTimeline = Effect.fn("cli.thread.readTimeline")(function* ( }); /** - * The latest `count` user and assistant messages, oldest first. Positions - * count every timeline item, so the read starts near the end and widens - * backward only while tool and plan items leave too few messages. + * Pages back from the newest item until `done` accepts a page, newest page + * first. Undefined when the server predates `beforePosition`: its strict + * schema refuses the field, and a forward-only one answers without `earlierPosition`. */ -export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(function* ( +const readBackward = Effect.fn("cli.thread.readBackward")(function* ( + tools: ThreadTools, + threadId: ThreadId, + view: "messages" | "activity", + nextLimit: () => number, + done: (page: ReadonlyArray) => boolean, + maxCharsPerItem = READ_ITEM_MAX_CHARS, +) { + const read = (beforePosition: number) => + tools.call( + "t3_thread_read", + { + threadId, + view, + limit: nextLimit(), + maxCharsPerItem, + runLimit: 1, + beforePosition, + }, + OrchestratorMcpThreadReadResult, + ); + const newest = yield* read(NEWEST_POSITION).pipe( + Effect.catchTags({ ThreadToolFailedError: () => Effect.succeed(null) }), + ); + if (newest === null || newest.earlierPosition === undefined) return undefined; + // Only the newest page carries pull request previews; later pages omit them. + let thread = newest.thread; + const pages = [newest.items]; + let earlier = done(newest.items) ? null : newest.earlierPosition; + while (earlier !== null) { + const before = earlier; + const page = yield* read(before); + thread = Object.assign({}, thread, page.thread); + // A server that repeats a page, or a cursor that does not move back, would read forever. + const items = page.items.filter((item) => item.position < before); + pages.push(items); + const next = page.earlierPosition ?? null; + earlier = done(items) || next === null || next >= before ? null : next; + } + return { thread, pages }; +}); + +const isConversationMessage = (item: OrchestratorMcpThreadTimelineItem) => + item.type === "user_message" || item.type === "assistant_message"; + +/** + * `readLatestMessages` for servers without `beforePosition`. Positions count + * every timeline item, so the read starts near the end and widens backward + * only while tool and plan items leave too few messages. + */ +const readLatestMessagesForward = Effect.fn("cli.thread.readLatestMessagesForward")(function* ( tools: ThreadTools, threadId: ThreadId, count: number, @@ -488,9 +540,7 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun ); window.push( ...page.items.filter( - (item) => - (item.type === "user_message" || item.type === "assistant_message") && - (end === undefined || item.position < end), + (item) => isConversationMessage(item) && (end === undefined || item.position < end), ), ); afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY; @@ -505,6 +555,27 @@ export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(fun return { thread, messages: messages.slice(Math.max(0, messages.length - count)) }; }); +/** The latest `count` user and assistant messages, oldest first. */ +export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(function* ( + tools: ThreadTools, + threadId: ThreadId, + count: number, +) { + let found = 0; + const read = yield* readBackward( + tools, + threadId, + "messages", + // Items can be long, so a page asks only for the messages still missing. + () => Math.min(READ_PAGE_LIMIT, Math.max(1, count - found)), + (page) => (found += page.filter(isConversationMessage).length) >= count, + ); + if (read === undefined) return yield* readLatestMessagesForward(tools, threadId, count); + // A --messages count can be too many items to spread as arguments. + const messages = read.pages.toReversed().flat().filter(isConversationMessage); + return { thread: read.thread, messages: messages.slice(Math.max(0, messages.length - count)) }; +}); + /** Item text past the read's per-item cap. */ const readFullText = Effect.fn("cli.thread.readFullText")(function* ( tools: ThreadTools, @@ -540,12 +611,21 @@ const runResultText = Effect.fn("cli.thread.runResultText")(function* ( runId: RunId, type: "assistant_message" | "error", ) { - const { items } = yield* readTimeline( + const view = type === "assistant_message" ? "messages" : "activity"; + const matches = (candidate: OrchestratorMcpThreadTimelineItem) => + candidate.runId === runId && candidate.type === type; + // The server returns only what fits its response budget, so a search that reads full text + // gets one long item per page; readFullText fetches the found item's text instead. + const read = yield* readBackward( tools, threadId, - type === "assistant_message" ? "messages" : "activity", + view, + () => READ_PAGE_LIMIT, + (page) => page.some(matches), + 1, ); - const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type); + const pages = read?.pages ?? [(yield* readTimeline(tools, threadId, view)).items]; + const item = pages.map((page) => page.findLast(matches)).find((match) => match !== undefined); return item === undefined ? null : yield* readFullText(tools, threadId, item); }); @@ -605,11 +685,28 @@ const runsAfter = Effect.fn("cli.thread.runsAfter")(function* ( if (own === undefined) return { later: [], sent: true }; const later = recentRuns.filter((run) => run.ordinal > own.ordinal); if (later.length === 0) return { later, sent: false }; - const { items } = yield* readTimeline(tools, threadId, "messages"); - const sent = items.some( - (item) => item.type === "user_message" && later.some((run) => run.runId === item.runId), + const isSent = (item: OrchestratorMcpThreadTimelineItem) => + item.type === "user_message" && later.some((run) => run.runId === item.runId); + // Runs take sent messages in order, so a later run's message comes after any + // message this run or an earlier one took. + const notLater = new Set( + recentRuns.filter((run) => run.ordinal <= own.ordinal).map((run) => run.runId), + ); + const read = yield* readBackward( + tools, + threadId, + "messages", + () => READ_PAGE_LIMIT, + (page) => + page.some( + (item) => + isSent(item) || + (item.type === "user_message" && item.runId != null && notLater.has(item.runId)), + ), + 1, ); - return { later, sent }; + const pages = read?.pages ?? [(yield* readTimeline(tools, threadId, "messages")).items]; + return { later, sent: pages.some((page) => page.some(isSent)) }; }); /**