Skip to content

Commit 796846d

Browse files
fix(server): a busy thread also gets one wake for a pass over several pull requests
The last change kept combined wakes out of the queue, so a busy thread still got one queued wake and turn per pull request. Combined wakes queue again. Each pull request's stamp now carries its own part of the wake, and when the wake is about to start, the parts for pull requests that went outdated while it waited are dropped. The message is rebuilt from the parts still current, and the wake is cancelled once none are. AI-assisted; verified with the tests and tools listed above.
1 parent cf4df55 commit 796846d

5 files changed

Lines changed: 212 additions & 118 deletions

File tree

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 72 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,7 @@ import {
8181
import * as KeyedLock from "@t3tools/shared/KeyedLock";
8282
import { modelSelectionsEqual } from "@t3tools/shared/model";
8383
import { modelSwitchSince } from "./modelSwitch.ts";
84+
import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts";
8485
import { recordThreadOpen } from "@t3tools/shared/paletteSearch";
8586
import {
8687
backgroundWorkHoldsCompletion,
@@ -1021,6 +1022,46 @@ function isStalePullRequestWatchWake(
10211022
);
10221023
}
10231024

1025+
/**
1026+
* A queued wake covering several pull requests, rebuilt from the ones still current, or
1027+
* undefined when it needs no change.
1028+
*/
1029+
function currentPullRequestWatchWake(
1030+
projection: Pick<OrchestrationV2ThreadProjection, "thread" | "messages">,
1031+
run: OrchestrationV2Run,
1032+
): OrchestrationV2ConversationMessage | undefined {
1033+
const message = projection.messages.find((candidate) => candidate.id === run.userMessageId);
1034+
const stamps = monitorPullRequestStamps(message?.notification?.source);
1035+
if (message === undefined || stamps.length < 2) return undefined;
1036+
const current = stamps.filter((stamp) => !isStalePullRequestWatchStamp(projection, stamp));
1037+
const [first, ...rest] = current;
1038+
if (first === undefined || rest.length === stamps.length - 1) return undefined;
1039+
const sections = current.flatMap(({ section }) => (section === undefined ? [] : [section]));
1040+
if (sections.length !== current.length) return undefined;
1041+
const wake = combinePullRequestWatchWakes(
1042+
sections.map(({ text, outcome, summary }) => ({
1043+
text,
1044+
notification: { source: { kind: "monitor" }, outcome, summary },
1045+
})) as [PullRequestWatchWake, ...Array<PullRequestWatchWake>],
1046+
);
1047+
return {
1048+
...message,
1049+
text: wake.text,
1050+
notification: {
1051+
...wake.notification,
1052+
source: {
1053+
kind: "monitor",
1054+
pullRequest: rest.length === 0 ? withoutSection(first) : first,
1055+
...(rest.length === 0 ? {} : { otherPullRequests: rest }),
1056+
},
1057+
},
1058+
};
1059+
}
1060+
1061+
function withoutSection({ section: _, ...stamp }: MonitorPullRequestStamp) {
1062+
return stamp;
1063+
}
1064+
10241065
function queuedRunCancellationEvents(
10251066
projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "attempts">,
10261067
run: OrchestrationV2Run,
@@ -2130,6 +2171,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
21302171
projection = yield* readCommandProjection(threadId);
21312172
storedQueuedRun = nextQueuedRun(projection);
21322173
}
2174+
// A wake that outlived some of its pull requests tells only the current ones.
2175+
const currentWake =
2176+
storedQueuedRun === undefined
2177+
? undefined
2178+
: currentPullRequestWatchWake(projection, storedQueuedRun);
2179+
if (storedQueuedRun !== undefined && currentWake !== undefined) {
2180+
const now = yield* DateTime.now;
2181+
yield* writeSystemEvents([
2182+
{
2183+
type: "message.updated",
2184+
threadId,
2185+
runId: storedQueuedRun.id,
2186+
...(storedQueuedRun.rootNodeId === null ? {} : { nodeId: storedQueuedRun.rootNodeId }),
2187+
providerInstanceId: storedQueuedRun.providerInstanceId,
2188+
occurredAt: now,
2189+
payload: { ...currentWake, updatedAt: now },
2190+
},
2191+
]);
2192+
const runId = storedQueuedRun.id;
2193+
projection = yield* readCommandProjection(threadId);
2194+
storedQueuedRun = projection.runs.find((run) => run.id === runId);
2195+
}
21332196
if (storedQueuedRun === undefined) {
21342197
return;
21352198
}
@@ -3596,28 +3659,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
35963659
entry.watch !== null &&
35973660
pullRequestSnapshotEndsWatch(link?.snapshot ?? null, entry.startedAt),
35983661
);
3599-
// A queued wake is dropped whole once outdated, so one covering several pull requests
3600-
// must start now; otherwise the sender splits it into one wake per pull request.
3601-
const queues =
3602-
entries.length > 1 &&
3603-
(yield* projectionStore.getThreadRecords(command.threadId, ["runs"]).pipe(
3604-
Effect.mapError(
3605-
(cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
3606-
),
3607-
Effect.map(({ runs }) => {
3608-
const latest = latestExecutedRun(runs);
3609-
return (
3610-
runs.some(isActiveRun) ||
3611-
((latest?.status === "failed" || latest?.status === "interrupted") &&
3612-
latest.workspacePreparation?.type === "worktree" &&
3613-
thread.worktreePath === null)
3614-
);
3615-
}),
3616-
));
36173662
if (
36183663
entries.some(({ entry, link }) => link?.watch?.startedAt !== entry.startedAt) ||
36193664
(wake && inactive) ||
3620-
queues ||
3665+
// One wake cannot drop the news of just some of its pull requests; the sender splits it.
36213666
(entries.length > 1 && outdated.some(Boolean))
36223667
) {
36233668
return yield* new OrchestratorDispatchError({
@@ -3631,21 +3676,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
36313676
yield* dispatchThreadMutation(mutation, events, effects);
36323677
}
36333678
if (wake === undefined || outdated[0]) return;
3634-
const stamps = entries.map(({ entry, key }) => ({
3679+
const { sections, ...wakeMessage } = wake;
3680+
const stamps = entries.map(({ entry, key }, index) => ({
36353681
...key,
36363682
watchStartedAt: entry.startedAt,
36373683
headSha: entry.includesRemarks === true ? null : (entry.watch?.headSha ?? null),
36383684
...(entry.watch === null ? { watchEnded: true } : {}),
3685+
...(entries.length > 1 && sections?.[index] !== undefined
3686+
? { section: sections[index] }
3687+
: {}),
36393688
}));
36403689
yield* dispatchMessage(
36413690
{
36423691
type: "message.dispatch",
36433692
commandId: command.commandId,
36443693
threadId: command.threadId,
3645-
messageId: wake.messageId,
3646-
text: wake.text,
3694+
messageId: wakeMessage.messageId,
3695+
text: wakeMessage.text,
36473696
notification: {
3648-
...wake.notification,
3697+
...wakeMessage.notification,
36493698
source:
36503699
wake.notification.source.kind === "monitor"
36513700
? {

‎apps/server/src/orchestration-v2/PullRequestWatchReactor.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,11 @@ export const make = Effect.gen(function* () {
464464
wake: {
465465
...combinePullRequestWatchWakes([first.wake, ...rest.map((item) => item.wake)]),
466466
...(first.wake.includesRemarks === true ? { includesRemarks: true } : {}),
467+
sections: items.map(({ wake }) => ({
468+
text: wake.text,
469+
outcome: wake.notification.outcome,
470+
summary: wake.notification.summary,
471+
})),
467472
messageId: MessageId.make(`message:pr-watch:${uuid}`),
468473
},
469474
});

‎apps/server/src/orchestration-v2/pullRequestWatch.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -284,7 +284,7 @@ const WATCHING_CLOSING =
284284
const WATCHING_CLOSING_PLURAL =
285285
"Look into each item and act on it as your task requires. Each PR T3 Code still watches stays linked and watched, so do not link, watch, or list them again. End your turn when you are done, and T3 Code wakes you on the next change. When you hand the work back to the user, call unwatch_pull_request for each first so the thread returns to their inbox.";
286286

287-
interface PullRequestWatchWake {
287+
export interface PullRequestWatchWake {
288288
readonly text: string;
289289
readonly notification: OrchestrationV2Notification;
290290
}

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 115 additions & 92 deletions
Original file line numberDiff line numberDiff line change
@@ -4094,110 +4094,133 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
40944094
}),
40954095
);
40964096

4097-
// A busy thread queues its wakes, and a queued wake is dropped whole once outdated, so
4098-
// there each pull request keeps its own wake.
40994097
it.effect.each([
41004098
["an idle", false],
41014099
["a busy", true],
4102-
] as const)("wakes %s thread once per pass, or per pull request while it is busy", ([, busy]) =>
4103-
Effect.gen(function* () {
4104-
const orchestrator = yield* Orchestrator.OrchestratorV2;
4105-
const threadId = ThreadId.make(`runtime-pull-request-watch-pass-${busy}`);
4106-
const projectId = ProjectId.make(`pr-watch-pass-project-${busy}`);
4107-
yield* seedProject({
4108-
projectId,
4109-
title: "Watch pass",
4110-
workspaceRoot: "/workspace/watch-pass",
4111-
defaultModelSelection: null,
4112-
createdAt: "2026-10-01T00:00:00.000Z",
4113-
});
4114-
yield* orchestrator.dispatch({
4115-
type: "thread.create",
4116-
createdBy: "user",
4117-
creationSource: "web",
4118-
commandId: CommandId.make(`pr-watch-pass-create-${busy}`),
4119-
threadId,
4120-
projectId,
4121-
title: "Watch pass",
4122-
modelSelection,
4123-
runtimeMode: "full-access",
4124-
interactionMode: "default",
4125-
branch: null,
4126-
worktreePath: null,
4127-
});
4128-
const numbers = [12, 13, 14];
4129-
for (const number of numbers) {
4130-
yield* orchestrator.dispatch({
4131-
type: "thread.pull-request.watch",
4132-
commandId: CommandId.make(`pr-watch-pass-start-${busy}-${number}`),
4133-
threadId,
4134-
host: "github.com",
4135-
repository: "pingdotgg/t3code",
4136-
number,
4137-
watching: true,
4138-
link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
4100+
] as const)(
4101+
"wakes %s thread once for a pass that changed several of its pull requests",
4102+
([, busy]) =>
4103+
Effect.gen(function* () {
4104+
const orchestrator = yield* Orchestrator.OrchestratorV2;
4105+
const threadId = ThreadId.make(`runtime-pull-request-watch-pass-${busy}`);
4106+
const projectId = ProjectId.make(`pr-watch-pass-project-${busy}`);
4107+
yield* seedProject({
4108+
projectId,
4109+
title: "Watch pass",
4110+
workspaceRoot: "/workspace/watch-pass",
4111+
defaultModelSelection: null,
4112+
createdAt: "2026-10-01T00:00:00.000Z",
41394113
});
4140-
}
4141-
if (busy) {
41424114
yield* orchestrator.dispatch({
4143-
type: "message.dispatch",
4115+
type: "thread.create",
41444116
createdBy: "user",
41454117
creationSource: "web",
4146-
commandId: CommandId.make("pr-watch-pass-busy"),
4118+
commandId: CommandId.make(`pr-watch-pass-create-${busy}`),
41474119
threadId,
4148-
messageId: MessageId.make("pr-watch-pass-busy"),
4149-
text: "Keep this run active.",
4150-
attachments: [],
4120+
projectId,
4121+
title: "Watch pass",
41514122
modelSelection,
4152-
dispatchMode: { type: "start_immediately" },
4123+
runtimeMode: "full-access",
4124+
interactionMode: "default",
4125+
branch: null,
4126+
worktreePath: null,
41534127
});
4154-
}
4155-
const host = Layer.mergeAll(
4156-
NodeServices.layer,
4157-
NodeCrypto.layer,
4158-
Layer.mock(PullRequestService.PullRequestService)({
4159-
detail: (input) =>
4160-
Effect.succeed({
4161-
...watchedPullRequestDetail({
4162-
projectId,
4163-
number: input.number,
4164-
at: "2026-10-02T12:00:00.000Z",
4128+
const numbers = [12, 13, 14];
4129+
for (const number of numbers) {
4130+
yield* orchestrator.dispatch({
4131+
type: "thread.pull-request.watch",
4132+
commandId: CommandId.make(`pr-watch-pass-start-${busy}-${number}`),
4133+
threadId,
4134+
host: "github.com",
4135+
repository: "pingdotgg/t3code",
4136+
number,
4137+
watching: true,
4138+
link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
4139+
});
4140+
}
4141+
if (busy) {
4142+
yield* orchestrator.dispatch({
4143+
type: "message.dispatch",
4144+
createdBy: "user",
4145+
creationSource: "web",
4146+
commandId: CommandId.make("pr-watch-pass-busy"),
4147+
threadId,
4148+
messageId: MessageId.make("pr-watch-pass-busy"),
4149+
text: "Keep this run active.",
4150+
attachments: [],
4151+
modelSelection,
4152+
dispatchMode: { type: "start_immediately" },
4153+
});
4154+
}
4155+
const host = Layer.mergeAll(
4156+
NodeServices.layer,
4157+
NodeCrypto.layer,
4158+
Layer.mock(PullRequestService.PullRequestService)({
4159+
detail: (input) =>
4160+
Effect.succeed({
4161+
...watchedPullRequestDetail({
4162+
projectId,
4163+
number: input.number,
4164+
at: "2026-10-02T12:00:00.000Z",
4165+
}),
4166+
headSha: `head${input.number}`,
4167+
checks: [
4168+
{ name: "test", status: "failure", description: null, url: null, required: true },
4169+
],
41654170
}),
4166-
headSha: `head${input.number}`,
4167-
checks: [
4168-
{ name: "test", status: "failure", description: null, url: null, required: true },
4169-
],
4170-
}),
4171-
activity: () =>
4172-
Effect.succeed({
4173-
comments: [],
4174-
commentCount: 0,
4175-
commentsTruncated: false,
4176-
reviewThreads: [],
4177-
commits: [],
4178-
}),
4179-
}),
4180-
);
4171+
activity: () =>
4172+
Effect.succeed({
4173+
comments: [],
4174+
commentCount: 0,
4175+
commentsTruncated: false,
4176+
reviewThreads: [],
4177+
commits: [],
4178+
}),
4179+
}),
4180+
);
41814181

4182-
const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4183-
yield* reactor.sweep;
4184-
const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]);
4185-
const wakes = messages.filter((message) => message.notification !== undefined);
4186-
const stamps = wakes.map(({ notification }) =>
4187-
notification?.source.kind === "monitor"
4188-
? [notification.source.pullRequest, ...(notification.source.otherPullRequests ?? [])]
4189-
.map((stamp) => stamp?.number)
4190-
.toSorted()
4191-
: [],
4192-
);
4193-
assert.deepEqual(
4194-
stamps.toSorted((left, right) => left[0]! - right[0]!),
4195-
busy ? numbers.map((number) => [number]) : [numbers],
4196-
);
4197-
for (const number of numbers) {
4198-
assert.isTrue(wakes.some((wake) => wake.text.includes(`#${number}`)));
4199-
}
4200-
}),
4182+
const reactor = yield* PullRequestWatchReactor.make.pipe(Effect.provide(host));
4183+
yield* reactor.sweep;
4184+
const { messages } = yield* orchestrator.getThreadRecords(threadId, ["messages"]);
4185+
const wakes = messages.filter((message) => message.notification !== undefined);
4186+
const stamps = wakes.map(({ notification }) =>
4187+
notification?.source.kind === "monitor"
4188+
? [notification.source.pullRequest, ...(notification.source.otherPullRequests ?? [])]
4189+
.map((stamp) => stamp?.number)
4190+
.toSorted()
4191+
: [],
4192+
);
4193+
assert.deepEqual(stamps, [numbers]);
4194+
for (const number of numbers) assert.include(wakes[0]!.text, `#${number}`);
4195+
if (!busy) return;
4196+
4197+
// A pull request unwatched while the wake waited leaves it; the others still start.
4198+
yield* orchestrator.dispatch({
4199+
type: "thread.pull-request.watch",
4200+
commandId: CommandId.make("pr-watch-pass-stop-12"),
4201+
threadId,
4202+
host: "github.com",
4203+
repository: "pingdotgg/t3code",
4204+
number: 12,
4205+
watching: false,
4206+
});
4207+
const active = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
4208+
yield* orchestrator.dispatch({
4209+
type: "run.interrupt",
4210+
commandId: CommandId.make("pr-watch-pass-interrupt"),
4211+
threadId,
4212+
runId: active.id,
4213+
});
4214+
yield* orchestrator.resumeQueuedRuns;
4215+
const after = yield* orchestrator.getThreadProjection(threadId);
4216+
const woken = after.messages.find((message) => message.id === wakes[0]!.id)!;
4217+
assert.notInclude(woken.text, "#12");
4218+
for (const number of [13, 14]) assert.include(woken.text, `#${number}`);
4219+
assert.notEqual(
4220+
after.runs.find((run) => run.userMessageId === woken.id)?.status,
4221+
"cancelled",
4222+
);
4223+
}),
42014224
);
42024225

42034226
it.effect.each(["pending", "action-required"] as const)("recovers %s watches", (initialStatus) =>

0 commit comments

Comments
 (0)