=>
Effect.fail(new WorkflowStop({ reason }));
@@ -730,6 +841,8 @@ export interface WorkflowDefinition {
readonly triggers: ReadonlyArray;
/** The kinds of question it asks, each with the label a list shows, in the order to show them. */
readonly asks: AskKinds;
+ /** How many of its runs may go on at once; undefined for no limit. */
+ readonly concurrency: number | undefined;
/** Fails with the reason as text: by here nothing reads the error but a person. */
readonly onEnd:
| ((payload: never, end: RunEnd) => Effect.Effect)
@@ -815,6 +928,8 @@ const invokeAs = Effect.fn("workflow.invoke")(function* (
return { outcome: "completed", value: value as A };
});
+/** Starts the name of every step that waits for a place in a pool, and of no step of a body. */
+const PLACE_PREFIX = "@pool:";
/** The step `onEnd` runs as. */
export const END_STEP = "onEnd";
const END_RETRY: StepRetry = { times: 3, schedule: Schedule.exponential("2 seconds") };
@@ -847,6 +962,8 @@ export const workflow =
(
* listed as Other.
*/
readonly asks?: AskKinds;
+ /** How many runs of this workflow go on at once, across its versions. Later ones queue. */
+ readonly concurrency?: number;
/**
* Runs once when the run ends, however it ends, to give back what the run took: a machine, a
* lock. It gets the payload and the run's id, not the body's values, so name what the run
@@ -866,8 +983,12 @@ export const workflow =
(
"resumeAfter",
"triggers",
"asks",
+ "concurrency",
"onEnd",
]);
+ if (options.concurrency !== undefined) {
+ checkLimit(`workflow("${name}")'s concurrency`, options.concurrency);
+ }
// Read once now, so a duration that does not parse fails the file and not a paused run later.
for (const rest of options.resumeAfter ?? [])
durationOf(`workflow("${name}")'s resumeAfter`, rest);
@@ -891,6 +1012,7 @@ const definitionOf =
(
resumeAfter: options.resumeAfter ?? DEFAULT_RESUME_AFTER,
triggers: options.triggers ?? [],
asks: checkAskKinds(name, options.asks),
+ concurrency: options.concurrency,
onEnd:
options.onEnd === undefined
? undefined
@@ -940,7 +1062,18 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo
}),
});
const input = (yield* Effect.orDie(decodePayload(payload.input))) as never;
- const outcome = yield* definition.body(input, { id: runId }).pipe(
+ const body = definition.body(input, { id: runId });
+ const outcome = yield* (
+ definition.concurrency === undefined
+ ? body
+ : holding(
+ `${PLACE_PREFIX}${definition.name}`,
+ definition.name,
+ definition.concurrency,
+ body,
+ true,
+ )
+ ).pipe(
Effect.flatMap((value) =>
definition.returns === ANY_JSON
? untypedResult(value)
@@ -994,13 +1127,24 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo
watchTurn: Effect.fn("RunContext.watchTurn")(function* (wait: string) {
if (link.current !== undefined) yield* link.current.watchTurn(runId, wait);
}),
+ placeAsked: Effect.fn("RunContext.placeAsked")(function* (name, pool, size) {
+ if (link.current !== undefined) {
+ yield* link.current.placeAsked({ runId, name, pool, size });
+ }
+ }),
+ placeLeft: Effect.fn("RunContext.placeLeft")(function* (name) {
+ if (link.current !== undefined) yield* link.current.placeLeft(runId, name);
+ }),
+ placesFreed: Effect.suspend(() => link.current?.placesFreed ?? Effect.void),
}),
),
);
yield* Activity.make({
name: "run/end",
- execute: Effect.asVoid(
+ execute: Effect.andThen(
store.runEnded(runId, outcome.outcome, outcome.reason ?? null, outcome.value),
+ // What it still held, as a run that stops inside `within` does, goes to the next.
+ Effect.suspend(() => link.current?.placesFreed ?? Effect.void),
),
});
yield* Activity.make({
@@ -1014,9 +1158,12 @@ export const layerDefinition = (definition: WorkflowDefinition, engine: EngineWo
Effect.tapCause((cause) =>
Cause.hasInterruptsOnly(cause)
? Effect.void
- : Effect.flatMap(WorkflowStore.WorkflowStore, (store) =>
- store.runPaused(runId, text(Cause.squash(cause))),
- ),
+ : Effect.gen(function* () {
+ const store = yield* WorkflowStore.WorkflowStore;
+ const link = yield* EngineLink;
+ yield* store.runPaused(runId, text(Cause.squash(cause)));
+ if (link.current !== undefined) yield* link.current.placesFreed;
+ }),
),
),
);
diff --git a/apps/web/src/components/workflows/WorkflowRunFeed.tsx b/apps/web/src/components/workflows/WorkflowRunFeed.tsx
index e7cda729d54af..328185420c194 100644
--- a/apps/web/src/components/workflows/WorkflowRunFeed.tsx
+++ b/apps/web/src/components/workflows/WorkflowRunFeed.tsx
@@ -195,6 +195,15 @@ const nthTry = (count: number, resolve: MessageResolver) =>
}),
);
+const queuedText = (beat: WorkflowBeat, resolve: MessageResolver) =>
+ beat.ahead === undefined || beat.ahead === 0
+ ? resolve(msg("queued, next in line", { $context: "a workflow step waits for a free place" }))
+ : resolve(
+ msg("{count, plural, one {queued, {count} ahead} other {queued, {count} ahead}}", {
+ count: beat.ahead,
+ }),
+ );
+
// The loading view and the timeline each draw a question's card, so a reason typed while the
// steps load is kept here rather than in the card that is about to be replaced.
const AnswerDrafts = createContext<{
@@ -431,7 +440,8 @@ export function WorkflowRunFeed({
beat.status !== "running" &&
beat.kind !== "ask" &&
beat.kind !== "sleep" &&
- beat.kind !== "wait",
+ beat.kind !== "wait" &&
+ beat.kind !== "queue",
) ??
null)
: null;
@@ -1019,7 +1029,11 @@ function WorkflowTimeline({
const running = row.beats.filter((beat) => beat.status === "running").length;
// Steps that only sleep or wait are under way without working.
const working = row.beats.some(
- (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait",
+ (beat) =>
+ beat.status === "running" &&
+ beat.kind !== "sleep" &&
+ beat.kind !== "wait" &&
+ beat.kind !== "queue",
);
const failed = row.beats.some((beat) => beat.status === "failed");
const asks = row.beats.some(
@@ -1267,6 +1281,8 @@ function WorkflowBeatRow({
: gt("about to wake");
case "wait":
return gt("waiting");
+ case "queue":
+ return queuedText(beat, m);
case "run":
return child === null ? gt("running") : workflowRunNow(child, m);
case "step":
@@ -1290,6 +1306,7 @@ function WorkflowBeatRow({
: gt("withdrawn by {by}", { by: withdrawal.by });
case "sleep":
case "wait":
+ case "queue":
return null;
case "run":
return child === null ? null : workflowRunNow(child, m);
@@ -1312,7 +1329,7 @@ function WorkflowBeatRow({
: needsYou
? "input"
: under
- ? beat.kind === "sleep" || beat.kind === "wait"
+ ? beat.kind === "sleep" || beat.kind === "wait" || beat.kind === "queue"
? "quiet"
: "working"
: "done"
@@ -1335,7 +1352,11 @@ function WorkflowBeatRow({
note={beat.kind === "agent" && (under || said === null) ? model : null}
verb={verb}
verbTone={
- needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" ? "quiet" : "working"
+ needsYou
+ ? "input"
+ : beat.kind === "sleep" || beat.kind === "wait" || beat.kind === "queue"
+ ? "quiet"
+ : "working"
}
aside={aside}
{...(failed ? { asideTone: "failed" as const } : {})}
@@ -1617,6 +1638,17 @@ function WorkflowBeatCard({
/>
);
+ case "queue":
+ if (!under) return {`${gt("queued")} · ${length}`};
+ return (
+
+ }
+ name={beat.name}
+ sub={`${queuedText(beat, m)} · ${length}`}
+ />
+
+ );
case "run": {
const title = beat.childRun?.title ?? beat.name;
return (
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json
index 5fd6ff3ede89a..96b3cb7f1967a 100644
--- a/apps/web/src/i18n/translations/de.json
+++ b/apps/web/src/i18n/translations/de.json
@@ -12910,6 +12910,11 @@
"c92657bb7f2293ff": "Genehmigung nötig",
"f1e5c1be1ac92361": "Genehmigen",
"fcb5f3c4d4753326": "Über diese Verbindung lassen sich keine Befehle genehmigen. Verwende einen Client, der das Terminal verwenden darf.",
+ "7150557773b3818b": "In der Warteschlange",
+ "efbeb3993ee2c3f5": "Wartet auf {pool}",
+ "0398ca6c1d24b92d": "wartet, als Nächstes dran",
+ "0af6d5ffd5166214": "{count, plural, one {wartet, {count} davor} other {wartet, {count} davor}}",
+ "49be26a27dcb30e5": "gewartet",
"4e96712d839ccbff": "{who} hat {choice} gesagt",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json
index fa018a7c51464..311e476e747ea 100644
--- a/apps/web/src/i18n/translations/en.json
+++ b/apps/web/src/i18n/translations/en.json
@@ -12919,6 +12919,11 @@
"c92657bb7f2293ff": "Needs approval",
"f1e5c1be1ac92361": "Approve",
"fcb5f3c4d4753326": "This connection cannot approve commands. Use a client that can use the terminal.",
+ "7150557773b3818b": "Queued",
+ "efbeb3993ee2c3f5": "Queued for {pool}",
+ "0398ca6c1d24b92d": "queued, next in line",
+ "0af6d5ffd5166214": "{count, plural, one {queued, {count} ahead} other {queued, {count} ahead}}",
+ "49be26a27dcb30e5": "queued",
"4e96712d839ccbff": "{who} said {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json
index 50309bfa62b15..56c909b7dd178 100644
--- a/apps/web/src/i18n/translations/es.json
+++ b/apps/web/src/i18n/translations/es.json
@@ -12905,6 +12905,11 @@
"c92657bb7f2293ff": "Necesita aprobación",
"f1e5c1be1ac92361": "Aprobar",
"fcb5f3c4d4753326": "Esta conexión no puede aprobar comandos. Usa un cliente que pueda usar el terminal.",
+ "7150557773b3818b": "En cola",
+ "efbeb3993ee2c3f5": "En cola para {pool}",
+ "0398ca6c1d24b92d": "en cola, el siguiente",
+ "0af6d5ffd5166214": "{count, plural, one {en cola, {count} delante} other {en cola, {count} delante}}",
+ "49be26a27dcb30e5": "en cola",
"4e96712d839ccbff": "{who} dijo {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json
index ef718bab74888..23a7578590f54 100644
--- a/apps/web/src/i18n/translations/fr.json
+++ b/apps/web/src/i18n/translations/fr.json
@@ -12910,6 +12910,11 @@
"c92657bb7f2293ff": "Approbation requise",
"f1e5c1be1ac92361": "Approuver",
"fcb5f3c4d4753326": "Cette connexion ne peut pas approuver de commandes. Utilisez un client qui peut utiliser le terminal.",
+ "7150557773b3818b": "En file d’attente",
+ "efbeb3993ee2c3f5": "En attente de {pool}",
+ "0398ca6c1d24b92d": "en attente, le prochain",
+ "0af6d5ffd5166214": "{count, plural, one {en attente, {count} devant} other {en attente, {count} devant}}",
+ "49be26a27dcb30e5": "en attente",
"4e96712d839ccbff": "{who} a répondu {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json
index 206f1bbddfd7c..c89a28f54095d 100644
--- a/apps/web/src/i18n/translations/ja.json
+++ b/apps/web/src/i18n/translations/ja.json
@@ -12850,6 +12850,11 @@
"c92657bb7f2293ff": "承認が必要",
"f1e5c1be1ac92361": "承認",
"fcb5f3c4d4753326": "この接続ではコマンドを承認できません。ターミナルを使用できるクライアントを使ってください。",
+ "7150557773b3818b": "待機中",
+ "efbeb3993ee2c3f5": "{pool} を待機中",
+ "0398ca6c1d24b92d": "待機中、次の番",
+ "0af6d5ffd5166214": "{count, plural, other {待機中、前に {count} 件}}",
+ "49be26a27dcb30e5": "待機",
"4e96712d839ccbff": "{who}の回答: {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json
index 18acb61580259..760c1546802f6 100644
--- a/apps/web/src/i18n/translations/ko.json
+++ b/apps/web/src/i18n/translations/ko.json
@@ -12846,6 +12846,11 @@
"c92657bb7f2293ff": "승인 필요",
"f1e5c1be1ac92361": "승인",
"fcb5f3c4d4753326": "이 연결에서는 명령을 승인할 수 없습니다. 터미널을 사용할 수 있는 클라이언트를 사용하세요.",
+ "7150557773b3818b": "대기 중",
+ "efbeb3993ee2c3f5": "{pool} 대기 중",
+ "0398ca6c1d24b92d": "대기 중, 다음 차례",
+ "0af6d5ffd5166214": "{count, plural, other {대기 중, 앞에 {count}개}}",
+ "49be26a27dcb30e5": "대기함",
"4e96712d839ccbff": "{who}의 답변: {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json
index 05b2204a445ae..a616078c936f6 100644
--- a/apps/web/src/i18n/translations/pt-BR.json
+++ b/apps/web/src/i18n/translations/pt-BR.json
@@ -12910,6 +12910,11 @@
"c92657bb7f2293ff": "Precisa de aprovação",
"f1e5c1be1ac92361": "Aprovar",
"fcb5f3c4d4753326": "Esta conexão não pode aprovar comandos. Use um cliente que possa usar o terminal.",
+ "7150557773b3818b": "Na fila",
+ "efbeb3993ee2c3f5": "Na fila de {pool}",
+ "0398ca6c1d24b92d": "na fila, o próximo",
+ "0af6d5ffd5166214": "{count, plural, one {na fila, {count} à frente} other {na fila, {count} à frente}}",
+ "49be26a27dcb30e5": "na fila",
"4e96712d839ccbff": "{who} disse {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json
index 3556dd9455160..30cdb82efc3a2 100644
--- a/apps/web/src/i18n/translations/ru.json
+++ b/apps/web/src/i18n/translations/ru.json
@@ -12910,6 +12910,11 @@
"c92657bb7f2293ff": "Нужно подтверждение",
"f1e5c1be1ac92361": "Подтвердить",
"fcb5f3c4d4753326": "Это подключение не может подтверждать команды. Используйте клиент, которому доступен терминал.",
+ "7150557773b3818b": "В очереди",
+ "efbeb3993ee2c3f5": "В очереди за {pool}",
+ "0398ca6c1d24b92d": "в очереди, следующий",
+ "0af6d5ffd5166214": "{count, plural, one {в очереди, впереди {count}} few {в очереди, впереди {count}} many {в очереди, впереди {count}} other {в очереди, впереди {count}}}",
+ "49be26a27dcb30e5": "в очереди",
"4e96712d839ccbff": "Ответ {who}: {choice}",
"19097cfb8f5a79cf": [
"Ответ ",
diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json
index 6b559d46a1f99..9c524ac8b6e42 100644
--- a/apps/web/src/i18n/translations/sv.json
+++ b/apps/web/src/i18n/translations/sv.json
@@ -12917,6 +12917,11 @@
"c92657bb7f2293ff": "Behöver godkännande",
"f1e5c1be1ac92361": "Godkänn",
"fcb5f3c4d4753326": "Den här anslutningen kan inte godkänna kommandon. Använd en klient som får använda terminalen.",
+ "7150557773b3818b": "I kö",
+ "efbeb3993ee2c3f5": "Köar för {pool}",
+ "0398ca6c1d24b92d": "i kö, näst på tur",
+ "0af6d5ffd5166214": "{count, plural, one {i kö, {count} före} other {i kö, {count} före}}",
+ "49be26a27dcb30e5": "köade",
"4e96712d839ccbff": "{who} svarade {choice}",
"19097cfb8f5a79cf": [
{
diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json
index 4d6210cc5e6d0..341422731b4c0 100644
--- a/apps/web/src/i18n/translations/zh.json
+++ b/apps/web/src/i18n/translations/zh.json
@@ -12928,6 +12928,11 @@
"c92657bb7f2293ff": "待批准",
"f1e5c1be1ac92361": "批准",
"fcb5f3c4d4753326": "此连接无法批准命令。请使用可以使用终端的客户端。",
+ "7150557773b3818b": "排队中",
+ "efbeb3993ee2c3f5": "正在排队等待 {pool}",
+ "0398ca6c1d24b92d": "排队中,下一个",
+ "0af6d5ffd5166214": "{count, plural, other {排队中,前面还有 {count} 个}}",
+ "49be26a27dcb30e5": "已排队",
"4e96712d839ccbff": "{who}的回答:{choice}",
"19097cfb8f5a79cf": [
{
diff --git a/docs/user/workflows.md b/docs/user/workflows.md
index c7b3de5e94630..1ad5e42b94da1 100644
--- a/docs/user/workflows.md
+++ b/docs/user/workflows.md
@@ -108,6 +108,24 @@ The app asks for the reason before it sends a choice that requires one, and `t3
`tags([...])` labels a run for `t3 workflow list --tag backlog`, whether or not it waits on anyone.
+## Limit how much runs at once
+
+Wrap part of a run in a named pool to cap how many runs are inside it at once, across the whole server:
+
+```ts
+const { within, agent } = T3;
+
+yield* within("builders", { limit: 4 }, agent("fix", { ... }));
+```
+
+When all places are taken, later runs queue in the order they asked and show as **Queued** with their place in line; they count as running, not as needing you. A place is given back when the wrapped part ends, or when its run ends, is cancelled, or pauses. The place is handed on at once, so a step of a paused or cancelled run that is still finishing can overlap with the next run in. A resumed run goes ahead of the queue and takes back every place it held, in every pool, all at once; until they are all free it holds none of them and shows as **Queued**.
+
+`limit: 1` makes it a lock. When calls on the same pool name ask for different limits, a call goes in only while the pool holds fewer runs than its own limit and fewer than the smallest limit of those already inside, and nobody who asked after it goes in first. So a `limit: 1` call always runs alone, but it waits for whoever is inside to finish, two `limit: 2` calls included.
+
+A run can hold several places in one pool by calling `within` side by side, as in `Effect.all`. Calling `within` for a pool from inside that same pool pauses the run with an error, because it could end up waiting for itself; so does `within` on the workflow's own name when it has a `concurrency`. A run that `invoke`s another while holding a place the other needs can still wait forever, so keep `invoke` out of a lock the invoked workflow takes. Step names starting with `@pool:` are kept for the steps that queue; a step or wait of your own named that way pauses its run with an error.
+
+To cap whole runs, give the workflow `concurrency: 4` in its options: its runs share a pool named after the workflow, and each keeps its place until it ends, `onEnd` included.
+
## Triggers
- **Schedules:** `every` runs on an interval, starting one interval after the workflow loads; `daily` runs at a local time of day (a time missed by more than 10 minutes while the server is down is skipped).
diff --git a/evals/workflow-authoring/grade.ts b/evals/workflow-authoring/grade.ts
index c817da2130bde..466ab2cd0f631 100644
--- a/evals/workflow-authoring/grade.ts
+++ b/evals/workflow-authoring/grade.ts
@@ -14,6 +14,7 @@ import * as Stream from "effect/Stream";
import WorkflowsMigration from "../../apps/server/src/persistence/Migrations/110_Workflows.ts";
import WorkflowRunTagsMigration from "../../apps/server/src/persistence/Migrations/115_WorkflowRunTags.ts";
import WorkflowMailSenderMigration from "../../apps/server/src/persistence/Migrations/117_WorkflowMailSender.ts";
+import WorkflowPoolsMigration from "../../apps/server/src/persistence/Migrations/118_WorkflowPools.ts";
import type { WorkflowDefinition } from "../../apps/server/src/workflows/workflow.ts";
import {
type AgentResult,
@@ -80,6 +81,7 @@ const world = Effect.fn("gradeWorkflow.world")(function* (
WorkflowsMigration.pipe(
Effect.andThen(WorkflowRunTagsMigration),
Effect.andThen(WorkflowMailSenderMigration),
+ Effect.andThen(WorkflowPoolsMigration),
),
database,
);
diff --git a/packages/client-runtime/src/workflows.ts b/packages/client-runtime/src/workflows.ts
index 0d582b5ea237d..99a2b485231e4 100644
--- a/packages/client-runtime/src/workflows.ts
+++ b/packages/client-runtime/src/workflows.ts
@@ -436,6 +436,14 @@ export function workflowRunState(
tone: "quiet",
};
}
+ if (detail.startsWith("queue ")) {
+ return {
+ word: resolve(
+ msg("Queued", { $context: "workflow run status: it waits for a free place" }),
+ ),
+ tone: "quiet",
+ };
+ }
// Something below it holds it up; say that, not that it idles.
if (node.children.some(needsPerson)) return input;
return { word: resolve(msg("Waiting", { $context: "workflow run status" })), tone: "quiet" };
@@ -487,6 +495,9 @@ export function workflowRunNow(node: WorkflowRunNode, resolve: MFunctionType = m
if (detail.startsWith("sleep ")) {
return resolve(msg("Sleeping at {step}", { step: detail.slice(6) }));
}
+ if (detail.startsWith("queue ")) {
+ return resolve(msg("Queued for {pool}", { pool: detail.slice(6) }));
+ }
if (below.some((child) => child.run.endedAt === null)) {
const open = below.filter((child) => child.run.endedAt === null);
return open.length === 1
@@ -537,6 +548,8 @@ export interface WorkflowBeat {
readonly result: WorkflowStep["result"];
/** What an agent said in closing, when its result is data. */
readonly said: string | null;
+ /** For a step queued for a place in a pool, how many are ahead of it. */
+ readonly ahead: number | undefined;
readonly startMs: number;
/** When it ended, or `nowMs` while it is under way. */
readonly endMs: number;
@@ -607,8 +620,9 @@ export function buildWorkflowTimeline(input: {
const stepStart = Date.parse(step.startedAt);
const stepEnd = step.endedAt === null ? nowMs : Date.parse(step.endedAt);
const childRun = step.kind === "wait" ? (childByStep.get(step.name) ?? null) : null;
+ // A place given at once is bookkeeping too; a wait for one is a beat.
const isBeat =
- step.kind !== "step" ||
+ (step.kind !== "step" && step.kind !== "queue") ||
step.status !== "completed" ||
step.attempts > 1 ||
stepEnd - stepStart >= QUICK_STEP_MS;
@@ -625,6 +639,7 @@ export function buildWorkflowTimeline(input: {
detail: step.detail,
result: step.result,
said: step.said,
+ ahead: step.ahead,
startMs: stepStart,
endMs: Math.max(stepStart, stepEnd),
thread:
diff --git a/packages/contracts/src/workflow.ts b/packages/contracts/src/workflow.ts
index 90585b0372e3c..e211d53671d3e 100644
--- a/packages/contracts/src/workflow.ts
+++ b/packages/contracts/src/workflow.ts
@@ -44,8 +44,8 @@ export type WorkflowRun = typeof WorkflowRun.Type;
export const WorkflowStep = Schema.Struct({
name: Schema.String,
- // A sleep's `detail` is when it wakes, as an ISO time.
- kind: Schema.Literals(["step", "wait", "agent", "ask", "sleep"]),
+ // A sleep's `detail` is when it wakes, as an ISO time. A `queue` step waits for a place in a pool.
+ kind: Schema.Literals(["step", "wait", "agent", "ask", "sleep", "queue"]),
status: Schema.Literals(["running", "completed", "failed"]),
attempts: Schema.Number,
detail: Schema.NullOr(Schema.String),
@@ -57,6 +57,8 @@ export const WorkflowStep = Schema.Struct({
result: Schema.NullOr(Schema.Json),
/** What an agent said in closing, when its result is data and not that reply. */
said: Schema.NullOr(Schema.String),
+ /** For a `queue` step still waiting, how many asked for a place in its pool before it. */
+ ahead: Schema.optional(Schema.Number),
startedAt: Schema.String,
endedAt: Schema.NullOr(Schema.String),
});
diff --git a/skills/t3-workflows/SKILL.md b/skills/t3-workflows/SKILL.md
index b493d22d19c34..3d30593dd59b2 100644
--- a/skills/t3-workflows/SKILL.md
+++ b/skills/t3-workflows/SKILL.md
@@ -60,7 +60,7 @@ property of `T3`: take what you use at the top of the file, as the quick start d
(`const { workflow, step, daily } = T3;`), or write `T3.step(…)` in full. A bare `daily(…)` or
`step(…)` without that line is a `ReferenceError`.
-- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke`
+- **Definitions & body**: `workflow`, `step`, `agent`, `ask`, `wait`, `sleep`, `title`, `stop`, `skip`, `invoke`, `within`
- **Inside `step` / `onEnd` only**: `store`, `signal`, `signalAll`, `start`, `runs`, `cancel`
- **Trackers & hosts**: `issues`, `pullRequests` (triggers, step calls, and `pullRequests.wait` in the body)
- **Triggers**: `every`, `daily`, `webhook`
@@ -93,6 +93,7 @@ Schema.Record(Schema.String, Schema.Number); // two arguments, not an object
| `triggers` | No | Array of triggers that start runs automatically. |
| `resumeAfter` | No | Durations to wait before auto-resuming a paused run. Defaults to `["5 minutes", "20 minutes", "80 minutes"]`. The server checks about every 15 seconds, so shorter waits act as 15 seconds. |
| `asks` | No | The kinds of question it asks, each with a label: `{ feature: "Feature wanted?" }`. An `ask` names one as its `kind`; a question of a kind not listed here shows under Other. |
+| `concurrency` | No | At most this many runs of the workflow at once; later ones queue (see Pools and limits). |
| `onEnd` | No | `(payload, { id, outcome, reason }) => Effect`: cleanup hook run once when the run ends. |
The body is `Effect.fn(function* (payload, run) { … })`, where `run.id` is the run's id. Use `yield*` on every primitive.
@@ -216,6 +217,41 @@ workflow(
End subject keys with a separator (e.g. `issue/412/`), so `runs({ workflow: fix, keyPrefix: "issue/412/" })` does not match `issue/4120`.
+## Pools and limits
+
+`within(pool, { limit }, body)` runs `body` (one call, or an `Effect.gen` of several) holding one of `limit` places in the named pool, and returns what `body` returns. A pool is shared by every run of every workflow on the server. When all places are taken, the call waits in arrival order and its run shows as queued (`waiting`, detail `queue `). The place is given back when `body` ends or fails, and when the run ends, is cancelled or pauses. A resumed run goes ahead of the queue and takes back every place it held, in every pool, all at once; until they are all free it holds none and shows as queued.
+
+`limit: 1` is a lock. When calls on one pool name ask for different limits, a call goes in only while the pool holds fewer than its own limit and fewer than the smallest limit of those already inside, and nobody who asked later goes in ahead of it. So a `limit: 1` call always runs alone, but it waits for whoever is inside, two `limit: 2` calls included. Prefer one limit per pool name.
+
+A run holds several places in one pool only by calling `within` side by side (`Effect.all` over several `within` calls). Never call `within` for a pool from inside that same pool, or for the workflow's own name when it has a `concurrency`: the run could wait for itself, so it pauses with an error instead. A run that `invoke`s another while holding a place the other needs is not caught and waits forever; keep `invoke` outside such a `within`. Step and wait names starting with `@pool:` are reserved for the queue steps (`@pool:`, then `@pool:#2` for a second call in the same run) and pause the run if you use one. A queue step cannot be signalled: `signal` to it is refused.
+
+`concurrency: N` in the workflow's options does the same for whole runs: its runs, across versions, share a pool named after the workflow, and each keeps its place until it ends, `onEnd` included.
+
+```ts
+const { workflow, within, agent, step } = T3;
+
+workflow(
+ "release",
+ { version: 1, payload: Schema.Struct({ branch: Schema.String }), concurrency: 8 },
+ Effect.fn(function* (payload) {
+ const built = yield* within(
+ "builders",
+ { limit: 2 },
+ agent("build", { project: "/home/me/app", brief: `Build ${payload.branch}.` }),
+ );
+ yield* within(
+ "deploy",
+ { limit: 1 },
+ step("deploy", { returns: Schema.Void }, deploy(built.value)),
+ );
+ }),
+);
+```
+
+(`deploy` is your own Effect helper.)
+
+A paused or cancelled run gives its place back at once, so anything of it still finishing, such as the other calls of an `Effect.all` inside the `within`, can overlap with the next holder.
+
## Store and signals
`store` holds durable key-value state shared across all workflows on the server (cursors, switches, counters, queues). Call `store`, `signal`, and `signalAll` **only inside `step` or `onEnd`**—never directly in the body.
From 2fbb071e0c031774cba7f6aa15110333c95d1d40 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 08:57:10 +0100
Subject: [PATCH 018/235] fix(pi): submit custom answers that match the hidden
option (#42670)
Co-authored-by: Julius Marminge
---
packages/provider-pi/src/server/adapter.test.ts | 12 ++++++++++--
packages/provider-pi/src/server/adapter.ts | 9 +++++----
2 files changed, 15 insertions(+), 6 deletions(-)
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index 99adf0393e539..368879d12ddc0 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -5684,7 +5684,7 @@ describe("PiAdapterV2", () => {
});
// The extension reads a bare number sent as the select's value as that option.
yield* answerWithCustomText("ui-ask", "2");
- yield* answerWithCustomText("ui-ask-parallel", "5");
+ yield* answerWithCustomText("ui-ask-parallel", "3. Type something.");
// Parallel dialogs can arrive before the follow-up input, including a multi-select of the
// same question, which the extension asks as an input with a non-empty placeholder.
const multiSelectTitle = `How many replicas?\n\n${lines.join("\n")}\n\nEnter the numbers of all that apply.`;
@@ -5715,7 +5715,7 @@ describe("PiAdapterV2", () => {
assert.equal((yield* takeWaitingRequest()).title, "Anything else?");
for (const [id, value] of [
["ui-custom", "2"],
- ["ui-custom-parallel", "5"],
+ ["ui-custom-parallel", "3. Type something."],
]) {
yield* fake.emit({
type: "extension_ui_request",
@@ -5724,6 +5724,14 @@ describe("PiAdapterV2", () => {
title: followUpTitle,
placeholder: "",
});
+ const nextTitle = `Next question after ${id}?`;
+ yield* fake.emit({
+ type: "extension_ui_request",
+ id: `next-${id}`,
+ method: "input",
+ title: nextTitle,
+ });
+ assert.equal((yield* takeWaitingRequest()).questions[0]?.id, `next-${id}`);
const inputResponse = yield* fake.takeRequest("extension_ui_response");
assert.deepEqual({ id: inputResponse["id"], value: inputResponse["value"] }, { id, value });
}
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index 3195b6c62d2a1..dd5ea4855baec 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -425,7 +425,7 @@ interface PendingPiPrompt {
* picks the select's last "Type something." line and answers the input dialog that follows.
*/
interface PiCustomAnswerRoute {
- readonly lines: ReadonlyArray;
+ readonly optionLines: ReadonlyArray;
readonly sentinel: string;
readonly followUpTitlePrefix: string;
}
@@ -3838,7 +3838,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
route !== undefined &&
typeof response["value"] === "string" &&
response["value"].trim().length > 0 &&
- !route.lines.includes(response["value"])
+ !route.optionLines.includes(response["value"])
) {
customAnswerFollowUps.set(route.followUpTitlePrefix, [
...(customAnswerFollowUps.get(route.followUpTitlePrefix) ?? []),
@@ -4822,6 +4822,7 @@ function piAskUserSingleSelectQuestion(
if (!options.every((option, index) => lines[index] === rpivOptionLine(option, index))) {
continue;
}
+ const optionLines = lines.slice(0, -1);
return {
question: {
id: questionId,
@@ -4838,9 +4839,9 @@ function piAskUserSingleSelectQuestion(
},
// The follow-up repeats the option lines; only its trailing instruction is localized.
customAnswerRoute: {
- lines,
+ optionLines,
sentinel,
- followUpTitlePrefix: `${prefix}${text}\n\n${lines.slice(0, -1).join("\n")}\n\n`,
+ followUpTitlePrefix: `${prefix}${text}\n\n${optionLines.join("\n")}\n\n`,
},
};
}
From 072611f65fc3b77f13909ce451e87c3e265d8b05 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 02:04:50 -0600
Subject: [PATCH 019/235] fix(web): a 9.996 KB file reads "10.0 KB", not "10.00
KB" (#42682)
Co-authored-by: Julius Marminge
---
apps/web/src/lib/formatBytes.test.ts | 2 ++
apps/web/src/lib/formatBytes.ts | 6 +++++-
2 files changed, 7 insertions(+), 1 deletion(-)
diff --git a/apps/web/src/lib/formatBytes.test.ts b/apps/web/src/lib/formatBytes.test.ts
index 5b5d948bb59c2..82de7bb7267c4 100644
--- a/apps/web/src/lib/formatBytes.test.ts
+++ b/apps/web/src/lib/formatBytes.test.ts
@@ -8,6 +8,8 @@ describe("formatBytes", () => {
[1_023, "1023 B"],
[1_024, "1.00 KB"],
[1_536, "1.50 KB"],
+ [10_235, "10.0 KB"],
+ [102_350, "100 KB"],
[1_047_552, "1023 KB"],
[1_048_576, "1.00 MB"],
[5 * 1_024 ** 4, "5.00 TB"],
diff --git a/apps/web/src/lib/formatBytes.ts b/apps/web/src/lib/formatBytes.ts
index fe6de1cdb2a12..1c1e1111f0d9e 100644
--- a/apps/web/src/lib/formatBytes.ts
+++ b/apps/web/src/lib/formatBytes.ts
@@ -1,5 +1,9 @@
function formatScaled(value: number): string {
- return value.toFixed(value >= 100 ? 0 : value >= 10 ? 1 : 2);
+ const twoDecimals = value.toFixed(2);
+ if (Number(twoDecimals) < 10) return twoDecimals;
+ const oneDecimal = value.toFixed(1);
+ if (Number(oneDecimal) < 100) return oneDecimal;
+ return value.toFixed(0);
}
export function formatBytes(value: number): string {
From a05a8518f9078b1587ae82c12a010e62d0114520 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 09:09:27 +0100
Subject: [PATCH 020/235] fix(pi): preview images read with an @-prefixed path
(#42678)
Co-authored-by: Julius Marminge
---
packages/provider-pi/src/server/adapter.test.ts | 2 +-
packages/provider-pi/src/server/adapter.ts | 5 ++++-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index 368879d12ddc0..b8b27ae299393 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -3478,7 +3478,7 @@ describe("PiAdapterV2", () => {
const cases = [
{
toolName: "read",
- args: { path: "/workspace/screens/shot.png" },
+ args: { path: "@/workspace/screens/shot.png" },
result: { content, structuredContent: { ...image, note } },
expected: { content },
},
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index dd5ea4855baec..93aa5fdd77490 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -1490,9 +1490,12 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
}
}
const output = piToolOutput(resultRecord, toolName);
+ // Pi strips @ only at the start of the raw argument, before preview trimming.
const readPath =
toolName === "read"
- ? (recordString(args, "path") ?? recordString(args, "file_path"))?.trim()
+ ? (recordString(args, "path") ?? recordString(args, "file_path"))
+ ?.replace(/^@/, "")
+ .trim()
: undefined;
const viewedImagePath =
readPath &&
From 9eaac040dedb154405dd0ee24230e5ca35198111 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 00:36:21 -0800
Subject: [PATCH 021/235] test(web): sidebar shift guard tests no longer race
the click against fake time (#42697)
---
.../Sidebar.shiftGuard.browser.test.ts | 37 ++++++++++++-------
1 file changed, 24 insertions(+), 13 deletions(-)
diff --git a/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts b/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts
index 23210bea89cc8..1c32872a9fc5a 100644
--- a/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts
+++ b/apps/web/src/components/Sidebar.shiftGuard.browser.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { userEvent } from "vite-plus/test/browser";
-import { fakeTimers, render } from "../../test/render";
+import { render } from "../../test/render";
import { createSidebarShiftGuard } from "./Sidebar.shiftGuard";
function mountList(container: HTMLElement, names: readonly string[]) {
@@ -31,6 +31,17 @@ function mountList(container: HTMLElement, names: readonly string[]) {
};
}
+// Fake timers would not do: the browser runner advances them with real time while a userEvent
+// command runs, so a slow click could outlast the guard's window before its press lands.
+function manualClock() {
+ let now = 0;
+ const spy = vi.spyOn(performance, "now").mockImplementation(() => now);
+ return {
+ advance: (ms: number) => void (now += ms),
+ [Symbol.dispose]: () => spy.mockRestore(),
+ };
+}
+
// userEvent cannot hold the mouse, so `act` runs inside the real press, after the guard saw it.
function duringPress(act: () => void) {
const listener = () => act();
@@ -44,14 +55,14 @@ describe("sidebar shift guard", () => {
it("drops a press on a row that slid up on its own, then accepts it after the delay", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using clock = manualClock();
list.remove("A");
list.guard.update();
await userEvent.click(list.button("B"));
expect(list.pressed).toEqual([]);
- vi.advanceTimersByTime(500);
+ clock.advance(500);
await userEvent.click(list.button("B"));
expect(list.pressed).toEqual(["B"]);
});
@@ -59,7 +70,7 @@ describe("sidebar shift guard", () => {
it("keeps rows that did not move, or barely moved, clickable", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using _clock = manualClock();
list.remove("C");
list.button("A").closest("ul")!.style.paddingTop = "2px";
@@ -72,7 +83,7 @@ describe("sidebar shift guard", () => {
it("keeps rows clickable when an empty list first fills", async () => {
await using screen = await render(null);
using list = mountList(screen.container, []);
- using _clock = fakeTimers();
+ using _clock = manualClock();
list.add("A");
list.add("B");
@@ -84,7 +95,7 @@ describe("sidebar shift guard", () => {
it("lets the user act on the row their own press moved", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using _clock = manualClock();
list.button("A").addEventListener("click", () => {
list.remove("A");
list.guard.update();
@@ -98,7 +109,7 @@ describe("sidebar shift guard", () => {
it("clears an earlier mark when the user's own input moves the row again", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C", "D"]);
- using _clock = fakeTimers();
+ using _clock = manualClock();
list.remove("A");
list.guard.update();
@@ -114,7 +125,7 @@ describe("sidebar shift guard", () => {
const field = document.createElement("input");
screen.container.append(field);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using _clock = manualClock();
field.focus();
await userEvent.keyboard("x");
@@ -127,7 +138,7 @@ describe("sidebar shift guard", () => {
it("keeps a held press dropped until its release, whatever happens before", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using clock = manualClock();
list.remove("A");
list.guard.update();
@@ -136,7 +147,7 @@ describe("sidebar shift guard", () => {
const other = { bubbles: true, pointerId: 9 };
screen.container.dispatchEvent(new PointerEvent("pointerdown", other));
screen.container.dispatchEvent(new PointerEvent("pointerup", other));
- vi.advanceTimersByTime(1_000);
+ clock.advance(1_000);
});
await userEvent.click(list.button("B"));
expect(list.pressed).toEqual([]);
@@ -145,7 +156,7 @@ describe("sidebar shift guard", () => {
it("lets keyboard activation through while a dropped press is held", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using _clock = manualClock();
list.remove("A");
list.guard.update();
@@ -166,14 +177,14 @@ describe("sidebar shift guard", () => {
it("ends a dropped press the browser cancels", async () => {
await using screen = await render(null);
using list = mountList(screen.container, ["A", "B", "C"]);
- using _clock = fakeTimers();
+ using clock = manualClock();
list.remove("A");
list.guard.update();
const touch = { bubbles: true, pointerId: 9, pointerType: "touch" };
list.button("B").dispatchEvent(new PointerEvent("pointerdown", touch));
list.button("B").dispatchEvent(new PointerEvent("pointercancel", touch));
- vi.advanceTimersByTime(500);
+ clock.advance(500);
await userEvent.click(list.button("B"));
expect(list.pressed).toEqual(["B"]);
});
From 9dc807ffdec69bd04929203f18fdaa3e6ba576db Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 00:38:53 -0800
Subject: [PATCH 022/235] fix(server): a run paused while a wake is delivered
stays paused (#42673)
---
apps/server/src/workflows/Workflows.test.ts | 101 ++++++++++++++++++++
apps/server/src/workflows/workflow.ts | 8 ++
2 files changed, 109 insertions(+)
diff --git a/apps/server/src/workflows/Workflows.test.ts b/apps/server/src/workflows/Workflows.test.ts
index 78939e8df2c34..abb8bedb7aaf9 100644
--- a/apps/server/src/workflows/Workflows.test.ts
+++ b/apps/server/src/workflows/Workflows.test.ts
@@ -2575,6 +2575,107 @@ it.effect("a watcher sees a question leave when it is withdrawn while its run is
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
);
+it.effect(
+ "a run that pauses while an answer is being delivered gets the answer on its resume",
+ () =>
+ Effect.gen(function* () {
+ // Between the wake's look at the run and its delivery, `bad` fails and pauses the run.
+ let armed: string | undefined;
+ let failBad: Effect.Effect = Effect.void;
+ const paused = yield* Deferred.make();
+ const store = Layer.effect(
+ WorkflowStore.WorkflowStore,
+ Effect.map(WorkflowStore.make, (real) =>
+ WorkflowStore.WorkflowStore.of({
+ ...real,
+ waitSignalled: (runId, ...rest) =>
+ Effect.tap(real.waitSignalled(runId, ...rest), (taken) =>
+ Effect.sync(() => void (taken ? (armed = runId) : undefined)),
+ ),
+ runPaused: (runId, ...rest) =>
+ Effect.andThen(real.runPaused(runId, ...rest), Deferred.succeed(paused, undefined)),
+ run: (runId) =>
+ Effect.flatMap(real.run(runId), (row) => {
+ if (armed !== runId) return Effect.succeed(row);
+ armed = undefined;
+ return Effect.as(Effect.andThen(failBad, Deferred.await(paused)), row);
+ }),
+ }),
+ ),
+ );
+ const { failures, latch, boot } = yield* harness(store);
+ failBad = Deferred.succeed(latch.bad, undefined).pipe(Effect.asVoid);
+ yield* Ref.set(failures, 1);
+ yield* boot(
+ Effect.gen(function* () {
+ const workflows = yield* Workflows.Workflows;
+ const { runId } = yield* workflows.start("doubting", {}, { idempotencyKey: "d1" });
+ yield* workflows.waitFor(
+ runId,
+ (run) => run.status === "waiting" && run.detail === "sure",
+ );
+ yield* workflows.answer(runId, "sure", { choice: "Yes" });
+ assert.equal((yield* workflows.waitFor(runId, status("paused"))).pauses, 1);
+ // The engine replays it for the wake, but its failed step waits for the resume.
+ // The resume runs `bad` again and delivers the answer the claim kept.
+ yield* workflows.resume(runId);
+ const done = yield* workflows.waitFor(runId, status("completed"));
+ assert.deepStrictEqual(done.result, "1 Yes");
+ }),
+ );
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+);
+
+it.effect("a step of a paused run waits for the resume, even when the engine replays it", () =>
+ Effect.gen(function* () {
+ // The row is paused while the engine still runs, as when a wake preempts a failing step.
+ let real: WorkflowStore.WorkflowStore["Service"] | undefined;
+ let workEnded = false;
+ const next = yield* Deferred.make<"looked" | "took">();
+ const store = Layer.effect(
+ WorkflowStore.WorkflowStore,
+ Effect.map(WorkflowStore.make, (made) => {
+ real = made;
+ return WorkflowStore.WorkflowStore.of({
+ ...made,
+ stepEnded: (runId, name, ...rest) =>
+ Effect.tap(made.stepEnded(runId, name, ...rest), () =>
+ Effect.sync(() => void (name === "work" ? (workEnded = true) : undefined)),
+ ),
+ run: (runId) =>
+ Effect.tap(made.run(runId), () =>
+ workEnded ? Deferred.succeed(next, "looked") : Effect.void,
+ ),
+ stepStarted: (runId, name, ...rest) =>
+ Effect.andThen(
+ name === "take" ? Deferred.succeed(next, "took") : Effect.void,
+ made.stepStarted(runId, name, ...rest),
+ ),
+ });
+ }),
+ );
+ const { counts, latch, boot } = yield* harness(store);
+ yield* boot(
+ Effect.gen(function* () {
+ const workflows = yield* Workflows.Workflows;
+ const { runId } = yield* workflows.start(
+ "owned",
+ { mode: "busy" },
+ { idempotencyKey: "p" },
+ );
+ yield* Deferred.await(latch.entered);
+ yield* real!.runPaused(runId, "work: a sibling failed");
+ yield* Deferred.succeed(latch.release, undefined);
+ // The next step looks at the run before it starts, and finds it paused.
+ assert.equal(yield* Deferred.await(next), "looked");
+ yield* workflows.resume(runId);
+ assert.equal((yield* workflows.waitFor(runId, status("completed"))).status, "completed");
+ assert.equal((yield* Ref.get(counts)).take, 1);
+ }),
+ );
+ }).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
+);
+
it("tags refuses a list with a gap in it", () => {
// The same list `tags([, "pr"])` makes: a first entry that was never set.
const gapped = new Array(2);
diff --git a/apps/server/src/workflows/workflow.ts b/apps/server/src/workflows/workflow.ts
index 191163d501334..ecf109c9bbe1c 100644
--- a/apps/server/src/workflows/workflow.ts
+++ b/apps/server/src/workflows/workflow.ts
@@ -196,6 +196,13 @@ export const journaled = (
) => {
const codec = Schema.toCodecJson(returns);
const encodable = Schema.encodeEffect(codec);
+ // A wake can preempt the run while a failed step is still finishing, and the engine then
+ // replays the paused run and runs the step again. Only a resume, which unpauses first, may.
+ const unlessPaused = Effect.flatMap(run.store.run(run.runId), (row) =>
+ row?.status === "paused"
+ ? Effect.fail(new StepFailed({ step: name, reason: "The run is paused." }))
+ : Effect.void,
+ );
return Activity.make({
name: action,
success: returns,
@@ -217,6 +224,7 @@ export const journaled = (
Effect.andThen(run.store.runPaused(run.runId, error.message, held), run.placesFreed),
),
),
+ (attempt) => Effect.andThen(unlessPaused, attempt),
),
});
};
From d41f231a1f65661cda829f3e5f97a9075721dda3 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 09:39:09 +0100
Subject: [PATCH 023/235] fix(pi): rewind removes discarded prompts after
returning to a session (#42662)
Co-authored-by: Julius Marminge
---
.../provider-pi/src/server/adapter.test.ts | 145 +++++++++++++++++-
packages/provider-pi/src/server/adapter.ts | 99 +++++++++---
2 files changed, 225 insertions(+), 19 deletions(-)
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index b8b27ae299393..45cb7c08eb22e 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -163,6 +163,10 @@ interface FakePi {
readonly emit: (record: PiRpcRecord, chunkBytes?: number) => Effect.Effect;
readonly takeRequest: (type: string) => Effect.Effect;
readonly queueEntries: (data: unknown) => void;
+ readonly setSessionEntries: (
+ entries: ReadonlyArray>,
+ forkFile: string,
+ ) => void;
readonly queueMessages: (data: unknown) => void;
readonly vetoNextSwitch: () => void;
readonly failNextFork: () => void;
@@ -231,6 +235,8 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* (
const stdout = yield* Queue.unbounded();
const requests = yield* Queue.unbounded();
const entriesQueue: Array = [];
+ let sessionEntries: ReadonlyArray> | undefined;
+ let forkFile: string | undefined;
const messagesQueue: Array = [];
const stateQueue: Array> = [];
const statsQueue: Array = [];
@@ -353,7 +359,13 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* (
return { ...base, data: { cancelled } };
}
case "get_entries":
- return { ...base, data: entriesQueue.shift() ?? { entries: [], leafId: null } };
+ return {
+ ...base,
+ data: entriesQueue.shift() ?? {
+ entries: sessionEntries ?? [],
+ leafId: sessionEntries?.at(-1)?.id ?? null,
+ },
+ };
case "get_messages":
return { ...base, data: messagesQueue.shift() ?? { messages: [] } };
case "get_session_stats":
@@ -363,6 +375,13 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* (
failFork = false;
return { ...base, success: false, error: "Invalid entry ID for forking" };
}
+ if (sessionEntries !== undefined && forkFile !== undefined) {
+ const index = sessionEntries.findIndex((entry) => entry.id === record["entryId"]);
+ if (index === -1)
+ return { ...base, success: false, error: "Invalid entry ID for forking" };
+ sessionEntries = sessionEntries.slice(0, index);
+ sessionFile = forkFile;
+ }
serviceTier = null;
return { ...base, data: { text: "Hello pi", cancelled: false } };
case "clear_queue":
@@ -471,6 +490,10 @@ const makeFakePiWithResponses = Effect.fnUntraced(function* (
emit,
takeRequest,
queueEntries: (data) => entriesQueue.push(data),
+ setSessionEntries: (entries, file) => {
+ sessionEntries = entries;
+ forkFile = file;
+ },
queueMessages: (data) => messagesQueue.push(data),
deferNextState: (started) => {
deferState = true;
@@ -4825,6 +4848,126 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
+ it.effect.each([
+ {
+ checkpoint: "strong",
+ ordinal: 2,
+ handoff: "command",
+ returnedPrompt: false,
+ discarded: true,
+ },
+ { checkpoint: "strong", ordinal: 2, handoff: "prompt", returnedPrompt: true, discarded: true },
+ {
+ checkpoint: "command",
+ ordinal: 2,
+ handoff: "prompt",
+ returnedPrompt: false,
+ discarded: false,
+ },
+ { checkpoint: "weak", ordinal: 2, handoff: "prompt", returnedPrompt: false, discarded: false },
+ {
+ checkpoint: "command",
+ ordinal: 1,
+ handoff: "prompt",
+ returnedPrompt: false,
+ discarded: false,
+ },
+ { checkpoint: "weak", ordinal: 1, handoff: "prompt", returnedPrompt: true, discarded: true },
+ ] as const)("restores the Pi checkpoint after a session round trip %j", (scenario) =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ const { runtime } = yield* openRuntime(fake);
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ const ref = (nativeId: string, strength: "strong" | "weak" = "strong") => ({
+ driver: PI_PROVIDER,
+ nativeId,
+ strength,
+ });
+ const sessionFile = providerThread.nativeThreadRef!.nativeId!;
+ const forkFile = "/fake/rewound.jsonl";
+ const turn = (
+ ordinal: number,
+ nativeTurnRef: OrchestrationV2ProviderTurn["nativeTurnRef"],
+ file = sessionFile,
+ ): OrchestrationV2ProviderTurn => ({
+ id: ProviderTurnId.make(`turn-${ordinal}`),
+ providerThreadId: providerThread.id,
+ nodeId: NodeId.make(`node-${ordinal}`),
+ runAttemptId: null,
+ nativeTurnRef,
+ nativeThreadRef: ref(file),
+ ordinal,
+ status: "completed",
+ startedAt: at(ordinal * 50 - 50),
+ completedAt: at(ordinal * 50),
+ });
+ const target = turn(
+ scenario.ordinal,
+ scenario.checkpoint === "strong"
+ ? ref("u2")
+ : scenario.checkpoint === "weak"
+ ? ref("uncaptured", "weak")
+ : null,
+ );
+ const retained =
+ scenario.ordinal === 1 || scenario.checkpoint === "command"
+ ? TURN_ONE_ENTRIES
+ : [
+ ...TURN_ONE_ENTRIES,
+ sessionMessage("u2", "a1b", "user", 60),
+ sessionMessage("a2", "u2", "assistant", 80),
+ ];
+ const retainedHead = retained.at(-1)!.id;
+ const entries = [
+ ...retained,
+ ...(scenario.discarded
+ ? [
+ sessionMessage("discarded", retainedHead, "user", 110),
+ sessionMessage("discarded-answer", "discarded", "assistant", 120),
+ ]
+ : []),
+ ...(scenario.returnedPrompt ? [sessionMessage("u5", "discarded-answer", "user", 210)] : []),
+ ];
+ fake.setSessionEntries(entries, forkFile);
+ const restored = yield* runtime.rollbackThread({
+ providerThread,
+ target: {
+ type: "provider_turn",
+ checkpointId: CheckpointId.make("checkpoint-1"),
+ appRunOrdinal: target.ordinal,
+ providerTurn: target,
+ },
+ providerThreadTurns: [
+ ...(target.ordinal === 2 ? [turn(1, ref("u1"))] : []),
+ target,
+ turn(
+ target.ordinal + 1,
+ scenario.handoff === "prompt" ? ref("away") : null,
+ "/fake/other.jsonl",
+ ),
+ turn(target.ordinal + 2, null, "/fake/clone.jsonl"),
+ turn(target.ordinal + 3, null),
+ ...(scenario.returnedPrompt ? [turn(target.ordinal + 4, ref("u5"))] : []),
+ ],
+ });
+ const requests = fake.allRequests();
+ assert.isFalse(requests.some((request) => request.type === "switch_session"));
+ assert.deepEqual(
+ requests.filter((request) => request.type === "fork").map((request) => request.entryId),
+ scenario.discarded ? ["discarded"] : [],
+ );
+ assert.equal(
+ restored.providerThread.nativeThreadRef?.nativeId,
+ scenario.discarded ? forkFile : sessionFile,
+ );
+ assert.equal(restored.providerThread.nativeConversationHeadRef?.nativeId, retainedHead);
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
it.effect("rolls back a persisted thread on a fresh runtime after its session was released", () =>
Effect.gen(function* () {
const previousFake = yield* makeFakePi;
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index 93aa5fdd77490..1ce21cfb7c903 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -4035,6 +4035,10 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
const isCurrentFile = (file: string) =>
currentFile != null &&
path.resolve(cwd, file) === path.resolve(cwd, currentFile);
+ const targetPath =
+ targetFile === undefined ? undefined : path.resolve(cwd, targetFile);
+ const isTargetFile = (file: string | null | undefined) =>
+ file != null && path.resolve(cwd, file) === targetPath;
const boundaryFile =
firstBoundary.type === "nothing"
? undefined
@@ -4048,7 +4052,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
if (
targetFile !== undefined &&
boundaryFile != null &&
- path.resolve(cwd, boundaryFile) !== path.resolve(cwd, targetFile)
+ !isTargetFile(boundaryFile)
) {
// A previous fork can carry the checkpoint into the session with the discard boundary.
const listing =
@@ -4168,17 +4172,26 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
);
}
}
- let forkEntryId: string | undefined;
- if (boundary.type !== "nothing") {
- forkEntryId = yield* piForkEntry(
- boundary,
- rollbackInput.providerThread.createdAt,
- switchedTo === undefined ? readCurrentEntries : readEntries,
- );
- } else if (switchedTo === undefined && recoveredLegacySource === undefined) {
+ const leftTargetFile =
+ target !== null &&
+ isTargetFile(sourceFile) &&
+ rollbackInput.providerThreadTurns.some((turn) => {
+ const file = turn.nativeThreadRef?.nativeId;
+ return turn.ordinal > target.ordinal && file != null && !isTargetFile(file);
+ });
+ const verifySource =
+ leftTargetFile || (boundary.type === "nothing" && switchedTo !== undefined);
+ if (
+ boundary.type === "nothing" &&
+ !verifySource &&
+ recoveredLegacySource === undefined
+ ) {
return piThreadSnapshot(state.providerThread);
- } else {
- const listing = piSessionListing(yield* request({ type: "get_entries" }));
+ }
+ let forkEntryId: string | undefined;
+ let sourceEntries = switchedTo === undefined ? readCurrentEntries : readEntries;
+ if (recoveredLegacySource !== undefined) {
+ const listing = piSessionListing(yield* sourceEntries);
const completedAt = target?.completedAt;
const retained =
listing !== null && targetId !== undefined
@@ -4191,18 +4204,68 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
if (
listing === null ||
retained === undefined ||
- (recoveredLegacySource !== undefined &&
- !piSameHistory(
- listing,
- retained.headId,
- recoveredLegacySource.listing,
- recoveredLegacySource.retained.headId,
- ))
+ !piSameHistory(
+ listing,
+ retained.headId,
+ recoveredLegacySource.listing,
+ recoveredLegacySource.retained.headId,
+ )
)
return yield* protocolError(
"Pi rollback could not verify the retained session head",
);
forkEntryId = retained.forkEntryId;
+ } else if (verifySource) {
+ const data = yield* sourceEntries;
+ sourceEntries = Effect.succeed(data);
+ const listing = piSessionListing(data);
+ // Without a captured checkpoint prompt, verify back to an earlier retained
+ // prompt in the same file or to the root if none was captured.
+ const anchorId =
+ targetId ??
+ piTurnEntryId(
+ rollbackInput.providerThreadTurns
+ .filter(
+ (turn) =>
+ target !== null &&
+ turn.ordinal < target.ordinal &&
+ isTargetFile(turn.nativeThreadRef?.nativeId) &&
+ piTurnEntryId(turn) !== undefined,
+ )
+ .sort((a, b) => b.ordinal - a.ordinal)[0],
+ ) ??
+ null;
+ const walk =
+ listing !== null && (anchorId === null || listing.entries.has(anchorId))
+ ? walkPiBranch(listing.entries, listing.leafId, anchorId)
+ : null;
+ if (listing === null || walk?.reachedStop !== true)
+ return yield* protocolError(
+ "Pi rollback could not verify the retained session head",
+ );
+ // A handoff can leave a prompt before the next recorded turn in this file.
+ for (const id of [...walk.userEntryIds].reverse()) {
+ if (boundary.type === "entry" && id === boundary.entryId) {
+ forkEntryId = id;
+ break;
+ }
+ const timestamp = listing.entries.get(id)?.timestamp;
+ if (timestamp == null || target?.completedAt == null)
+ return yield* protocolError(
+ "Pi rollback could not verify the retained session head",
+ );
+ if (timestamp >= DateTime.toEpochMillis(target.completedAt)) {
+ forkEntryId = id;
+ break;
+ }
+ }
+ }
+ if (forkEntryId === undefined && boundary.type !== "nothing") {
+ forkEntryId = yield* piForkEntry(
+ boundary,
+ rollbackInput.providerThread.createdAt,
+ sourceEntries,
+ );
}
if (forkEntryId !== undefined) {
const forkData = yield* lifecycleRequest({
From b2f56cc0aa55f34ed94bec852e1f398ba4ca6aa3 Mon Sep 17 00:00:00 2001
From: Wout Stiens <71498452+StiensWout@users.noreply.github.com>
Date: Wed, 25 Nov 2026 09:41:39 +0100
Subject: [PATCH 024/235] fix(server): Claude imports keep questions after
quoted command output (#42674)
Co-authored-by: Julius Marminge
---
.../src/project/AgentSessionScanner.test.ts | 47 ++++++++++++++++++
.../server/src/project/AgentSessionScanner.ts | 49 +++++++++++++++++--
2 files changed, 92 insertions(+), 4 deletions(-)
diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts
index adc34b2348cb4..acda443fd58af 100644
--- a/apps/server/src/project/AgentSessionScanner.test.ts
+++ b/apps/server/src/project/AgentSessionScanner.test.ts
@@ -3687,6 +3687,53 @@ describe("parseAgentSessionTranscript", () => {
});
});
+ const parseClaudeUserTurns = (userTurns: ReadonlyArray) =>
+ AgentSessionScanner.parseAgentSessionTranscript({
+ contents: [
+ ...userTurns.map((content) => ({ type: "user", message: { role: "user", content } })),
+ { type: "assistant", message: { role: "assistant", content: "Here is what happened." } },
+ ]
+ .map((record) => encodeTranscriptRecord(record))
+ .join("\n"),
+ source: "claudeAgent",
+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),
+ fallbackSessionId: "62c057bb-b316-4b29-be2c-140090d71254",
+ lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
+ });
+
+ it.each([
+ "Enabled plan mode",
+ "/review\nreview",
+ ])("keeps a Claude question after quoted %s and names the thread after it", (quote) => {
+ const prompt = `${quote}\nWhy did this change?`;
+
+ expect(parseClaudeUserTurns([prompt])).toMatchObject({
+ title: "Why did this change?",
+ messages: [{ role: "user", text: prompt }, { role: "assistant" }],
+ });
+ });
+
+ it("keeps a Claude question after quoted output full of shell closing tags", () => {
+ const prompt = `${"".repeat(16_000)}\nWhy did this change?`;
+
+ expect(parseClaudeUserTurns([prompt])).toMatchObject({
+ title: "Why did this change?",
+ messages: [{ role: "user", text: prompt }, { role: "assistant" }],
+ });
+ });
+
+ it.each([
+ "\nfinished\n",
+ "\nfinished\n",
+ "\na1\ncompleted\n\nBash, Read",
+ ])("hides Claude output with trailing markup of its own (%s)", (output) => {
+ expect(
+ parseClaudeUserTurns([output, "What happened?"])
+ ?.messages.filter((message) => message.role === "user")
+ .map((message) => message.text),
+ ).toEqual(["What happened?"]);
+ });
+
it.each([
{ customTitles: ["Refactor auth module"], expected: "Refactor auth module" },
// Claude writes an empty customTitle when the user clears a rename.
diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts
index f45c8fcf2a838..0f492c6c04db3 100644
--- a/apps/server/src/project/AgentSessionScanner.ts
+++ b/apps/server/src/project/AgentSessionScanner.ts
@@ -420,10 +420,36 @@ function codexHistoryBase(records: ReadonlyArray) {
: undefined;
}
+// Where the run of sticky `block` matches at the start of `text` ends.
+function leadingBlocksEnd(text: string, block: RegExp): number {
+ let end = 0;
+ while (block.test(text)) {
+ end = block.lastIndex;
+ }
+ return end;
+}
+
// Claude Code records its own UI as user turns: slash commands, `!` shell runs and
// their output, task notifications. Keep what the user typed, as they typed it.
-const CLAUDE_UI_OUTPUT =
- /^(?:<(?:task-notification|local-command-stdout|local-command-stderr|local-command-caveat|bash-stdout|bash-stderr)>|\[Request interrupted by user(?: for tool use)?\]$)/;
+function claudeUiOutputEnd(text: string): number {
+ return leadingBlocksEnd(
+ text,
+ /<(local-command-stdout|local-command-stderr|local-command-caveat|bash-stdout|bash-stderr)>[\s\S]*?<\/\1>\s*/y,
+ );
+}
+
+// Shell payloads can print closing tags verbatim, so a complete envelope is
+// judged by its outer tags; prose after a quoted block stays visible.
+function isClaudeShellOutput(text: string): boolean {
+ if (text.startsWith("")) return text.endsWith("");
+ if (!text.startsWith("")) return false;
+ return (
+ text.endsWith("") ||
+ (text.endsWith("") && /<\/bash-stdout>\s*/.test(text))
+ );
+}
+
+const CLAUDE_COMMAND_BLOCK = /[\s\S]*?<\/command-\1>\s*/y;
/**
* A slash command as typed. Its arguments may name the thread; a bare command
@@ -431,6 +457,7 @@ const CLAUDE_UI_OUTPUT =
*/
function claudeCommand(text: string): { readonly text: string; readonly titleText: string } | null {
if (!/^/.test(text)) return null;
+ if (leadingBlocksEnd(text, CLAUDE_COMMAND_BLOCK) !== text.length) return null;
const name =
/([^<]*)<\/command-name>/.exec(text)?.[1]?.trim() ||
`/${/([^<]*)<\/command-message>/.exec(text)?.[1]?.trim() ?? ""}`;
@@ -440,10 +467,24 @@ function claudeCommand(text: string): { readonly text: string; readonly titleTex
/** What a Claude user turn shows the user typed, and the part of it that may name the thread. */
function claudeUserText(text: string): { readonly text: string; readonly titleText: string } {
- if (CLAUDE_UI_OUTPUT.test(text)) return { text: "", titleText: "" };
+ const outputEnd = claudeUiOutputEnd(text);
+ if (
+ outputEnd === text.length ||
+ // Only Claude writes task notifications, sometimes with trailing markup of its own.
+ text.startsWith("") ||
+ isClaudeShellOutput(text) ||
+ /^\[Request interrupted by user(?: for tool use)?\]$/.test(text)
+ ) {
+ return { text: "", titleText: "" };
+ }
const shellInput = /^([\s\S]*)<\/bash-input>$/.exec(text)?.[1];
if (shellInput !== undefined) return { text: `!${shellInput}`, titleText: "" };
- return claudeCommand(text) ?? { text, titleText: text };
+ return (
+ claudeCommand(text) ?? {
+ text,
+ titleText: text.slice(outputEnd || leadingBlocksEnd(text, CLAUDE_COMMAND_BLOCK)),
+ }
+ );
}
function claudeVisibleText(record: DecodedTranscriptRecord) {
From 07276c41971d7b985b1e836c22948674a3ab9971 Mon Sep 17 00:00:00 2001
From: Victor
Date: Wed, 25 Nov 2026 02:43:59 -0600
Subject: [PATCH 025/235] fix(shared): backticked insights keep their line
breaks (#42691)
Co-authored-by: Julius Marminge
---
packages/shared/src/assistantInsights.ts | 2 +-
packages/shared/src/threadFindText.test.ts | 13 +++++++++++++
2 files changed, 14 insertions(+), 1 deletion(-)
diff --git a/packages/shared/src/assistantInsights.ts b/packages/shared/src/assistantInsights.ts
index 60f4ad1df349a..78c2dfc57f0ee 100644
--- a/packages/shared/src/assistantInsights.ts
+++ b/packages/shared/src/assistantInsights.ts
@@ -1,3 +1,3 @@
export function shouldPreserveAssistantLineBreaks(text: string): boolean {
- return /^★ Insight(?:\s|─)/mu.test(text);
+ return /^★ Insight(?:\s|─)|(? {
+ expect(assistantSegments("`★ Insight ─────`\nfirst line\nsecond line\n`─────`")).toEqual([
+ "first line",
+ " second line",
+ ]);
+ expect(assistantSegments("`★ Insight ─────` opens a callout.\nfirst line\nsecond line")).toEqual([
+ "★ Insight ───── opens a callout. first line second line",
+ ]);
+ expect(
+ assistantSegments("`★ Insight ─────`\u2028opens a callout.\nfirst line\nsecond line"),
+ ).toEqual(["★ Insight ─────\u2028opens a callout. first line second line"]);
+});
+
it("indexes image destinations rendered as file chips", () => {
expect(
assistantSegments(
From feecca53e4dcc82e450ce3fcae687354822f0ef3 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 00:47:46 -0800
Subject: [PATCH 026/235] fix(provider-core): provider refreshes no longer kill
in-flight npm version checks (#42687)
---
.../src/server/ProviderLatestVersions.test.ts | 17 ++--
.../src/server/ProviderLatestVersions.ts | 61 ++++++++-------
.../src/server/maintenanceResolver.test.ts | 77 +++++++++++++++++++
.../src/server/maintenanceResolver.ts | 16 +++-
4 files changed, 131 insertions(+), 40 deletions(-)
diff --git a/packages/provider-core/src/server/ProviderLatestVersions.test.ts b/packages/provider-core/src/server/ProviderLatestVersions.test.ts
index eafdf4ac3dbc0..b7b18e7059335 100644
--- a/packages/provider-core/src/server/ProviderLatestVersions.test.ts
+++ b/packages/provider-core/src/server/ProviderLatestVersions.test.ts
@@ -28,13 +28,14 @@ describe("ProviderLatestVersions", () => {
}),
);
- it.effect("a waiting caller looks up again when the shared lookup is interrupted", () =>
+ it.effect("interrupting the owner leaves the shared lookup running for its waiters", () =>
Effect.gen(function* () {
const latestVersions = yield* ProviderLatestVersions.make();
+ const release = yield* Deferred.make();
let lookups = 0;
const lookup = Effect.suspend(() => {
lookups += 1;
- return lookups === 1 ? Effect.never : Effect.succeed("2.0.0");
+ return Deferred.await(release).pipe(Effect.as("2.0.0"));
});
const owner = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), {
@@ -43,15 +44,15 @@ describe("ProviderLatestVersions", () => {
const waiter = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), {
startImmediately: true,
});
- expect(lookups).toBe(1);
yield* Fiber.interrupt(owner);
+ yield* Deferred.succeed(release, undefined);
expect(yield* Fiber.join(waiter)).toBe("2.0.0");
expect(yield* latestVersions.cached("@example/cli", lookup)).toBe("2.0.0");
- expect(lookups).toBe(2);
+ expect(lookups).toBe(1);
}),
);
- it.effect("a caller interrupted while it claims the lookup frees the key", () =>
+ it.effect("a caller interrupted while it claims the lookup still starts it", () =>
Effect.gen(function* () {
const latestVersions = yield* ProviderLatestVersions.make();
let lookups = 0;
@@ -73,12 +74,8 @@ describe("ProviderLatestVersions", () => {
{ startImmediately: true },
);
expect(Exit.hasInterrupts(yield* Fiber.await(owner))).toBe(true);
- expect(lookups).toBe(0);
- const next = yield* Effect.forkChild(latestVersions.cached("@example/cli", lookup), {
- startImmediately: true,
- });
+ expect(yield* latestVersions.cached("@example/cli", lookup)).toBe("2.0.0");
expect(lookups).toBe(1);
- expect(yield* Fiber.join(next)).toBe("2.0.0");
}),
);
it.effect("a waiting caller retries with its own lookup after the owner fails", () =>
diff --git a/packages/provider-core/src/server/ProviderLatestVersions.ts b/packages/provider-core/src/server/ProviderLatestVersions.ts
index 92239311e4c4e..b35b775a2dc01 100644
--- a/packages/provider-core/src/server/ProviderLatestVersions.ts
+++ b/packages/provider-core/src/server/ProviderLatestVersions.ts
@@ -4,6 +4,7 @@ import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
+import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -33,6 +34,7 @@ export class ProviderLatestVersions extends Context.Service<
export const make = Effect.fn("ProviderLatestVersions.make")(function* (
seed: Iterable = [],
) {
+ const scope = yield* Effect.scope;
const entries = yield* Ref.make(
new Map(
Array.from(seed, ([key, version]) => [key, { version, expiresAt: Number.MAX_SAFE_INTEGER }]),
@@ -45,35 +47,38 @@ export const make = Effect.fn("ProviderLatestVersions.make")(function* (
const inFlight = yield* Deferred.make>();
// Replacing or invalidating this entry retires any lookup still in flight.
const pending: Entry = { version: null, expiresAt: 0, inFlight };
- // Claim and cleanup registration must be atomic with respect to interruption.
- return yield* Effect.acquireUseRelease(
- Ref.modify(entries, (current) => {
- const entry = current.get(key);
- return !options?.fresh && entry && (entry.expiresAt > now || entry.inFlight)
- ? [entry, current]
- : [undefined, new Map(current).set(key, pending)];
+ const settle = (exit: Exit.Exit) => {
+ const version = Exit.isSuccess(exit) ? Option.some(exit.value) : Option.none();
+ return Ref.update(entries, (current) => {
+ if (current.get(key) !== pending) return current;
+ const next = new Map(current);
+ if (Option.isNone(version)) {
+ next.delete(key);
+ return next;
+ }
+ const ttl = version.value === null ? MISSING_TTL : FOUND_TTL;
+ return next.set(key, { version: version.value, expiresAt: now + Duration.toMillis(ttl) });
+ }).pipe(Effect.andThen(Deferred.succeed(inFlight, version)), Effect.asVoid);
+ };
+ // Claiming the key and starting its lookup must be atomic with respect to interruption.
+ return yield* Effect.uninterruptibleMask((restore) =>
+ Effect.gen(function* () {
+ const existing = yield* Ref.modify(entries, (current) => {
+ const entry = current.get(key);
+ return !options?.fresh && entry && (entry.expiresAt > now || entry.inFlight)
+ ? [entry, current]
+ : [undefined, new Map(current).set(key, pending)];
+ });
+ if (!existing) {
+ // Interrupting a caller must not kill the lookup: a killed `npm view` leaves its
+ // partial download behind, and the next caller would start the download over.
+ const fiber = yield* restore(lookup).pipe(Effect.onExit(settle), Effect.forkIn(scope));
+ return yield* restore(Fiber.join(fiber));
+ }
+ if (!existing.inFlight) return existing.version;
+ const shared = yield* restore(Deferred.await(existing.inFlight));
+ return Option.isSome(shared) ? shared.value : yield* restore(cached(key, lookup, options));
}),
- (existing) =>
- Effect.gen(function* () {
- if (!existing) return yield* lookup;
- if (!existing.inFlight) return existing.version;
- const shared = yield* Deferred.await(existing.inFlight);
- return Option.isSome(shared) ? shared.value : yield* cached(key, lookup, options);
- }),
- (existing, exit) => {
- if (existing) return Effect.void;
- const version = Exit.isSuccess(exit) ? Option.some(exit.value) : Option.none();
- return Ref.update(entries, (current) => {
- if (current.get(key) !== pending) return current;
- const next = new Map(current);
- if (Option.isNone(version)) {
- next.delete(key);
- return next;
- }
- const ttl = version.value === null ? MISSING_TTL : FOUND_TTL;
- return next.set(key, { version: version.value, expiresAt: now + Duration.toMillis(ttl) });
- }).pipe(Effect.andThen(Deferred.succeed(inFlight, version)), Effect.asVoid);
- },
);
});
return ProviderLatestVersions.of({
diff --git a/packages/provider-core/src/server/maintenanceResolver.test.ts b/packages/provider-core/src/server/maintenanceResolver.test.ts
index f392f4b546963..21b1f4da5d1e1 100644
--- a/packages/provider-core/src/server/maintenanceResolver.test.ts
+++ b/packages/provider-core/src/server/maintenanceResolver.test.ts
@@ -436,6 +436,83 @@ it.layer(
{ skip: !symlinksSupported || windowsHost },
);
+ // A killed `npm view` leaves its partial packument in npm's cache tmp dir.
+ it.effect.skipIf(!symlinksSupported || windowsHost)(
+ "neither a refresh nor the probe timeout kills a slow npm version check or starts another download",
+ () =>
+ Effect.gen(function* () {
+ const tempDir = yield* makeTempDir("t3-interrupted-npm-view");
+ const npmBinDir = NodePath.join(tempDir, "npm-bin");
+ writeExecutable(NodePath.join(npmBinDir, "npm"));
+ const binaryPath = NodePath.join(tempDir, ".local/bin/native-package-tool");
+ writeExecutable(binaryPath);
+ const spawned = yield* Deferred.make();
+ const download = yield* Deferred.make();
+ let spawns = 0;
+ let downloaded = false;
+ let killedMidDownload = 0;
+ const slowNpmView = ChildProcessSpawner.make(() =>
+ Effect.sync(() => {
+ spawns++;
+ Deferred.doneUnsafe(spawned, Effect.void);
+ return ChildProcessSpawner.makeHandle({
+ pid: ChildProcessSpawner.ProcessId(spawns),
+ exitCode: Deferred.await(download).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
+ isRunning: Effect.succeed(true),
+ kill: () =>
+ Effect.sync(() => {
+ if (!downloaded) killedMidDownload++;
+ }),
+ unref: Effect.succeed(Effect.void),
+ stdin: Sink.drain,
+ stdout: Stream.fromEffect(Deferred.await(download)).pipe(
+ Stream.as('"1.2.0"'),
+ Stream.encodeText,
+ ),
+ stderr: Stream.empty,
+ all: Stream.empty,
+ getInputFd: () => Sink.drain,
+ getOutputFd: () => Stream.empty,
+ });
+ }),
+ );
+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
+ nativePackageToolUpdate,
+ { binaryPath, env: { PATH: "" } },
+ ).pipe(
+ Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }),
+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, slowNpmView),
+ );
+ const check = enrichProviderSnapshotWithVersionAdvisory(
+ installedPackageToolProvider,
+ capabilities,
+ );
+
+ const first = yield* Effect.forkChild(check);
+ yield* Deferred.await(spawned);
+ // A provider refresh interrupts the enrichment still in flight.
+ yield* Fiber.interrupt(first);
+ const second = yield* Effect.forkChild(check);
+ yield* Effect.yieldNow;
+ // A slow registry outlasts the probe timeout.
+ yield* TestClock.adjust("1 minute");
+ downloaded = true;
+ yield* Deferred.succeed(download, undefined);
+ const snapshot = yield* Fiber.join(second);
+
+ expect(snapshot.versionAdvisory?.latestVersion).toBe("1.2.0");
+ expect({ spawns, killedMidDownload }).toEqual({ spawns: 1, killedMidDownload: 0 });
+ }).pipe(
+ Effect.provide(ProviderLatestVersions.layer),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make(() =>
+ Effect.die("a configured npm lookup must not fall back to public npm"),
+ ),
+ ),
+ ),
+ );
+
it.effect.skipIf(windowsHost)(
"does not offer a Vite+ update npm's release-age policy will not install",
() =>
diff --git a/packages/provider-core/src/server/maintenanceResolver.ts b/packages/provider-core/src/server/maintenanceResolver.ts
index 583bb1e02111c..18f18da5f63ea 100644
--- a/packages/provider-core/src/server/maintenanceResolver.ts
+++ b/packages/provider-core/src/server/maintenanceResolver.ts
@@ -40,6 +40,9 @@ import * as ProviderLatestVersions from "./ProviderLatestVersions.ts";
const LATEST_VERSION_TIMEOUT_MS = 4_000;
const PROBE_TIMEOUT_MS = 10_000;
+// npm leaves a killed packument download in its cache's tmp dir, so registry probes are
+// bounded by npm's own fetch-timeout instead of being killed.
+const NPM_REGISTRY_PROBE_TIMEOUT = null;
const PROBE_MAX_BYTES = 256 * 1_024;
const WRAPPER_SCRIPT_MAX_BYTES = 16 * 1_024;
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
@@ -415,6 +418,7 @@ const runProbe = Effect.fn("runProbe")(function* (
args: ReadonlyArray,
env: NodeJS.ProcessEnv,
okExitCodes: ReadonlyArray = [0],
+ timeoutMs: number | null = PROBE_TIMEOUT_MS,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const collect = Effect.gen(function* () {
@@ -441,8 +445,13 @@ const runProbe = Effect.fn("runProbe")(function* (
});
return yield* collect.pipe(
Effect.scoped,
- Effect.timeoutOption(Duration.millis(PROBE_TIMEOUT_MS)),
- Effect.map(Option.getOrNull),
+ (scoped) =>
+ timeoutMs === null
+ ? scoped
+ : scoped.pipe(
+ Effect.timeoutOption(Duration.millis(timeoutMs)),
+ Effect.map(Option.getOrNull),
+ ),
Effect.catchCause((cause) =>
Effect.logWarning("Maintenance probe failed", {
command,
@@ -537,6 +546,7 @@ const runNpmGlobalLatestVersions = Effect.fn("runNpmGlobalLatestVersions")(funct
env,
// npm outdated exits 1 when updates are available.
[0, 1],
+ NPM_REGISTRY_PROBE_TIMEOUT,
);
const outdatedEntries = outdated ? Option.getOrUndefined(decodeOutdated(outdated)) : undefined;
// npm prints failures such as an unreachable registry as `{"error": ...}`, also exiting 1.
@@ -1315,6 +1325,8 @@ const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup
npmPath,
["view", "--global", "--json", `${packageName}@latest`, "version"],
env,
+ [0],
+ NPM_REGISTRY_PROBE_TIMEOUT,
).pipe(
Effect.map((stdout) => {
const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null;
From d38dcccef8e3d0fac83e73336f77485b515b2c76 Mon Sep 17 00:00:00 2001
From: Julius Marminge
Date: Wed, 25 Nov 2026 01:14:56 -0800
Subject: [PATCH 027/235] fix(web): project actions menu re-reads t3.json each
time it opens (#42707)
---
.../src/components/ProjectScriptsControl.tsx | 24 ++++---
.../chat/ThreadDetailsPanel.browser.test.tsx | 66 ++++++++++++++++++-
.../components/chat/ThreadDetailsPanel.tsx | 7 +-
apps/web/src/hooks/useT3ProjectFileScripts.ts | 14 ++--
4 files changed, 85 insertions(+), 26 deletions(-)
diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx
index 210762bfdebf9..870a165912a81 100644
--- a/apps/web/src/components/ProjectScriptsControl.tsx
+++ b/apps/web/src/components/ProjectScriptsControl.tsx
@@ -69,6 +69,7 @@ interface ProjectScriptsControlProps {
environmentId: EnvironmentId;
scripts: ReadonlyArray;
fileScripts?: ReadonlyArray;
+ onActionsMenuOpen?: () => void;
preferredScriptId?: string | null;
onRunScript?: ((script: ProjectScript) => void) | undefined;
onAddScript: (input: NewProjectScriptInput) => Promise;
@@ -86,6 +87,7 @@ export default function ProjectScriptsControl({
environmentId,
scripts,
fileScripts = NO_FILE_SCRIPTS,
+ onActionsMenuOpen,
preferredScriptId = null,
onRunScript,
onAddScript,
@@ -108,6 +110,10 @@ export default function ProjectScriptsControl({
if (actionsMenuOpen.presentation !== presentation) {
setActionsMenuOpen({ presentation, scripts: false, imports: false });
}
+ const openActionsMenu = (menus: { scripts: boolean; imports: boolean }) => {
+ if (menus.scripts || menus.imports) onActionsMenuOpen?.();
+ setActionsMenuOpen({ presentation, ...menus });
+ };
const [editorRequest, setEditorRequest] = useState(null);
const editorRequestIdRef = React.useRef(0);
@@ -286,9 +292,7 @@ export default function ProjectScriptsControl({
{scripts.length > 0 || importableScripts.length > 0 ? (
- setActionsMenuOpen({ presentation, scripts: open, imports: false })
- }
+ onOpenChange={(open) => openActionsMenu({ scripts: open, imports: false })}
>
@@ -361,9 +365,7 @@ export default function ProjectScriptsControl({
)}