- {checkoutThread.branch ? (
- <>
-
-
-
-
- >
- ) : showsScratchMachine ? (
+ {props.environmentLabel !== null ? (
<>
-
{props.scratchMachineLabel}
+
{props.environmentLabel}
>
) : (
@@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP
aria-hidden
className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1"
>
- {remoteMachineIcon}
- {remoteMachineIcon}
{
},
};
});
- const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({
+ const checkpoint = (
+ ordinal: number,
+ status: "ready" | "missing" | "stale" | "error" = "ready",
+ ) => ({
runId: runId(ordinal),
checkpointTurnCount: ordinal,
checkpointRef: `checkpoint-${ordinal}` as never,
@@ -326,6 +329,11 @@ describe("V2 session presentation", () => {
"user-1": 0,
"user-2": 1,
});
+ // A failed snapshot capture still pins the conversation; only file restore needs one.
+ expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({
+ "user-1": 0,
+ "user-2": 1,
+ });
});
it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => {
diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts
index 1122c3122aca0..5196ee43458d8 100644
--- a/apps/web/src/session-logic.ts
+++ b/apps/web/src/session-logic.ts
@@ -1153,10 +1153,10 @@ export function deriveRevertTurnCountByUserMessageId(input: {
return byUserMessageId;
}
-// A missing snapshot (no git, or a side chat) still pins a conversation position; only
-// restoring files needs a ready one.
+// A missing or failed snapshot (no git, a side chat, a capture error) still pins a
+// conversation position; only restoring files needs a ready one.
function isRewindableCheckpoint(checkpoint: Pick) {
- return checkpoint.status === "ready" || checkpoint.status === "missing";
+ return checkpoint.status !== "stale";
}
export function findRevertCheckpoint(
diff --git a/docs/progress.md b/docs/progress.md
index 71a49391f9275..d8c825422f51f 100644
--- a/docs/progress.md
+++ b/docs/progress.md
@@ -307,3 +307,20 @@
- Numbers: `KeepAwake.test.ts` gains two `makeHold` cases on the TestClock: a denied hold run twice across an hour spawns once and logs one warning with an empty cause; a plain non-zero exit retries at 5 s and again 10 s later. Both failed before the change (no `makeHold`), 3/3 pass after.
- What worked: pulling the retry policy into an exported `makeHold(holdOnce)` with a `denied` Ref, so the test drives it with a fake `holdOnce` instead of spawning `systemd-inhibit`.
- Next: Tomáš merges the PR and switches hub2 and hub to the new build; their logs should show one `keep-awake disabled until restart` line per server start instead of a stack every few minutes.
+
+## 2026-11-22: Fork synced with upstream `c198f73b37` by a merge
+
+- What: upstream main `c198f73b37`, 17 commits newer than the last sync base `c9e9e7d36a` (88 files, +1878/-318), was merged into `tomas/sync-upstream-2026-11-22c` at fork main `2479ed911e` (#32) with a real merge (this commit), as in the last seven syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push.
+- Why: upstream changed 27 files the fork also changes: `Orchestrator.ts`, `ProviderTurnStartService.ts` and its test, `runtimeLayer.test.ts`, `ChatView.tsx`, client-runtime `threadWorkflows.ts` and its test, and the 10 web and 10 mobile catalogs. The sync was asked for at `70b5e489b9` (15 commits); #40767 and #40776 landed during the work and are included.
+- Conflict: one, in `ProviderTurnStartService.ts`. Upstream #40764 keeps the "Native resume is unavailable" refusal for a Resume on a provider without native resume and skips it only when pending context goes with the resume (handoffs, missed attachments, side chat, a restart note); that resume then becomes a prompted turn with "Continue where you left off.". The fork never refuses there: since 2026-11-15 such a Resume starts a normal turn with that text (`continueInstead`, `resume: false`), and that start already carried pending context through the delivery session. Kept upstream's `carriesPendingContext`, which now picks the delivery session, and dropped the refusal.
+- Proof: with upstream's refusal kept, the fork's "asks to continue when the provider cannot resume natively" fails (93/94 in `ProviderTurnStartService.test.ts`); with the resolution the file passes 94/94, including upstream's two new pending-context cases, which expect the same text the fork's start sends.
+- Catalogs: the 20 catalogs merged without conflicts. Each parses to base plus the fork's key changes (+64/-3 keys per web catalog, +1/-1 per mobile catalog) plus upstream's (-2 per web catalog, +1 per mobile catalog), with no key changed by both sides and no duplicate keys. `vp run i18n:generate` in apps/web and apps/mobile changed no key or value: it only moved the fork's keys from the catalog tails into source order and rewrapped arrays, so the merged layout was kept. `vp run i18n:check` passes.
+- Fork behavior kept: the fork's diff against upstream is 121 files before (`c9e9e7d36a..2479ed911e`) and after the merge (`c198f73b37..HEAD`). The added and removed lines are identical in every file except `ProviderTurnStartService.ts`, where the removed refusal is now upstream's longer form of the same check (+11/-16 before, +11/-22 after). In the other direction, `2479ed911e..HEAD` holds upstream's 88-file change line for line except that refusal.
+- Checked and left alone: #40767 (Queue instead of Steer for sessions that cannot steer) changes `ChatView.tsx` and `threadWorkflows.ts` away from the fork's hunks (Auto level, lineage and machine bar; `threadSupportsProviderHandoff`). #40745 (Edit from here after a failed checkpoint capture) changes `Orchestrator.ts` at the rewind check, apart from the fork's Auto routing; `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch. #40738 makes `t3 thread list` include delegated threads (all but subagents), so threads launched with the fork's `delegatedFrom` show there too. #40154 and #39822 concern Antigravity's own Auto runtime mode, not the fork's `auto-*` model slugs. #40734, #40703, #40736, #40759, #40741, #40726, #40739, #40744, #40758, #40755 and #40776 touch no fork code.
+- Agent context: #40741 adds TanStack Source text to the pull-request MCP tools, so `mcpToolListJsonBytes` grows 59052 -> 59192 (+140); `AgentContextBudget.test.ts` passes 2/2. The PR needs the `agent-context-increase` label for the Agent context budget check.
+- Numbers: `vp run check:changed upstream/main --timeout 2700` (the fork's 121 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1616 tests in 58 files and react compiler (27 files) pass in 11m02s. `vp run check:changed origin/main --timeout 2700` (upstream's files): format, lint, knip, graphql, typecheck (39 packages), 1677 tests in 54 files and react compiler (13 files) pass in 11m43s. Both ran on the merge with `c3a330d834`; #40776 landed meanwhile, so the unpushed merge was redone on `c198f73b37` with the same resolution (the trees differ only by #40776's 2 files), and `vp run check:changed ` checked those 2 files: format, lint, knip, typecheck (2 packages), its browser test 2/2 and react compiler pass in 2m07s. `vp run i18n:check` passes on the final tree.
+- What worked: `check:changed` diffs against `git merge-base HEAD `, so to check only the files a redone merge adds, detach at a throwaway commit with the new tree whose parent is the first merge (`git commit-tree HEAD^{tree} -p `); the working tree does not change. The per-key catalog check must compare nested plural values by their JSON text and look for duplicate keys per object.
+- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 405 MB, written under the worktree's ignored `.t3` and deleted after seeding), and `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (62.2 MB, 5 projects, 28 threads), applying migrations 103-105 from earlier syncs. `vp run dev:server --home-dir .t3/verify` with seeding off booted on that dir on port 14254, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its process tree and the port was released. No agent turn was sent. Warnings: the expected two (no Rust build for the resource monitor, the scratch home inside the Git repo), plus, on stop, upstream's keep-awake run event stream logging its interrupt; this sync does not change that code.
+- Review: one independent read-only review found no bugs. It confirmed that in `ProviderTurnStartService.ts` the merge differs from upstream by exactly the fork's three changes (`continueInstead`, the dropped refusal, `resume: false` for it), that `resume: false` keeps upstream's new delivery-session `resumeTurn` and resume `operation` branch unreachable for these sessions, that pending context is delivered once, and that the other shared files differ from fork main by exactly upstream's lines.
+- Switching the hubs: these 17 commits add no migrations and change no lockfile or package manifests; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs.
+- Next: Tomáš merges the PR, then switches hub2 and hub to the new build.
diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md
index 84c13d30c4c84..00b27e02ae23d 100644
--- a/docs/user/providers-claude.md
+++ b/docs/user/providers-claude.md
@@ -63,8 +63,8 @@ When you return to a large thread after Claude's prompt cache expires, a
**Compact** chip with the thread's token count shows
next to the send button. While it is on, Enter summarizes the history first, then
sends your message. Click the chip to switch it to **Keep** and keep the full
-history for that message. The mobile app shows no chip: an eligible message sent
-from it summarizes first. The cache lasts about an hour on a Claude
+history for that message. The mobile app shows the same chip, labelled with the
+token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude
subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using
composer commands.
diff --git a/docs/user/source-control.md b/docs/user/source-control.md
index fa193bf0e87a8..b6702c13de5d9 100644
--- a/docs/user/source-control.md
+++ b/docs/user/source-control.md
@@ -160,7 +160,9 @@ Alternatively, open **Settings → Source control & issues**, expand **TanStack
from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is
used before the `src` login. With several `src` logins, pick the account there too.
-Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues
+Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An
+agent can open a private pull request on a public repository when you ask for one: its branch goes
+to the repository's private companion and never to the repository itself. Issues
can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees
from a list are not available yet.
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index b2535a81123e1..941fdcd9b389e 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -28,6 +28,7 @@ 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 Schema from "effect/Schema";
import * as SubscriptionRef from "effect/SubscriptionRef";
import * as TestClock from "effect/testing/TestClock";
import { RpcClientError } from "effect/rpc";
@@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix
import {
archiveThread,
interruptThreadTurn,
+ promoteQueuedRun,
revertThreadCheckpoint,
resumeThreadQueue,
startThreadTurn,
@@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed(
SecureRandom.make((size) => new Uint8Array(size)),
);
+class Refused extends Schema.TaggedError()("Refused", {}) {}
+
const TARGET = new PrimaryConnectionTarget({
environmentId: EnvironmentId.make("environment-1"),
label: "Test environment",
@@ -634,6 +638,121 @@ describe("V2 environment commands", () => {
}).pipe(Effect.provide(layerTestRandom)),
);
+ const turnSends = [
+ {
+ name: "new thread's first message",
+ method: ORCHESTRATION_V2_WS_METHODS.launchThread,
+ send: (commandId: CommandId) =>
+ startThreadTurn({
+ commandId,
+ threadId: v2ThreadId,
+ message: {
+ messageId: MessageId.make(commandId),
+ role: "user",
+ text: "hi",
+ attachments: [],
+ },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ bootstrap: {
+ createThread: {
+ projectId: ProjectId.make("project-1"),
+ title: "Thread",
+ modelSelection: v2Projection.thread.modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt: "2026-06-20T00:00:00.000Z",
+ },
+ },
+ }),
+ },
+ {
+ name: "queued message sent now",
+ method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
+ send: (commandId: CommandId) =>
+ resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }),
+ },
+ {
+ name: "queued message steered",
+ method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand,
+ send: (commandId: CommandId) =>
+ promoteQueuedRun({
+ commandId,
+ threadId: v2ThreadId,
+ queuedRunId: RunId.make("queued"),
+ targetRunId: RunId.make("running"),
+ }),
+ },
+ ] as const;
+
+ const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")(
+ function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) {
+ const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] });
+ const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session));
+ const attempts: string[] = [];
+ const firstAttemptFailed = yield* Deferred.make();
+ const healthyMethod = (
+ healthySession.client as unknown as Record<
+ string,
+ (input: unknown) => Effect.Effect
+ >
+ )[turnSend.method]!;
+ const failingClient = {
+ ...healthySession.client,
+ [turnSend.method]: (input: { readonly commandId: CommandId }) =>
+ Effect.gen(function* () {
+ attempts.push(input.commandId);
+ if (attempts.length > 1) return yield* healthyMethod(input);
+ yield* SubscriptionRef.set(supervisor.session, Option.none());
+ yield* Deferred.succeed(firstAttemptFailed, undefined);
+ return yield* failure;
+ }),
+ } as unknown as WsRpcProtocolClient;
+ yield* SubscriptionRef.set(
+ supervisor.session,
+ Option.some({ ...healthySession, client: failingClient }),
+ );
+ const sendFiber = yield* turnSend
+ .send(CommandId.make("command-turn-send"))
+ .pipe(
+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),
+ Effect.forkChild,
+ );
+ yield* Deferred.await(firstAttemptFailed);
+ yield* SubscriptionRef.set(
+ supervisor.session,
+ Option.some({ ...healthySession, client: failingClient }),
+ );
+ return { exit: yield* Fiber.await(sendFiber), attempts };
+ },
+ );
+
+ it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) =>
+ Effect.gen(function* () {
+ const { exit, attempts } = yield* sendFailingFirstAttempt(
+ turnSend,
+ Effect.failCause(Cause.interrupt()),
+ );
+
+ expect(attempts).toEqual(["command-turn-send", "command-turn-send"]);
+ expect(Exit.isSuccess(exit)).toBe(true);
+ }).pipe(Effect.provide(layerTestRandom)),
+ );
+
+ it.effect("doesn't resend a new thread's first message the server refused", () =>
+ Effect.gen(function* () {
+ const { exit, attempts } = yield* sendFailingFirstAttempt(
+ turnSends[0],
+ Effect.fail(new Refused()),
+ );
+
+ expect(attempts).toEqual(["command-turn-send"]);
+ expect(Exit.isFailure(exit)).toBe(true);
+ }).pipe(Effect.provide(layerTestRandom)),
+ );
+
it.effect("Stop with no run left ends the thread's pull request watches", () =>
Effect.gen(function* () {
const link = {
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index ee17123e8839f..0ea95420460a7 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2;
// alone would leave the send pending forever.
const MESSAGE_DISPATCH_TIMEOUT = "60 seconds";
-const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* (
- command: Extract,
- resendAfterSocketLoss: boolean,
-) {
+const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* <
+ A,
+ E,
+ R,
+>(attempt: Effect.Effect) {
const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
- const attempt = dispatch(command).pipe(
- Effect.timeoutOrElse({
- duration: MESSAGE_DISPATCH_TIMEOUT,
- orElse: () =>
- Effect.fail(
- new EnvironmentRpcUnavailableError({
- environmentId: supervisor.target.environmentId,
- ...translatableMessage(
- msg("{host} did not confirm the message within 60 seconds.", {
- host: supervisor.target.label,
- }),
- ),
- }),
- ),
- }),
- );
- if (!resendAfterSocketLoss) return yield* attempt;
for (let resends = 0; ; resends += 1) {
const attemptSession = yield* SubscriptionRef.get(supervisor.session);
const exit = yield* Effect.exit(attempt);
@@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio
}
});
+const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* (
+ command: Extract,
+ resend: boolean,
+) {
+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
+ const attempt = dispatch(command).pipe(
+ Effect.timeoutOrElse({
+ duration: MESSAGE_DISPATCH_TIMEOUT,
+ orElse: () =>
+ Effect.fail(
+ new EnvironmentRpcUnavailableError({
+ environmentId: supervisor.target.environmentId,
+ ...translatableMessage(
+ msg("{host} did not confirm the message within 60 seconds.", {
+ host: supervisor.target.label,
+ }),
+ ),
+ }),
+ ),
+ }),
+ );
+ return yield* resend ? resendAfterSocketLoss(attempt) : attempt;
+});
+
const getProjection = (threadId: ThreadId) =>
request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId });
@@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
input.message.attachments,
attachments,
);
+ const resend = input.resendAfterSocketLoss ?? true;
const bootstrap = input.bootstrap?.createThread;
const prepareWorktree = input.bootstrap?.prepareWorktree;
if (bootstrap !== undefined || prepareWorktree !== undefined) {
@@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
? {}
: { branch: bootstrap.branch }),
};
- return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
+ const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
commandId,
creationSource: input.creationSource ?? "web",
threadId: input.threadId,
@@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
attachments,
},
});
+ return yield* resend ? resendAfterSocketLoss(launch) : launch;
}
const requestedMode = input.dispatchMode ?? "auto";
- const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true;
if (requestedMode === "start") {
return yield* dispatchMessage(
{
@@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
...(input.freshContext ? { freshContext: true } : {}),
dispatchMode: { type: "start_immediately" },
},
- resendAfterSocketLoss,
+ resend,
);
}
@@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}),
dispatchMode,
},
- resendAfterSocketLoss,
+ resend,
);
});
@@ -1065,9 +1074,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea
);
if (
checkpoint === undefined ||
- // Missing snapshots support conversation rewind only.
+ // Missing or failed snapshots support conversation rewind only.
(checkpoint.status !== "ready" &&
- !(input.restoreFiles === false && checkpoint.status === "missing"))
+ !(input.restoreFiles === false && checkpoint.status !== "stale"))
) {
const target =
input.checkpointId === undefined
@@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(
export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
input: ResumeThreadQueueInput,
) {
- return yield* dispatch({
- ...(input.runId === undefined
- ? { type: "queue.resume" as const }
- : { type: "queued-run.start" as const, runId: input.runId }),
- commandId: yield* allocateCommandId(input),
- threadId: input.threadId,
- });
+ return yield* resendAfterSocketLoss(
+ dispatch({
+ ...(input.runId === undefined
+ ? { type: "queue.resume" as const }
+ : { type: "queued-run.start" as const, runId: input.runId }),
+ commandId: yield* allocateCommandId(input),
+ threadId: input.threadId,
+ }),
+ );
});
export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* (
input: PromoteQueuedRunInput,
) {
- return yield* dispatch({
- type: "queued-message.promote-to-steer",
- commandId: yield* allocateCommandId(input),
- threadId: input.threadId,
- queuedRunId: input.queuedRunId,
- targetRunId: input.targetRunId,
- });
+ return yield* resendAfterSocketLoss(
+ dispatch({
+ type: "queued-message.promote-to-steer",
+ commandId: yield* allocateCommandId(input),
+ threadId: input.threadId,
+ queuedRunId: input.queuedRunId,
+ targetRunId: input.targetRunId,
+ }),
+ );
});
export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts
index 1527dbd9f3e87..68817c9c2a431 100644
--- a/packages/client-runtime/src/state/threadWorkflows.test.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.test.ts
@@ -6,6 +6,7 @@ import {
deriveThreadQueueWorkflowState,
getUserQueuedThreadRuns,
resolveLatestMergeBackRun,
+ threadCanSteer,
threadSupportsProviderHandoff,
} from "./threadWorkflows.ts";
@@ -13,6 +14,7 @@ const capabilities = (input?: {
readonly queued?: boolean;
readonly steer?: boolean;
readonly restartSteer?: boolean;
+ readonly interrupt?: boolean;
readonly nativeFork?: boolean;
readonly portableFork?: boolean;
}) =>
@@ -21,6 +23,7 @@ const capabilities = (input?: {
supportsQueuedMessages: input?.queued ?? false,
supportsActiveSteering: input?.steer ?? false,
supportsSteeringByInterruptRestart: input?.restartSteer ?? false,
+ supportsInterrupt: input?.interrupt ?? false,
},
threads: {
canForkThread: input?.nativeFork ?? false,
@@ -31,6 +34,35 @@ const capabilities = (input?: {
}) as never;
describe("thread workflows", () => {
+ it.each([
+ ["queue only", { queued: true }, false, false],
+ ["session still attaching", undefined, false, true],
+ ["native steering", { steer: true }, false, true],
+ ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true],
+ ["restart without interrupt", { restartSteer: true }, false, false],
+ ["explicit compaction", { steer: true }, true, false],
+ ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => {
+ const projection = {
+ thread: { id: "thread", activeProviderThreadId: "provider-thread" },
+ runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }],
+ providerThreads: [{ id: "provider-thread", providerSessionId: "session" }],
+ providerSessions: [
+ ...(turns === undefined
+ ? []
+ : [{ id: "session", status: "running", capabilities: capabilities(turns) }]),
+ { id: "other", status: "ready", capabilities: capabilities({ steer: true }) },
+ ],
+ messages: [],
+ } as unknown as OrchestrationV2ThreadProjection;
+ expect(
+ threadCanSteer(projection, {
+ compactCommandIsActive,
+ compactionRunning: false,
+ activeRunId: projection.runs[0]!.id,
+ }),
+ ).toBe(expected);
+ });
+
it("skips message history classification when no runs are queued", () => {
let metadataReads = 0;
const message = {
@@ -153,7 +185,7 @@ describe("thread workflows", () => {
{
id: "provider-session",
status: "running",
- capabilities: capabilities({ queued: true, restartSteer: true }),
+ capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }),
},
],
} as never);
diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts
index b429449ace869..4905af1497fb7 100644
--- a/packages/client-runtime/src/state/threadWorkflows.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.ts
@@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array";
import { mFallback, msg } from "gt-i18n";
import type { MFunctionType } from "gt-i18n/types";
+import { compactionBlocksSteering } from "./composerDispatch.ts";
import type { ThreadStructure } from "./models.ts";
type Projection = ThreadStructure;
@@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und
);
}
+function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean {
+ return (
+ turns.supportsActiveSteering ||
+ (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart)
+ );
+}
+
+export function threadCanSteer(
+ projection: Projection | null,
+ input: {
+ readonly compactCommandIsActive: boolean;
+ readonly compactionRunning: boolean;
+ readonly activeRunId: Run["id"] | null | undefined;
+ },
+): boolean {
+ const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns;
+ // A steer submitted before the session attaches can wait for its provider turn.
+ if (turns && !supportsSteering(turns)) return false;
+ return !compactionBlocksSteering({
+ compactCommandIsActive: input.compactCommandIsActive,
+ compactionRunning: input.compactionRunning,
+ steersDuringCompaction: turns?.activeSteeringDuringCompaction === true,
+ run: projection?.runs.find((run) => run.id === input.activeRunId),
+ messages: projection?.messages,
+ });
+}
+
export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean {
if (projection == null) return false;
const session = resolveThreadProviderSession(projection);
@@ -143,6 +171,7 @@ export function deriveThreadQueueWorkflowState(
const activeRun = resolveActiveThreadRun(projection);
const session = resolveThreadProviderSession(projection);
const capabilities = session?.capabilities.turns;
+ const canSteer = capabilities !== undefined && supportsSteering(capabilities);
const activeMessage = projection.messages.find(
(message) => message.id === activeRun?.userMessageId,
);
@@ -183,12 +212,8 @@ export function deriveThreadQueueWorkflowState(
canPromoteToSteer:
promoteSkipsCompaction ||
((activeRun?.status === "preparing" || activeRun?.status === "starting") &&
- (capabilities === undefined ||
- capabilities.supportsActiveSteering ||
- capabilities.supportsSteeringByInterruptRestart)) ||
- (hasSteerableProviderTurn &&
- (capabilities?.supportsActiveSteering === true ||
- capabilities?.supportsSteeringByInterruptRestart === true)),
+ (capabilities === undefined || canSteer)) ||
+ (hasSteerableProviderTurn && canSteer),
promoteSkipsCompaction,
};
}
diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts
index 63087b6b253e1..0bb2858c107cf 100644
--- a/packages/contracts/src/pullRequest.ts
+++ b/packages/contracts/src/pullRequest.ts
@@ -356,6 +356,10 @@ export const PullRequestStackMembership = Schema.Struct({
});
export type PullRequestStackMembership = typeof PullRequestStackMembership.Type;
+/** Who can read a pull request on a host that can hide one in a public repository. */
+export const PullRequestVisibility = Schema.Literals(["public", "private"]);
+export type PullRequestVisibility = typeof PullRequestVisibility.Type;
+
export const PullRequestListEntry = Schema.Struct({
stack: Schema.optional(PullRequestStackMembership),
provider: SourceControlProviderKind,
@@ -383,6 +387,8 @@ export const PullRequestListEntry = Schema.Struct({
labels: Schema.Array(PullRequestLabel),
reviewDecision: Schema.optional(PullRequestReviewDecision),
checksState: Schema.optional(PullRequestChecksState),
+ /** Absent where the host has no private pull requests or names no visibility. */
+ visibility: Schema.optional(PullRequestVisibility),
});
export type PullRequestListEntry = typeof PullRequestListEntry.Type;
@@ -684,6 +690,8 @@ export const PullRequestDetail = Schema.Struct({
/** Absent where the host has no merge queue or does not report one. */
mergeQueueRemoval: Schema.optional(PullRequestMergeQueueRemoval),
maintainerCanModify: Schema.optional(Schema.Boolean),
+ /** Absent where the host has no private pull requests or names no visibility. */
+ visibility: Schema.optional(PullRequestVisibility),
});
export type PullRequestDetail = typeof PullRequestDetail.Type;
diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts
index 019af2a98783f..b3e54117f02ee 100644
--- a/packages/provider-pi/src/server/adapter.test.ts
+++ b/packages/provider-pi/src/server/adapter.test.ts
@@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => {
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
+ it.effect("reports cached input as a share of input in live and completed token usage", () =>
+ Effect.gen(function* () {
+ const fake = yield* makeFakePi;
+ fake.queueState({
+ sessionFile: FAKE_SESSION_FILE,
+ model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 },
+ });
+ const { runtime, takeEvent } = yield* openRuntime(fake);
+ const providerThread = yield* runtime.ensureThread({
+ threadId: THREAD_ID,
+ modelSelection: modelSelection("default"),
+ runtimePolicy,
+ });
+ yield* startTurn(runtime, providerThread);
+ yield* fake.takeRequest("prompt");
+ // Pi's message usage counts uncached input, cache reads and cache writes separately.
+ const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 };
+ // Session stats total every message in the session, not this turn.
+ fake.queueStats({
+ tokens: {
+ input: 1_206,
+ cacheRead: 90_202,
+ cacheWrite: 60_622,
+ output: 250,
+ total: 152_280,
+ },
+ contextUsage: { tokens: 50_791, contextWindow: 1_000_000 },
+ });
+ yield* fake.emit({ type: "response", command: "prompt", success: true });
+ yield* fake.emit({ type: "agent_start" });
+ yield* fake.emit({ type: "message_start", message: { role: "assistant" } });
+ yield* fake.emit({
+ type: "message_update",
+ usage: { ...usage, totalTokens: 50_791 },
+ assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" },
+ });
+ const live = yield* takeEvent(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined,
+ );
+ assert.deepInclude(
+ live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined,
+ { inputTokens: 50_668, cachedInputTokens: 40_101 },
+ );
+ yield* fake.emit({ type: "agent_settled" });
+ const completed = yield* takeEvent(
+ (event) =>
+ event.type === "provider_turn.updated" && event.providerTurn.status === "completed",
+ );
+ assert.deepInclude(
+ completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined,
+ { inputTokens: 50_668, cachedInputTokens: 40_101 },
+ );
+ }).pipe(Effect.scoped, Effect.provide(layerTest)),
+ );
+
it.effect.each(["turn window", "full tree"] as const)(
"finishes a turn whose %s has a parentId cycle",
(cycleIn) =>
diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts
index eae7f3eb6c2fa..e7803bbe9c5ee 100644
--- a/packages/provider-pi/src/server/adapter.ts
+++ b/packages/provider-pi/src/server/adapter.ts
@@ -359,6 +359,11 @@ function compactionTitle(status: PiCompactionStatus): string {
}
}
+type PiMessageTokenUsage = Pick<
+ OrchestrationV2ProviderTurnTokenUsage,
+ "inputTokens" | "cachedInputTokens" | "outputTokens"
+>;
+
interface ActivePiTurn {
readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput;
readonly providerTurn: OrchestrationV2ProviderTurn;
@@ -377,6 +382,7 @@ interface ActivePiTurn {
promptMayBeCommandOnly: boolean;
latestCompactionAfterTokens: number | null;
lastLiveUsedTokens: number | null;
+ lastMessageUsage: PiMessageTokenUsage | undefined;
settleProbeGeneration: number;
/** An extension may start compaction immediately after Pi emits agent_settled. */
settleWhenIdle: boolean;
@@ -904,6 +910,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
return value === undefined ? undefined : Math.max(0, Math.trunc(value));
};
+ // Pi counts uncached input, cache reads and cache writes separately; input includes all three.
+ const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => {
+ const uncachedInputTokens = nonNegativeInteger(usage, "input");
+ const cachedInputTokens = nonNegativeInteger(usage, "cacheRead");
+ const outputTokens = nonNegativeInteger(usage, "output");
+ return {
+ ...(uncachedInputTokens === undefined
+ ? {}
+ : {
+ inputTokens:
+ uncachedInputTokens +
+ (cachedInputTokens ?? 0) +
+ (nonNegativeInteger(usage, "cacheWrite") ?? 0),
+ }),
+ ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
+ ...(outputTokens === undefined ? {} : { outputTokens }),
+ };
+ };
+
const rememberModelContextWindow = (model: unknown): number | null => {
const provider = recordString(model, "provider");
const id = recordString(model, "id");
@@ -994,6 +1019,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
const tokenUsageFromStats = (
stats: unknown,
fallbackUsedTokens: number | null,
+ messageUsage: PiMessageTokenUsage | undefined,
updatedAt: DateTime.Utc,
): OrchestrationV2ProviderTurnTokenUsage | undefined => {
const contextUsage = recordField(stats, "contextUsage");
@@ -1002,24 +1028,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined;
if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0)
return undefined;
-
- const totals = recordField(stats, "tokens");
- const inputTokens = nonNegativeInteger(totals, "input");
- const cachedInputTokens = nonNegativeInteger(totals, "cacheRead");
- const outputTokens = nonNegativeInteger(totals, "output");
- return {
- usedTokens,
- maxTokens,
- ...(inputTokens === undefined ? {} : { inputTokens }),
- ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
- ...(outputTokens === undefined ? {} : { outputTokens }),
- updatedAt: DateTime.formatIso(updatedAt),
- };
+ // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message.
+ return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) };
};
- const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) =>
+ const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) =>
request({ type: "get_session_stats" }, 2_000).pipe(
- Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)),
+ Effect.map((stats) =>
+ tokenUsageFromStats(
+ stats,
+ turn.latestCompactionAfterTokens,
+ turn.lastMessageUsage,
+ updatedAt,
+ ),
+ ),
Effect.orElseSucceed(() => undefined),
);
@@ -1030,6 +1052,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
/* Provider events include streaming deltas; avoid a span for each update. */
Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) {
const usedTokens = nonNegativeInteger(usage, "totalTokens");
+ if (usedTokens !== undefined && usedTokens > 0) {
+ turn.lastMessageUsage = piMessageTokenUsage(usage);
+ }
if (
usedTokens === undefined ||
usedTokens === 0 ||
@@ -1040,9 +1065,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
return;
}
turn.lastLiveUsedTokens = usedTokens;
- const inputTokens = nonNegativeInteger(usage, "input");
- const cachedInputTokens = nonNegativeInteger(usage, "cacheRead");
- const outputTokens = nonNegativeInteger(usage, "output");
const updatedAt = yield* DateTime.now;
yield* emit({
type: "provider_turn.updated",
@@ -1053,9 +1075,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
tokenUsage: {
usedTokens,
maxTokens: contextWindow,
- ...(inputTokens === undefined ? {} : { inputTokens }),
- ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }),
- ...(outputTokens === undefined ? {} : { outputTokens }),
+ ...turn.lastMessageUsage,
updatedAt: DateTime.formatIso(updatedAt),
},
},
@@ -2075,9 +2095,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
}
const treeRefs =
turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs();
- const tokenUsage = readUsage
- ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt)
- : undefined;
+ const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined;
const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure);
yield* emit({
type: "provider_turn.updated",
@@ -3474,6 +3492,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* (
compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false),
latestCompactionAfterTokens: null,
lastLiveUsedTokens: null,
+ lastMessageUsage: undefined,
settleProbeGeneration: 0,
settleWhenIdle: false,
compactionCancelled: false,
diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts
index 4db5f263daba1..fffa0feb4014b 100644
--- a/packages/source-control-core/src/server/PullRequestProvider.ts
+++ b/packages/source-control-core/src/server/PullRequestProvider.ts
@@ -40,6 +40,7 @@ import type {
PullRequestPreview,
PullRequestUpdateMethod,
PullRequestViewerPermissions,
+ PullRequestVisibility,
SourceControlProviderKind,
} from "@t3tools/contracts";
import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts";
@@ -108,6 +109,8 @@ export interface ProviderChangeRequest {
readonly labels: ReadonlyArray;
readonly reviewDecision?: PullRequestReviewDecision | null | undefined;
readonly checksState?: PullRequestChecksState | null | undefined;
+ /** Absent where the host has no private change requests or names no visibility. */
+ readonly visibility?: PullRequestVisibility;
}
export interface ProviderChangeRequestSummary {
diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts
index 4a6e93ab74f45..ccf23f59b2258 100644
--- a/packages/source-control-core/src/server/SourceControlProvider.ts
+++ b/packages/source-control-core/src/server/SourceControlProvider.ts
@@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service<
}) => Effect.Effect;
/** True when `createChangeRequest` opens the change request as a draft when asked. */
readonly createsDraftChangeRequests?: boolean;
+ /**
+ * The private companion of the checkout's repository, made when it has none. The branch of
+ * a private change request is pushed to `url` and never to the repository itself, which
+ * everyone can read. Absent on a host without private change requests.
+ */
+ readonly privateChangeRequestRemote?: (input: {
+ readonly cwd: string;
+ readonly context?: SourceControlProviderContext;
+ }) => Effect.Effect<
+ { readonly url: string; readonly repository: string },
+ SourceControlProviderError
+ >;
readonly listChangeRequests: (input: {
readonly cwd: string;
readonly context?: SourceControlProviderContext;
@@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service<
readonly bodyFile: string;
/** Honored only by a provider with `createsDraftChangeRequests`. */
readonly draft?: boolean;
+ /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */
+ readonly private?: boolean;
}) => Effect.Effect;
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts
new file mode 100644
index 0000000000000..838309b037617
--- /dev/null
+++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts
@@ -0,0 +1,138 @@
+import { assert, describe, it } from "@effect/vitest";
+import * as Effect from "effect/Effect";
+import * as HttpClient from "effect/http/HttpClient";
+
+import * as TanStackSourceApi from "./TanStackSourceApi.ts";
+import * as Credentials from "./TanStackSourceCredentials.ts";
+import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts";
+
+const HOST = "source.tanstack.com";
+
+/**
+ * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the
+ * companion repository, and Source has stored no file or line counts for it.
+ */
+const PRIVATE_PULL = {
+ number: 42,
+ title: "Fix the thing",
+ state: "open",
+ visibility: "private",
+ draft: false,
+ author: "bob",
+ head: "acme:fix/thing",
+ createdAt: 1_000,
+ body: null,
+ base: "main",
+ headRepo: "acme/web.private",
+ headSha: "c".repeat(40),
+ baseSha: "b".repeat(40),
+ mergeCommitSha: null,
+ mergedAt: null,
+ mergedBy: null,
+ mergeable: null,
+ changedFiles: null,
+ changedLines: null,
+};
+
+const FILES = {
+ baseSha: "b".repeat(40),
+ headSha: "c".repeat(40),
+ mergeBaseSha: "b".repeat(40),
+ available: true,
+ truncated: false,
+ files: [
+ { path: "a.ts", status: "modified", additions: 3, deletions: 1 },
+ { path: "b.ts", status: "added", additions: 4, deletions: 0 },
+ ],
+};
+
+const RESPONSES: Record = {
+ "/repos/acme/web/pulls/42": PRIVATE_PULL,
+ "/repos/acme/web/pulls/42/files": FILES,
+ "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true },
+ "/repos/acme/web/pulls/42/stack": { members: [] },
+ [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [],
+ "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null },
+ "/repos/acme/web/issues/42": {
+ timeline: [
+ { id: 1, comment: "Looks good", author: "alice", at: 2_000 },
+ { event: "head_updated", actor: "bob", at: 3_000 },
+ ],
+ next: null,
+ },
+ "/repos/acme/web/pulls/42/comments": [],
+ "/repos/acme/web/pulls/42/commits": {
+ baseSha: null,
+ headSha: null,
+ mergeBaseSha: null,
+ available: true,
+ commits: [],
+ },
+ "/user": { username: "alice" },
+};
+
+const api = TanStackSourceApi.TanStackSourceApi.of({
+ request: (input) =>
+ input.path in RESPONSES
+ ? Effect.succeed(JSON.stringify(RESPONSES[input.path]))
+ : Effect.die(`unexpected ${input.path}`),
+ response: () => Effect.die("unexpected response read"),
+});
+
+const provider = TanStackSourcePullRequestProvider.make.pipe(
+ Effect.provideService(TanStackSourceApi.TanStackSourceApi, api),
+ Effect.provideService(
+ Credentials.TanStackSourceCredentials,
+ Credentials.TanStackSourceCredentials.of({
+ get: () => Effect.die("unexpected credential read"),
+ invalidate: () => Effect.void,
+ }),
+ ),
+ Effect.provideService(
+ HttpClient.HttpClient,
+ HttpClient.make(() => Effect.die("unexpected http request")),
+ ),
+);
+
+describe("TanStackSourcePullRequestProvider.getChangeRequest", () => {
+ // A client without this host's definition percent-encodes the owner's `@`; stored links
+ // keep the web's own spelling.
+ it.effect.each(["acme/web", "@acme/web", "%40acme/web"])(
+ "reads a private pull request of %s",
+ (repository) =>
+ Effect.gen(function* () {
+ const detail = yield* (yield* provider).getChangeRequest({
+ host: HOST,
+ repository,
+ number: 42,
+ cwd: "/repo",
+ });
+ assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`);
+ assert.strictEqual(detail.visibility, "private");
+ assert.strictEqual(detail.headBranch, "fix/thing");
+ assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private");
+ // Source stores no counts for it, so they come from its files.
+ assert.deepStrictEqual(
+ [detail.changedFiles, detail.additions, detail.deletions],
+ [2, 7, 1],
+ );
+ }),
+ );
+});
+
+describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => {
+ it.effect("reads the comments of a timeline that also holds events", () =>
+ Effect.gen(function* () {
+ const activity = yield* (yield* provider).getChangeRequestActivity({
+ host: HOST,
+ repository: "acme/web",
+ number: 42,
+ cwd: "/repo",
+ });
+ assert.deepStrictEqual(
+ activity.comments.map((comment) => comment.body),
+ ["Looks good"],
+ );
+ }),
+ );
+});
diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts
index 509e03e1f41f4..0529ce6df17c7 100644
--- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts
+++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts
@@ -35,6 +35,8 @@ const PULL = {
function checkout(options: {
readonly recordedOwner: string | null;
readonly isAncestor: boolean;
+ readonly pull?: Partial;
+ readonly force?: boolean;
}) {
const git: Array = [];
const config = new Map(
@@ -43,14 +45,28 @@ function checkout(options: {
const api = TanStackSourceApi.TanStackSourceApi.of({
request: (input) =>
input.path === "/repos/acme/web/pulls/42"
- ? Effect.succeed(JSON.stringify(PULL))
+ ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull }))
: Effect.die(`unexpected ${input.path}`),
response: () => Effect.die("unexpected response read"),
});
const host = TestSourceControlHost.layer({
git: {
resolvePrimaryRemoteName: () => Effect.succeed("origin"),
- ensureRemote: () => Effect.succeed("origin"),
+ ensureRemote: (input) =>
+ Effect.sync(() => {
+ git.push(`remote ${input.preferredName} ${input.url}`);
+ return input.url === REMOTE ? "origin" : input.preferredName;
+ }),
+ fetchRemoteBranch: (input) =>
+ Effect.sync(
+ () =>
+ void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`),
+ ),
+ fetchRemoteTrackingBranch: () => Effect.void,
+ setBranchUpstream: (input) =>
+ Effect.sync(
+ () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`),
+ ),
readConfigValue: (_cwd, key) =>
Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)),
writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)),
@@ -86,7 +102,13 @@ function checkout(options: {
},
});
const run = TanStackSourceSourceControlProvider.make.pipe(
- Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })),
+ Effect.flatMap((provider) =>
+ provider.checkoutChangeRequest({
+ cwd: "/repo",
+ reference: "42",
+ ...(options.force === undefined ? {} : { force: options.force }),
+ }),
+ ),
Effect.provideService(TanStackSourceApi.TanStackSourceApi, api),
Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))),
);
@@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => {
assert.isFalse(git.some((command) => command.startsWith("checkout")));
});
});
+
+ // Source publishes no `refs/pull//head` for a private pull request, on either repository.
+ it.effect("takes a private pull request's branch from the companion repository", () => {
+ const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" };
+ const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull });
+ const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true });
+ return Effect.gen(function* () {
+ yield* forced.run;
+ assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --");
+ yield* run;
+ assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme");
+ assert.deepStrictEqual(git, [
+ `remote source ${REMOTE}`,
+ "remote acme https://source.tanstack.com/@acme/web.private.git",
+ "fetch acme fix-thing:fix-thing",
+ "upstream fix-thing acme/fix-thing",
+ "switch fix-thing",
+ ]);
+ });
+ });
+});
+
+describe("TanStackSourceSourceControlProvider private pull requests", () => {
+ it.effect("asks Source for the companion and opens the pull request as private", () => {
+ const requests: Array<{ method: string; path: string; body: unknown }> = [];
+ const api = TanStackSourceApi.TanStackSourceApi.of({
+ request: (input) => {
+ requests.push({ method: input.method ?? "GET", path: input.path, body: input.body });
+ return Effect.succeed(
+ JSON.stringify({
+ owner: "acme",
+ name: "web.private",
+ defaultBranch: null,
+ cloneUrl: "https://source.tanstack.com/@acme/web.private.git",
+ }),
+ );
+ },
+ response: () => Effect.die("unexpected response read"),
+ });
+ const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") });
+ return Effect.gen(function* () {
+ const provider = yield* TanStackSourceSourceControlProvider.make;
+ const companion = provider.privateChangeRequestRemote;
+ assert.isDefined(companion);
+ assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), {
+ url: "https://source.tanstack.com/@acme/web.private.git",
+ repository: "acme/web.private",
+ });
+ yield* provider.createChangeRequest({
+ cwd: "/repo",
+ baseRefName: "main",
+ headSelector: "sec/fix",
+ title: "Fix",
+ bodyFile: "/tmp/body.md",
+ private: true,
+ });
+ assert.deepStrictEqual(requests, [
+ { method: "POST", path: "/repos/acme/web/private-remote", body: undefined },
+ {
+ method: "POST",
+ path: "/repos/acme/web/pulls",
+ body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true },
+ },
+ ]);
+ }).pipe(
+ Effect.provideService(TanStackSourceApi.TanStackSourceApi, api),
+ Effect.provide(
+ Layer.merge(
+ TestSourceControlHost.layer({
+ git: {
+ resolvePrimaryRemoteName: () => Effect.succeed("origin"),
+ readConfigValue: () => Effect.succeed(REMOTE),
+ },
+ }),
+ files,
+ ),
+ ),
+ );
+ });
});
diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts
index a1abb376b472d..f194848611361 100644
--- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts
+++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts
@@ -395,6 +395,18 @@ export const make = Effect.gen(function* () {
},
),
createsDraftChangeRequests: true,
+ privateChangeRequestRemote: Effect.fn(
+ "TanStackSourceSourceControlProvider.privateChangeRequestRemote",
+ )(function* (input) {
+ const target = yield* resolveTarget("privateChangeRequestRemote", input);
+ const companion = yield* read(
+ "privateChangeRequestRemote",
+ input.cwd,
+ { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` },
+ Repository,
+ );
+ return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` };
+ }),
createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")(
function* (input) {
const target = yield* resolveTarget("createChangeRequest", {
@@ -437,6 +449,7 @@ export const make = Effect.gen(function* () {
base: input.target?.refName ?? input.baseRefName,
...(body.trim().length === 0 ? {} : { body }),
...(input.draft === true ? { draft: true } : {}),
+ ...(input.private === true ? { private: true } : {}),
},
})
.pipe(
@@ -494,7 +507,8 @@ export const make = Effect.gen(function* () {
return repository.defaultBranch;
},
),
- // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too.
+ // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A
+ // private one has no such ref: its branch is read from the companion repository.
checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")(
function* (input) {
const pull = yield* getPull(input);
@@ -519,9 +533,26 @@ export const make = Effect.gen(function* () {
});
const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest";
const branches = yield* git.listLocalBranchNames(input.cwd);
- if (!pull.isCrossRepository) {
+ const companion =
+ pullRepository !== null &&
+ pull.headRepositoryNameWithOwner?.toLowerCase() ===
+ `${pullRepository}.private`.toLowerCase()
+ ? pull.headRepositoryNameWithOwner
+ : null;
+ if (!pull.isCrossRepository || companion !== null) {
const localBranch = pull.headRefName;
- const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch };
+ const remoteBranch = {
+ cwd: input.cwd,
+ remoteName:
+ companion === null
+ ? remoteName
+ : yield* git.ensureRemote({
+ cwd: input.cwd,
+ preferredName: companion.split("/")[0] ?? "private",
+ url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`,
+ }),
+ remoteBranch: localBranch,
+ };
if (input.force !== true && !branches.includes(localBranch))
yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch });
else yield* git.fetchRemoteTrackingBranch(remoteBranch);
@@ -535,11 +566,18 @@ export const make = Effect.gen(function* () {
"--no-track",
"-B",
localBranch,
- `refs/remotes/${remoteName}/${localBranch}`,
+ `refs/remotes/${remoteBranch.remoteName}/${localBranch}`,
"--",
],
});
yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch });
+ // Whatever push defaults say, this branch must not be published to the public remote.
+ if (companion !== null)
+ yield* git.writeConfigValue({
+ cwd: input.cwd,
+ key: `branch.${localBranch}.pushRemote`,
+ value: remoteBranch.remoteName,
+ });
yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch }));
return;
}
diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts
new file mode 100644
index 0000000000000..ac43a46ccdcad
--- /dev/null
+++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts";
+
+describe("tanStackSourceRepositoryPath", () => {
+ it.each([
+ ["acme/web", "acme/web"],
+ ["@acme/web", "acme/web"],
+ // Clients without this host's definition percent-encode the owner's `@`.
+ ["%40acme/web", "acme/web"],
+ ["/@acme/web.git/", "acme/web"],
+ ["acme/web.private", "acme/web.private"],
+ ["acme", null],
+ ["acme/web/extra", null],
+ ["acme/..", null],
+ ])("reads %s as %s", (path, repository) => {
+ expect(tanStackSourceRepositoryPath(path)).toBe(repository);
+ });
+});
diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts
index 22923264629bf..dfa6d4e9031a0 100644
--- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts
+++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts
@@ -1,4 +1,4 @@
-import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts";
+import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts";
export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const;
export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number];
@@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null {
const SEGMENT = /^[A-Za-z0-9_.-]+$/u;
-/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */
+/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */
export function tanStackSourceRepositoryPath(path: string): string | null {
- const [owner, name, ...rest] = path
- .trim()
- .replace(/^\/+|\/+$/gu, "")
- .replace(/\.git$/u, "")
- .replace(/^@/u, "")
- .split("/");
+ const [owner, name, ...rest] = withoutOwnerMark(
+ path
+ .trim()
+ .replace(/^\/+|\/+$/gu, "")
+ .replace(/\.git$/u, ""),
+ ).split("/");
return rest.length === 0 &&
owner !== undefined &&
name !== undefined &&
diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts
index 4d698fb881dfb..24c93e6aac83d 100644
--- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts
+++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts
@@ -146,6 +146,7 @@ describe("toActivity", () => {
["4", "review-comment", null],
]);
expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`);
+ expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`);
expect(activity.reviewThreads).toMatchObject([
{ id: "4", path: "a.ts", line: 2, side: "left", isResolved: true },
]);
diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts
index acf3c4158f95c..51537627ca3e7 100644
--- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts
+++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts
@@ -16,6 +16,8 @@ import type {
import * as DateTime from "effect/DateTime";
import * as Schema from "effect/Schema";
+import { withoutOwnerMark } from "../shared/definition.ts";
+
/** Source sends times as epoch milliseconds. */
const EpochMillis = Schema.Finite;
const Login = Schema.String;
@@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({
labels: Schema.optional(Schema.Array(Schema.String)),
head: Schema.String,
createdAt: EpochMillis,
+ visibility: Schema.optional(Schema.String),
});
export type SourcePull = typeof SourcePull.Type;
@@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({
type TimelineEntry = typeof TimelineEntry.Type;
export const SourceTimeline = Schema.Struct({
- timeline: Schema.Array(TimelineEntry),
+ // Events such as `head_updated` sit between the comments and carry no id.
+ timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])),
next: Schema.NullOr(Schema.String),
});
@@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String });
export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis));
export const pullUrl = (host: string, repository: string, number: number) =>
- `https://${host}/@${repository}/pull/${number}`;
+ `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`;
-/** A GitHub-synced pull request from a fork names its head only by its pull ref. */
-export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, "");
+/**
+ * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private
+ * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede.
+ */
+export const headBranchName = (head: string) =>
+ head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, "");
+
+/** Absent when Source names no visibility, so a reader tells unknown from public. */
+const visibilityOf = (pull: Pick) =>
+ pull.visibility === "private" || pull.visibility === "public"
+ ? { visibility: pull.visibility }
+ : {};
export function toActor(login: string | null, host: string): PullRequestActor | null {
if (login === null || login.trim() === "") return null;
@@ -280,6 +294,7 @@ export function toChangeRequest(
baseBranch: pull.base ?? "",
state: pull.state,
isDraft: pull.draft,
+ ...visibilityOf(pull),
mergeability: "unknown",
additions: 0,
deletions: 0,
@@ -380,7 +395,9 @@ export function toActivity(input: {
}): ProviderChangeRequestActivity {
const { host } = input;
const page = pullUrl(host, input.repository, input.number);
- const entries = input.timeline.timeline.filter(visible);
+ const entries = input.timeline.timeline.filter(
+ (entry): entry is TimelineEntry => "id" in entry && visible(entry),
+ );
const comments: Array = entries.map((entry: TimelineEntry) => ({
id: String(entry.id),
kind:
diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts
index e3ce5c867fa5c..6e09a89fa2cda 100644
--- a/packages/source-control-tanstack-source/src/shared/definition.test.ts
+++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts
@@ -31,7 +31,23 @@ describe("TanStack Source definition", () => {
number: 7,
}),
).toBe("https://source.tanstack.com/@TanStack/router/pull/7");
+ // A stored link or an older client may name the repository as the web spells it.
+ for (const repository of ["@TanStack/router", "%40TanStack/router"])
+ expect(
+ definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }),
+ repository,
+ ).toBe("https://source.tanstack.com/@TanStack/router/pull/7");
expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7");
expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull();
});
+
+ it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])(
+ "keys %s as the API's owner/name",
+ (repository) => {
+ expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe(
+ "source.tanstack.com/tanstack/router",
+ );
+ expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull();
+ },
+ );
});
diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts
index 1aee00c968dc6..032adc5a45cdd 100644
--- a/packages/source-control-tanstack-source/src/shared/definition.ts
+++ b/packages/source-control-tanstack-source/src/shared/definition.ts
@@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) {
: { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` };
}
+/**
+ * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this
+ * definition percent-encodes that as `%40owner/name`.
+ */
+export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, "");
+
+/** Links stored with the web's spelling compare equal to the project's own key. */
+function canonicalRepositoryKey(key: string): string | null {
+ const slash = key.indexOf("/");
+ return slash > 0 && isTanStackSourceHost(key.slice(0, slash))
+ ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}`
+ : null;
+}
+
/** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */
function repositoryKeyFromRemote(key: string): string | null {
// Remote parsing spells the `@` percent-encoded.
@@ -80,13 +94,13 @@ export const definition = defineSourceControl({
? null
: webUrl
? changeRequestUrlBelow(webUrl, `pull/${number}`)
- : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`,
+ : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`,
parseChangeRequestUrl,
commitUrl: (input) =>
buildCommitUrl(
input.webUrl
? input
- : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` },
+ : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` },
"commit",
),
parseIssueUrl: (url) =>
@@ -122,6 +136,7 @@ export const definition = defineSourceControl({
checkoutChangeRequestHost: () => null,
changeRequestHeadRef: (number) => `refs/pull/${number}/head`,
repositoryKeyFromRemote,
+ canonicalRepositoryKey,
recognizeRemote: ({ hostname }) =>
isTanStackSourceHost(hostname)
? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` }
diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts
new file mode 100644
index 0000000000000..acd9096465978
--- /dev/null
+++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts
@@ -0,0 +1,75 @@
+import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts";
+import { expect } from "e2e";
+import * as Effect from "effect/Effect";
+import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
+
+import { T3_HOME } from "../e2e.config.ts";
+import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
+
+const PROMPT_LOG_LIMIT = 64 * 1024;
+const FRAME_OPEN = "".length;
+
+const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")(
+ function* (origin: string) {
+ const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]);
+ const { projects } = yield* HttpClient.execute(
+ HttpClientRequest.get(`${origin}/api/projects`).pipe(
+ HttpClientRequest.bearerToken(issued.stdout.trim()),
+ ),
+ ).pipe(
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)),
+ );
+ const client = yield* rpcClient(T3_HOME, origin);
+ const { task } = yield* client["scheduledTasks.upsert"]({
+ title: "Webhook log",
+ prompt: "{{body.text}}",
+ enabled: true,
+ schedule: { type: "webhook" },
+ projectId: projects.find((project) => project.title === "webhook-log")!.id,
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ });
+ // The emoji's high surrogate is the last code unit the delivery log keeps.
+ const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`;
+ yield* HttpClient.execute(
+ HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe(
+ HttpClientRequest.bodyJsonUnsafe({ text }),
+ ),
+ ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk));
+ },
+ Effect.scoped,
+ Effect.provide(FetchHttpClient.layer),
+);
+
+test(
+ "A long webhook prompt in the delivery log does not end in a broken character",
+ WEB,
+ async ({ t3, app, browser, screen }) => {
+ await t3.project("webhook-log");
+ await runPromise(deliverStraddlingEmoji(app.baseUrl ?? ""));
+
+ await t3.open("/settings/scheduled-tasks");
+ await screen.getByRole("button", "Actions for Webhook log").tap();
+ await screen.getByRole("menuitem", "Deliveries").tap();
+ const dialog = screen.getByRole("dialog");
+ await dialog.getByRole("button", /POST/).tap();
+ const prompt = dialog.getByText(/^ {
+ const block = [...document.querySelectorAll("pre")].find((pre) =>
+ pre.textContent?.startsWith("