Compare commits

..
Author SHA1 Message Date
maria-rcks 355a1c5985 fix(server): dedupe codex subagent item events 2026-08-06 22:56:22 -04:00
327 changed files with 11382 additions and 35923 deletions

No files matched your search

+15 -4
View File
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
## Authenticate the browser on the first navigation
@@ -50,13 +50,24 @@ Treat the overall testing or implementation loop—not an assistant turn or one
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
## Recover a consumed or expired pairing token
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
Create another token against the same database and web URL as the running dev server:
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
+9 -12
View File
@@ -1,14 +1,12 @@
# Optional: T3 Connect source builds
# `cp .env.example .env` enables T3 Connect against the production deployment.
# These are the same public identifiers baked into official release builds, not
# secrets. Remove or comment them out to build with cloud features disabled.
# Do not add server-side secrets to this file.
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
# under API keys, JWT templates, and OAuth applications.
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
@@ -17,9 +15,8 @@ T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
# automatically.
T3CODE_RELAY_URL=https://relay.t3.codes
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
-4
View File
@@ -11,11 +11,9 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:gfsaaser24
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
@@ -27,9 +25,7 @@ github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:saphid
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
-429
View File
@@ -1,429 +0,0 @@
const fs = require("node:fs");
const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"threadSnapshotDecodedBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const CEILING_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const SCENARIO_KEYS = [
"id",
"historyTurns",
"historyCommandToolsPerTurn",
"historyMcpResultBytes",
"measuredCommandTools",
"measuredMcpResultBytes",
];
function resultShaMarker(sha) {
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function assertExactKeys(value, expected, label) {
assertObject(value, label);
const actual = Object.keys(value).sort();
const wanted = [...expected].sort();
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
throw new Error(`${label} has unexpected fields`);
}
}
function assertMetric(value, label) {
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
}
}
function validateResult(value) {
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
if (value.schemaVersion !== 1) {
throw new Error("result.schemaVersion must be 1");
}
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
if (value.scenario.id !== "thread-transfer-v1") {
throw new Error("result.scenario.id is not supported");
}
for (const key of SCENARIO_KEYS.slice(1)) {
assertMetric(value.scenario[key], `result.scenario.${key}`);
}
assertExactKeys(value.providers, PROVIDERS, "result.providers");
for (const provider of PROVIDERS) {
const entry = value.providers[provider];
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
for (const key of OBSERVED_KEYS) {
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
}
for (const key of CEILING_KEYS) {
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
}
}
return value;
}
function readResult(directory) {
if (!directory) return undefined;
const file = path.join(directory, RESULT_FILE);
if (!fs.existsSync(file)) return undefined;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.size > 64 * 1_024) {
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
}
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
}
function formatBytes(bytes) {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
return `${(bytes / 1_024).toFixed(1)} KiB`;
}
function formatValue(value, kind) {
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
}
function formatImpact(current, baseline, kind) {
if (baseline === undefined) return "—";
const delta = current - baseline;
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
const magnitude = formatValue(Math.abs(delta), kind);
const percent =
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
return `${prefix}${magnitude}${percent}`;
}
function sameScenario(left, right) {
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
}
const METRICS = [
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
{
key: "measuredTurnWebSocketWireBytes",
label: "Live turn WebSocket wire",
kind: "bytes",
},
{
key: "measuredTurnWebSocketDecodedBytes",
label: "Live turn WebSocket decoded",
kind: "bytes",
},
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
const rows = [];
const ceilingChanges = [];
let failed = false;
for (const provider of PROVIDERS) {
for (const metric of METRICS) {
const observed = current.providers[provider].observed[metric.key];
const ceiling = current.providers[provider].ceiling[metric.key];
const baselineObserved = comparable
? baseline.providers[provider].observed[metric.key]
: undefined;
const pass = observed <= ceiling;
failed ||= !pass;
rows.push(
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
ceilingChanges.push(
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
: "unavailable";
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
const notices = [];
if (!baseline) {
notices.push(
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
);
} else if (!comparable) {
notices.push(
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
);
} else if (!input.baselineRun.matchesBase) {
notices.push(
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
);
}
if (ceilingChanges.length > 0) {
notices.push(
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
);
}
return [
COMMENT_MARKER,
resultShaMarker(input.currentRun.sha),
"## Thread transfer impact",
"",
failed
? "❌ One or more thread transfer ceilings were exceeded."
: "✅ Thread transfer remains within every enforced ceiling.",
...(notices.length > 0 ? ["", ...notices] : []),
"",
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"<details>",
"<summary>Scenario and decoded snapshot size</summary>",
"",
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
"",
...PROVIDERS.map(
(provider) =>
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
"</details>",
"",
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
].join("\n");
}
async function artifactsForRun(github, owner, repo, runId) {
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
owner,
repo,
run_id: runId,
per_page: 100,
});
}
function findResultArtifact(artifacts) {
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
}
async function resolve({ github, context, core }) {
const source = context.payload.workflow_run;
const { owner, repo } = context.repo;
if (source.event !== "pull_request") {
core.setOutput("publish", "false");
return;
}
let pullNumber = source.pull_requests?.[0]?.number;
if (!pullNumber) {
const associated = await github.paginate(
github.rest.repos.listPullRequestsAssociatedWithCommit,
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
);
const matchingPulls = associated.filter(
(pull) =>
pull.state === "open" &&
pull.head.sha === source.head_sha &&
pull.head.ref === source.head_branch,
);
if (matchingPulls.length !== 1) {
core.info(
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
);
core.setOutput("publish", "false");
return;
}
pullNumber = matchingPulls[0].number;
}
if (!pullNumber) {
core.info("No open pull request is associated with the completed CI run.");
core.setOutput("publish", "false");
return;
}
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
if (pull.head.sha !== source.head_sha) {
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
core.setOutput("publish", "false");
return;
}
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
const sourceArtifact = findResultArtifact(sourceArtifacts);
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: source.workflow_id,
branch: pull.base.ref,
event: "push",
status: "success",
per_page: 100,
});
const orderedRuns = [
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
].slice(0, 20);
let baselineRun;
for (const run of orderedRuns) {
const artifacts = await artifactsForRun(github, owner, repo, run.id);
if (findResultArtifact(artifacts)) {
baselineRun = run;
break;
}
}
core.setOutput("publish", "true");
core.setOutput("pull_number", String(pullNumber));
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
core.setOutput("pr_run_id", String(source.id));
core.setOutput("pr_sha", source.head_sha);
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
core.setOutput(
"baseline_matches_base",
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
);
}
async function upsertComment(github, context, pullNumber, body, options = {}) {
const { owner, repo } = context.repo;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(
(comment) =>
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
);
if (
options.preserveResultSha &&
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
) {
return;
}
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
}
}
async function upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
expectedSha,
body,
options,
) {
const { owner, repo } = context.repo;
const { data: pull } = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (pull.head.sha !== expectedSha) {
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
return false;
}
await upsertComment(github, context, pullNumber, body, options);
return true;
}
async function publish({ github, context, core }) {
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
throw new Error("PR_NUMBER is invalid");
}
const current = readResult(process.env.PR_RESULT_DIR);
const currentRun = {
sha: process.env.PR_SHA,
conclusion: process.env.PR_CONCLUSION,
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
};
if (!current) {
await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
[
COMMENT_MARKER,
"## Thread transfer impact",
"",
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
"",
"_This comment will update automatically after the next completed run._",
].join("\n"),
{ preserveResultSha: currentRun.sha },
);
return;
}
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
const baselineRun = baseline
? {
sha: process.env.BASELINE_SHA,
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
}
: undefined;
const body = renderComment({ current, baseline, currentRun, baselineRun });
const published = await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
body,
);
if (published) {
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
}
}
module.exports = {
publish,
readResult,
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
};
@@ -1,292 +0,0 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const {
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
const observed = {
totalWireBytes: 2_200_000,
threadSnapshotWireBytes: 1_950_000,
threadSnapshotDecodedBytes: 9_100_000,
measuredTurnWebSocketWireBytes: 250_000,
measuredTurnWebSocketDecodedBytes: 1_150_000,
measuredTurnWebSocketMessages: 15,
};
const ceiling = {
totalWireBytes: 2_900_000,
threadSnapshotWireBytes: 2_600_000,
measuredTurnWebSocketWireBytes: 320_000,
measuredTurnWebSocketDecodedBytes: 1_550_000,
measuredTurnWebSocketMessages: 20,
};
return {
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: 10,
historyCommandToolsPerTurn: 5,
historyMcpResultBytes: 900_000,
measuredCommandTools: 20,
measuredMcpResultBytes: 1_100_000,
},
providers: {
codex: { observed: { ...observed, ...overrides }, ceiling },
claudeAgent: { observed, ceiling },
},
};
}
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
/unexpected fields/,
);
assert.throws(
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
});
test("renders baseline, impact, ceiling, and ceiling changes", () => {
const baseline = result();
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
current.providers.codex.ceiling = {
...current.providers.codex.ceiling,
measuredTurnWebSocketWireBytes: 330_000,
};
const comment = renderComment({
current,
baseline,
currentRun: {
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
conclusion: "success",
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
},
baselineRun: {
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
matchesBase: true,
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
},
});
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
assert.match(comment, /This PR changes transfer ceilings/);
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
assert.match(
comment,
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
const outputs = {};
const listWorkflowRunArtifacts = () => {};
const listWorkflowRuns = () => {};
const listPullRequestsAssociatedWithCommit = () => {};
const github = {
paginate: async (method, input) => {
if (method === listPullRequestsAssociatedWithCommit) {
return [
{
number: 5350,
state: "open",
head: { sha: "head-sha", ref: "feature-branch", repo: null },
},
];
}
if (method === listWorkflowRunArtifacts) {
return [
{
name: "thread-transfer-results",
expired: false,
runId: input.run_id,
},
];
}
if (method === listWorkflowRuns) {
return [{ id: 1, head_sha: "base-sha" }];
}
throw new Error("unexpected pagination call");
},
rest: {
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
pulls: {
get: async () => ({
data: {
head: { sha: "head-sha" },
base: { sha: "base-sha", ref: "main" },
},
}),
},
repos: { listPullRequestsAssociatedWithCommit },
},
};
await resolve({
github,
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "true");
assert.equal(outputs.pull_number, "5350");
assert.equal(outputs.pr_artifact, "true");
assert.equal(outputs.baseline_run_id, "1");
assert.equal(outputs.baseline_matches_base, "true");
});
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
const outputs = {};
const listPullRequestsAssociatedWithCommit = () => {};
let fetchedPull = false;
await resolve({
github: {
paginate: async (method) => {
assert.equal(method, listPullRequestsAssociatedWithCommit);
return [5350, 5351].map((number) => ({
number,
state: "open",
head: {
sha: "head-sha",
ref: "feature-branch",
repo: { full_name: "pingdotgg/t3code" },
},
}));
},
rest: {
actions: {},
pulls: {
get: async () => {
fetchedPull = true;
},
},
repos: { listPullRequestsAssociatedWithCommit },
},
},
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "false");
assert.equal(fetchedPull, false);
});
test("does not publish a stale result after the PR head advances", async () => {
let listedComments = false;
const info = [];
const published = await upsertCommentForCurrentHead(
{
paginate: async () => {
listedComments = true;
return [];
},
rest: {
issues: {
listComments: () => {},
createComment: () => {
throw new Error("must not create a stale comment");
},
updateComment: () => {
throw new Error("must not update a stale comment");
},
},
pulls: {
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: (message) => info.push(message) },
5350,
"old-head-sha",
"stale body",
);
assert.equal(published, false);
assert.equal(listedComments, false);
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
});
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
let updatedComment = false;
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const published = await upsertCommentForCurrentHead(
{
paginate: async () => [
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
},
],
rest: {
issues: {
listComments: () => {},
createComment: () => {
updatedComment = true;
},
updateComment: () => {
updatedComment = true;
},
},
pulls: {
get: async () => ({ data: { head: { sha } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: () => {} },
5350,
sha,
"missing artifact warning",
{ preserveResultSha: sha },
);
assert.equal(published, true);
assert.equal(updatedComment, false);
});
-21
View File
@@ -84,29 +84,8 @@ jobs:
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
env:
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
run: vp run test
- name: Publish transfer budget report
if: always()
run: |
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
else
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
fi
- name: Upload thread transfer result
if: always()
uses: actions/upload-artifact@v7
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer-result.json
if-no-files-found: ignore
retention-days: 30
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
@@ -1,75 +0,0 @@
name: Thread Transfer Report
on:
workflow_run:
workflows: [CI]
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
jobs:
publish:
name: Publish PR comment
if: github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-24.04
concurrency:
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
cancel-in-progress: true
steps:
# workflow_run has a write-capable token even for fork PRs. Only load the
# publisher from the trusted default branch and never execute PR code.
- name: Checkout trusted publisher
uses: actions/checkout@v6
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
- name: Test trusted publisher
run: node --test .github/scripts/thread-transfer-report.test.cjs
- id: resolve
name: Resolve PR and baseline artifacts
uses: actions/github-script@v8
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.resolve({ github, context, core });
- name: Download PR result
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/pr
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.pr_run_id }}
- name: Download main baseline
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/main
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
- name: Update thread transfer comment
if: steps.resolve.outputs.publish == 'true'
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.publish({ github, context, core });
+2 -2
View File
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.32",
"version": "0.0.31",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -78,7 +78,6 @@ describe("DesktopLifecycle", () => {
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -91,7 +91,6 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -23,21 +23,6 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
}
}
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
"ElectronDialogPickFilesError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
@@ -84,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogPickFilesError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
@@ -97,12 +81,6 @@ export interface ElectronDialogPickFolderInput {
readonly defaultPath: Option.Option<string>;
}
export interface ElectronDialogPickFilesInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
readonly filters: readonly Electron.FileFilter[];
}
export interface ElectronDialogConfirmInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly message: string;
@@ -114,9 +92,6 @@ export class ElectronDialog extends Context.Service<
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly pickFiles: (
input: ElectronDialogPickFilesInput,
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
@@ -162,32 +137,6 @@ export const make = ElectronDialog.of({
}
return Option.fromNullishOr(result.filePaths[0]);
}),
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = {
properties: ["openFile", "multiSelections"],
filters: [...input.filters],
...(defaultPath === null ? {} : { defaultPath }),
};
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogPickFilesError({
ownerWindowId,
defaultPath,
cause,
}),
});
return result.canceled ? [] : result.filePaths;
}),
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
@@ -38,7 +38,6 @@ import {
getWindowFullscreenState,
openExternal,
pickFolder,
pickThemeFiles,
setTheme,
showContextMenu,
} from "./methods/window.ts";
@@ -80,7 +79,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
-1
View File
@@ -1,5 +1,4 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
-51
View File
@@ -3,15 +3,10 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -273,49 +268,3 @@ export const openExternal = DesktopIpc.makeIpcMethod({
return yield* shell.openExternal(url);
}),
});
/** Theme files are a few KB; anything larger returns empty text and lets the
* renderer reject it by size without the contents ever crossing the bridge. */
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
payload: Schema.Undefined,
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// The VS Code extensions directory is the same dotfolder on Windows,
// macOS, and Linux; when it is missing the picker opens wherever the
// platform would by default.
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
const defaultPath = yield* fileSystem
.exists(extensionsDir)
.pipe(Effect.orElseSucceed(() => false));
const paths = yield* dialog.pickFiles({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
filters: [{ name: "JSON", extensions: ["json"] }],
});
if (paths.length === 0) {
return null;
}
return yield* Effect.forEach(paths, (filePath) => {
const name = path.basename(filePath);
return Effect.gen(function* () {
const info = yield* fileSystem.stat(filePath);
const size = Number(info.size);
if (size > PICKED_THEME_FILE_MAX_BYTES) {
return { name, size, text: "" } satisfies PickedThemeFile;
}
const text = yield* fileSystem.readFileString(filePath);
return { name, size, text } satisfies PickedThemeFile;
}).pipe(
// An unreadable file degrades to an entry the renderer reports.
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
);
});
}),
});
-1
View File
@@ -97,7 +97,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
@@ -13,6 +13,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
@@ -29,7 +30,6 @@ const clientSettings: ClientSettings = {
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
@@ -39,7 +39,8 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
legacySidebarEnabled: false,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -52,7 +52,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
pickFiles: () => Effect.succeed([]),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
@@ -81,8 +80,6 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -96,30 +93,6 @@ const makeElectronMenuLayer = (
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -127,7 +100,25 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -146,38 +137,4 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
// zoom roles: the roles zoom whichever webContents has focus, which breaks
// app zoom while an embedded preview WebContentsView holds focus.
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const viewMenu = template.find((item) => item.label === "View");
assert.isDefined(viewMenu);
if (!Array.isArray(viewMenu.submenu)) {
throw new Error("Expected View menu submenu to be an array.");
}
assert.isUndefined(
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
);
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
assert.isDefined(zoomIn);
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
if (typeof zoomIn.click !== "function") {
throw new Error("Expected Zoom In menu item to have a click handler.");
}
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
}),
);
});
@@ -49,13 +49,6 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
direction: DesktopWindow.MainWindowZoomDirection,
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.zoomMain(direction);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -134,9 +127,6 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -191,21 +181,10 @@ export const make = Effect.gen(function* () {
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
/*
Not the zoom roles: those act on the focused webContents, so with
an embedded preview WebContentsView focused they zoom the guest
page and the app UI appears stuck. These always zoom the main
window (see DesktopWindow.zoomMain).
*/
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
{
label: "Zoom In",
accelerator: "CmdOrCtrl+Plus",
visible: false,
click: zoomClick("in"),
},
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
-20
View File
@@ -61,8 +61,6 @@ export type DesktopWindowError =
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export type MainWindowZoomDirection = "in" | "out" | "reset";
export class DesktopWindow extends Context.Service<
DesktopWindow,
{
@@ -89,12 +87,6 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
// Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
// menu roles act on whichever webContents has keyboard focus, so with an
// embedded preview WebContentsView (or DevTools) focused they zoom the
// guest page instead of the app UI. The menu routes here to always target
// the main window.
readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -844,18 +836,6 @@ export const make = Effect.gen(function* () {
send();
}),
zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
yield* Effect.annotateCurrentSpan({ direction });
const window = yield* focusedMainWindow;
if (Option.isNone(window) || window.value.isDestroyed()) {
return;
}
const webContents = window.value.webContents;
// Same step size as the Electron zoomIn/zoomOut menu roles.
webContents.setZoomLevel(
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
);
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
+1 -1
View File
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
</div>
<p class="releases-link">
Looking for older versions? Check the{" "}
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
+1 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.2",
version: "1.0.1",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
@@ -535,12 +535,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
return
}
if buffer.isEmpty {
feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
lastAppliedBuffer = ""
return
}
if buffer.hasPrefix(lastAppliedBuffer) {
let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
feedData(Data(suffix.utf8))
-5
View File
@@ -138,10 +138,5 @@
"@react-native-menu/menu"
]
}
},
"reanimated": {
"staticFeatureFlags": {
"DISABLE_COMMIT_PAUSING_MECHANISM": true
}
}
}
@@ -16,18 +16,6 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
/**
* Horizontal correction applied to content rendered in the brand title slot,
* shared with the connection-status swap so both align identically.
*/
export function brandTitleOffset(nativeLeadingItem: boolean): number {
if (Platform.OS !== "ios") return 0;
if (nativeLeadingItem) {
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
}
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
}
/**
* Compact brand lockup sized for native navigation bars.
*/
@@ -40,7 +28,16 @@ export function CompactBrandTitle(
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
const titleOffset =
Platform.OS !== "ios"
? 0
: props.nativeLeadingItem
? Platform.isPad
? IPAD_NATIVE_LEADING_TITLE_OFFSET
: IOS_NATIVE_LEADING_TITLE_OFFSET
: Platform.isPad
? IPAD_HOME_TITLE_OFFSET
: 0;
return (
<View
@@ -21,7 +21,6 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
@@ -43,11 +42,6 @@ interface CloudEnvironmentRowsProps {
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*
* Already-connected relay environments render even without cloud config or a
* signed-in account — they are registered on this device and must stay
* reachable and removable. Only discovery (the available list, refresh, and
* its errors) requires a signed-in session.
*/
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
@@ -56,33 +50,20 @@ export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
if (props.showcaseSignedIn !== undefined) {
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
}
// No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
if (!hasCloudPublicConfig()) {
return <ConnectedOnlyCloudEnvironmentRows {...props} />;
}
return <SignedInCloudEnvironmentRows {...props} />;
}
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
if (!isSignedIn) return null;
return <CloudEnvironmentRowsContent {...props} />;
}
function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
if (props.connectedCloudEnvironments.length === 0) return null;
return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
}
function CloudEnvironmentRowsContent(
props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
) {
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const discoveryAvailable = props.discoveryAvailable ?? true;
const availableCloudEnvironments = discoveryAvailable
? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
: [];
const availableCloudEnvironments =
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
@@ -108,27 +89,25 @@ function CloudEnvironmentRowsContent(
{showHeader ? (
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
{discoveryAvailable ? (
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
) : null}
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
</View>
) : null}
@@ -173,9 +152,7 @@ function CloudEnvironmentRowsContent(
{/* Rendered alongside any connected rows — a failed discovery must not
hide behind an otherwise-healthy list. */}
{discoveryAvailable &&
controller.relayDiscovery.error &&
!controller.relayDiscovery.isRefreshing ? (
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Connect environments
@@ -58,8 +58,8 @@ export function ConnectionsRouteScreen() {
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
+12 -23
View File
@@ -21,7 +21,6 @@ import {
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import { WorkspaceConnectionTitle } from "./WorkspaceConnectionTitle";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
@@ -48,7 +47,6 @@ export function HomeHeader(props: {
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
@@ -209,27 +207,18 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
>
<View className="w-full max-w-[720px] self-center gap-3">
<View className="flex-row items-center gap-2.5">
{/* Brand slot doubles as the connection status surface: while an
environment reconnects, the lockup fades to a status label in
place (no layout shift in the list below). */}
<WorkspaceConnectionTitle
grow
onPress={props.onOpenEnvironments}
brand={
<View className="flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
}
/>
<View className="flex-1 flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
<ControlPillMenu
actions={menuActions}
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -19,7 +20,6 @@ import { useHomeListOptions } from "./home-list-options";
import { buildHomeProjectScopes } from "./homeThreadList";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -44,7 +44,6 @@ export function HomeRouteScreen() {
unsnoozeThread,
pinThread,
unpinThread,
movePinnedThread,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -127,16 +126,8 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title after the split branch blanks the detail
header. The brand slot doubles as the connection status surface:
while an environment reconnects, the lockup fades to a status label
in place (no layout shift in the list below). */}
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
})}
/>
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
@@ -147,9 +138,6 @@ export function HomeRouteScreen() {
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
@@ -171,9 +159,11 @@ export function HomeRouteScreen() {
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
+41 -49
View File
@@ -11,7 +11,6 @@ import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -72,6 +71,8 @@ import {
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -96,6 +97,7 @@ interface HomeScreenProps {
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
@@ -111,10 +113,6 @@ interface HomeScreenProps {
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onMovePinnedThread: (
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -526,12 +524,6 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onPinThread],
);
const handleMovePinnedThread = useCallback(
(thread: EnvironmentThreadShell, direction: "up" | "down") => {
void props.onMovePinnedThread(thread, direction);
},
[props.onMovePinnedThread],
);
const handleUnpinThread = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onUnpinThread(thread);
@@ -606,29 +598,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinReorderEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinReorder === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
const arrangedPinnedKeys = useMemo(() => {
const pinned = sortPinnedThreadsByOrderKey(
props.threads.filter(
(thread) =>
thread.pinnedAt != null &&
thread.archivedAt === null &&
pinReorderEnvironmentIds.has(thread.environmentId),
),
);
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
}, [pinReorderEnvironmentIds, props.threads]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -815,18 +784,11 @@ export function HomeScreen(props: HomeScreenProps) {
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
canMovePinnedUp={arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0}
canMovePinnedDown={(() => {
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
return index !== -1 && index < arrangedPinnedKeys.length - 1;
})()}
onSnoozeThread={handleSnoozeThread}
onUnsnoozeThread={handleUnsnoozeThread}
onUnsettleThread={handleUnsettleThread}
onPinThread={handlePinThread}
onUnpinThread={handleUnpinThread}
onMovePinnedThread={handleMovePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
@@ -839,8 +801,6 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleSettleThread,
handleSnoozeThread,
@@ -850,7 +810,6 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
pinReorderEnvironmentIds,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -1017,13 +976,20 @@ export function HomeScreen(props: HomeScreenProps) {
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
// Connection state surfaces in the header title slot
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
// reconnects never shift the rows.
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
if (!hasAnyThreads) {
return (
@@ -1042,17 +1008,41 @@ export function HomeScreen(props: HomeScreenProps) {
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
{emptyState.loading ? (
{emptyState.loading && !shouldShowConnectionStatus ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="mt-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="pb-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</>
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
@@ -1133,6 +1123,7 @@ export function HomeScreen(props: HomeScreenProps) {
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -1187,6 +1178,7 @@ export function HomeScreen(props: HomeScreenProps) {
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -4,7 +4,6 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import {
shouldShowWorkspaceConnectionStatus,
workspaceConnectionStatusLabel,
workspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
@@ -85,36 +84,4 @@ describe("workspace connection status", () => {
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
});
it("presents nothing while connected", () => {
expect(workspaceConnectionStatusPresentation(workspaceState())).toBeNull();
});
it("presents progress while reconnecting but not while offline", () => {
const reconnecting = workspaceState({
hasConnectingEnvironment: true,
hasReadyEnvironment: false,
connectingEnvironments: [
{
environmentId: "environment-1" as never,
environmentLabel: "Julius’s Mac mini",
displayUrl: "",
isRelayManaged: false,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
},
],
});
expect(workspaceConnectionStatusPresentation(reconnecting)).toEqual({
label: "Reconnecting to Julius’s Mac mini",
showsProgress: true,
});
const offline = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
expect(workspaceConnectionStatusPresentation(offline)).toEqual({
label: "You are offline",
showsProgress: false,
});
});
});
@@ -0,0 +1,56 @@
import { SymbolView } from "../../components/AppSymbol";
import { ActivityIndicator, Pressable } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { WorkspaceState } from "../../state/workspaceModel";
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
export function WorkspaceConnectionStatus(props: {
readonly state: WorkspaceState;
readonly onPress: () => void;
readonly variant?: "floating" | "sidebar";
}) {
const iconColor = useThemeColor("--color-icon-muted");
const isSynchronizing =
props.state.networkStatus !== "offline" &&
props.state.connectionError === null &&
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
const variant = props.variant ?? "floating";
return (
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
accessibilityRole="button"
onPress={props.onPress}
className={
variant === "sidebar"
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
}
style={
variant === "floating"
? {
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}
: undefined
}
>
{isSynchronizing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
)}
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
{workspaceConnectionStatusLabel(props.state)}
</Text>
{variant === "sidebar" ? (
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
) : null}
</Pressable>
);
}
@@ -1,194 +0,0 @@
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { ActivityIndicator, Animated, Platform, Pressable, View } from "react-native";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { brandTitleOffset, CompactBrandTitle } from "../../components/CompactBrandTitle";
import { useThemeColor } from "../../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { useWorkspaceState } from "../../state/workspace";
import {
workspaceConnectionStatusPresentation,
type WorkspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
/**
* Delay before a connection interruption surfaces in the title slot. Sub-second
* blips (the common reconnect case) resolve without any UI at all.
*/
const STATUS_SHOW_DELAY_MS = 800;
const FADE_IN_MS = 250;
/**
* Connection status presentation, debounced for display: null until the
* workspace has been in a non-connected state for STATUS_SHOW_DELAY_MS,
* then live-updating until the workspace reconnects (null again immediately).
*/
function useDelayedConnectionStatus(): WorkspaceConnectionStatusPresentation | null {
const { state } = useWorkspaceState();
const presentation = workspaceConnectionStatusPresentation(state);
const hasStatus = presentation !== null;
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!hasStatus) {
setVisible(false);
return;
}
const timer = setTimeout(() => setVisible(true), STATUS_SHOW_DELAY_MS);
return () => clearTimeout(timer);
}, [hasStatus]);
return visible ? presentation : null;
}
/**
* One-shot entrance fade for the status label. Deliberately JS-driven: this can
* mount inside a native header item (RNSScreenStackHeaderSubview), where
* native-driver animated nodes blank the re-hosted view entirely. The JS driver
* updates opacity through the ordinary style path, which those subviews handle.
*/
function StatusFadeIn(props: { readonly children: ReactNode; readonly grow?: boolean }) {
const opacity = useRef(new Animated.Value(0)).current;
useEffect(() => {
const animation = Animated.timing(opacity, {
duration: FADE_IN_MS,
toValue: 1,
useNativeDriver: false,
});
animation.start();
return () => animation.stop();
}, [opacity]);
return (
<Animated.View
style={[
{ alignItems: "center", flexDirection: "row", opacity },
props.grow ? { flex: 1, minWidth: 0 } : null,
]}
>
{props.children}
</Animated.View>
);
}
/**
* Renders the brand/title slot of a thread-list surface, swapping the brand
* for the workspace connection status while an environment is unavailable.
*
* Both states occupy the same slot, so connection changes never shift the
* layout below. While connected the brand renders untouched — no wrapper —
* keeping the native header item on the exact element tree that predates the
* status swap. Replaces the old WorkspaceConnectionStatus pill, which inserted
* a row above the thread list.
*/
export function WorkspaceConnectionTitle(props: {
/** Content shown while connected (brand lockup or a screen title). */
readonly brand: ReactNode;
/** Opens environment settings. Status is not pressable when omitted. */
readonly onPress?: () => void;
/** Fill the available row width (in-flow headers) instead of hugging content (native title slots). */
readonly grow?: boolean;
readonly size?: "navbar" | "pageTitle";
/** Horizontal correction so the status aligns with the brand in native title slots. */
readonly statusOffset?: number;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const status = useDelayedConnectionStatus();
const size = props.size ?? "navbar";
if (status === null) {
return props.grow ? (
<View style={{ alignItems: "center", flex: 1, flexDirection: "row", minWidth: 0 }}>
{props.brand}
</View>
) : (
<>{props.brand}</>
);
}
return (
<StatusFadeIn grow={props.grow}>
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={status.label}
accessibilityRole="button"
disabled={props.onPress === undefined}
hitSlop={8}
onPress={props.onPress}
className="flex-row items-center gap-2"
style={{ marginLeft: props.statusOffset ?? 0 }}
>
{status.showsProgress ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="wifi.slash"
size={size === "pageTitle" ? 17 : 15}
tintColor={iconColor}
type="monochrome"
/>
)}
<Text
className={
size === "pageTitle"
? "text-[20px] font-t3-bold text-foreground-muted"
: "text-[16px] font-t3-bold text-foreground-muted"
}
numberOfLines={1}
style={{ flexShrink: 1 }}
>
{status.label}
</Text>
</Pressable>
</StatusFadeIn>
);
}
/**
* getCompactBrandHeaderOptions with the brand slot upgraded to the
* connection-status swap. Screens with an environment-settings callback apply
* this over the static brand options at mount.
*/
export function getConnectionAwareBrandHeaderOptions(opts: {
readonly onOpenEnvironments: () => void;
readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"];
}): NativeStackNavigationOptions {
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
return {
headerTitle: "Threads",
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
title: "Threads",
unstable_headerLeftItems: (): NativeStackHeaderItem[] => [
{
element: (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle nativeLeadingItem />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(true)}
/>
),
hidesSharedBackground: true,
type: "custom",
},
],
};
}
return {
headerTitle: () => (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(false)}
/>
),
headerTitleStyle: opts.fallbackTitleStyle,
title: "Threads",
};
}
@@ -8,14 +8,9 @@ import { Alert } from "react-native";
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
import {
pinOrderKeyBetween,
planPinnedMove,
sortPinnedThreadsByOrderKey,
} from "@t3tools/client-runtime/state/thread-sort";
import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
/** Version skew: never send settle/unsettle to a server that predates them
@@ -41,13 +36,6 @@ function environmentSupportsPinning(environmentId: EnvironmentThreadShell["envir
);
}
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinReorder === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -223,10 +211,6 @@ export function useThreadListActions(): {
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly movePinnedThread: (
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
@@ -347,21 +331,9 @@ export function useThreadListActions(): {
return false;
}
selectionHaptic();
// Same placement as web: a fresh pin takes the top of the arranged
// run. Servers that predate reordering get the bare pin (keyless).
let orderKey: string | undefined;
if (environmentSupportsPinReorder(thread.environmentId)) {
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
let firstKey: string | null = null;
for (const shell of shells) {
if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
}
orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
}
const result = await pinMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
input: { threadId: thread.id },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
@@ -406,85 +378,6 @@ export function useThreadListActions(): {
[unpinMutation],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
// while search or a project scope filters rows: the same fractional-key
// scheme web dragging uses, one write to one thread per move (plus a
// one-time section materialization when legacy keyless pins are involved).
const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
reportFailure: false,
});
// One move at a time: a second tap before the first write's event lands
// would plan from the same stale snapshot and silently collapse two moves
// into one — same double-dispatch guard as snoozeThread.
const movePinnedInFlightRef = useRef(false);
const movePinnedThread = useCallback(
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
if (movePinnedInFlightRef.current) return false;
if (!environmentSupportsPinReorder(thread.environmentId)) {
Alert.alert(
"Could not move thread",
"This environment's server does not support pinned reordering yet. Update the server to reorder pins.",
);
return false;
}
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
const pinned = sortPinnedThreadsByOrderKey(
shells.filter(
(shell) =>
shell.pinnedAt != null &&
shell.archivedAt === null &&
environmentSupportsPinReorder(shell.environmentId),
),
);
const orderedIds = pinned.map((shell) => scopedThreadKey(shell.environmentId, shell.id));
const assignments = planPinnedMove({
orderedIds,
keysById: new Map(
pinned.map((shell) => [
scopedThreadKey(shell.environmentId, shell.id),
shell.pinOrderKey ?? null,
]),
),
movedId: scopedThreadKey(thread.environmentId, thread.id),
direction,
});
if (assignments === null || assignments.length === 0) return false;
const shellByKey = new Map(
pinned.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
);
selectionHaptic();
movePinnedInFlightRef.current = true;
try {
for (const assignment of assignments) {
const target = shellByKey.get(assignment.id);
if (target === undefined) continue;
const result = await reorderPinnedMutation({
environmentId: target.environmentId,
input: { threadId: target.id, orderKey: assignment.orderKey },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not move thread",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The pinned thread could not be moved.",
);
// No rollback: keys already written are valid orderings on their
// own (each write is a complete, consistent placement), so a
// partial materialization leaves the list sensible, not corrupt.
return false;
}
}
return true;
} finally {
movePinnedInFlightRef.current = false;
}
},
[reorderPinnedMutation],
);
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
return {
@@ -496,7 +389,6 @@ export function useThreadListActions(): {
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
};
}
@@ -1,11 +1,5 @@
import type { WorkspaceState } from "../../state/workspaceModel";
export interface WorkspaceConnectionStatusPresentation {
readonly label: string;
/** True while actively working (connecting/syncing) — render a spinner. False for offline/error/idle states — render a wifi-slash icon. */
readonly showsProgress: boolean;
}
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
return (
state.networkStatus === "offline" ||
@@ -30,17 +24,3 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
}
return "Not connected";
}
/** Header-title presentation of the connection state, or null while connected. */
export function workspaceConnectionStatusPresentation(
state: WorkspaceState,
): WorkspaceConnectionStatusPresentation | null {
if (!shouldShowWorkspaceConnectionStatus(state)) return null;
return {
label: workspaceConnectionStatusLabel(state),
showsProgress:
state.networkStatus !== "offline" &&
state.connectionError === null &&
(state.connectingEnvironments.length > 0 || state.hasPendingShellSnapshot),
};
}
@@ -2,7 +2,7 @@ import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useEffect } from "react";
import { useEffect } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -21,18 +21,16 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
return (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<NativeStackScreenOptions options={{ title: isSignedIn ? "Account" : "Sign in" }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
<UserProfileView isDismissible={false} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
<AuthView isDismissible={false} />
)
) : null}
</View>
@@ -8,6 +8,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/AppText";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
import { splitEnvironmentSections } from "../connection/environmentSections";
@@ -160,19 +161,18 @@ export function SettingsEnvironmentsRouteScreen() {
</View>
)}
{/* Always mounted: already-connected relay environments must stay
visible (and removable) even when cloud config is missing or the
user is signed out — the component gates discovery itself. */}
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
{...(SHOWCASE_ENABLED
? {
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
showcaseSignedIn: true,
}
: {})}
/>
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
<CloudEnvironmentRows
connectedCloudEnvironments={connectedCloudEnvironments}
onReconnectEnvironment={onReconnectEnvironment}
{...(SHOWCASE_ENABLED
? {
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
showcaseSignedIn: true,
}
: {})}
/>
) : null}
</ScrollView>
</View>
);
@@ -131,7 +131,7 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<LegacySettingsSection />
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
@@ -519,7 +519,7 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<LegacySettingsSection />
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
@@ -538,27 +538,26 @@ function GeneralSettingsSection() {
}
/**
* Device-local legacy toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → General → Legacy features backed by
* mobile preferences.
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
*/
function LegacySettingsSection() {
function BetaSettingsSection() {
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
return (
<View className="gap-3">
<SettingsSection title="Legacy">
<SettingsSection title="Beta">
<SettingsSwitchRow
icon="sidebar.left"
label="Legacy Thread List"
value={!threadListV2Enabled}
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
Brings back the original grouped thread list. The default list is flat, in creation order:
active work renders as cards; settled threads collapse to compact rows.
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
</Text>
</View>
);
@@ -25,12 +25,15 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ComposerSurface } from "./ThreadComposer";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
@@ -40,7 +43,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -100,10 +103,6 @@ export function NewTaskDraftScreen(props: {
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
});
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
@@ -522,15 +521,7 @@ export function NewTaskDraftScreen(props: {
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => {
// The delayed focus can land after the settings sheet opened, which
// would pop the keyboard underneath its modal.
if (!settingsSheetPresentation.isActiveRef.current) {
promptInputRef.current?.focus();
} else {
settingsSheetPresentation.restoreFocusAfterSave();
}
});
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
});
return () => {
@@ -539,11 +530,7 @@ export function NewTaskDraftScreen(props: {
cancelAnimationFrame(focusFrame);
}
};
}, [
selectedProject,
settingsSheetPresentation.isActiveRef,
settingsSheetPresentation.restoreFocusAfterSave,
]);
}, [selectedProject]);
const environmentMenuActions = useMemo(
() =>
@@ -557,6 +544,10 @@ export function NewTaskDraftScreen(props: {
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
@@ -566,6 +557,54 @@ export function NewTaskDraftScreen(props: {
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
flow.runtimeMode === "approval-required"
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: flow.runtimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: flow.interactionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
@@ -636,12 +675,10 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: flow.selectedModelOption?.label ?? "Model",
optionDescriptors: providerOptionDescriptors,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
});
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
@@ -651,6 +688,13 @@ export function NewTaskDraftScreen(props: {
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
@@ -658,6 +702,28 @@ export function NewTaskDraftScreen(props: {
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
return;
}
if (event.startsWith("options:runtime:")) {
flow.setRuntimeMode(
event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
);
return;
}
if (event.startsWith("options:interaction:")) {
flow.setInteractionMode(
event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
);
}
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
@@ -864,9 +930,7 @@ export function NewTaskDraftScreen(props: {
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
// The settings sheet dismisses the keyboard, so its flag keeps the Android
// draft composer expanded through the blur (mirrors ThreadComposer).
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
const isExpanded = !isAndroid || isComposerFocused;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -920,14 +984,28 @@ export function NewTaskDraftScreen(props: {
showChevron={false}
disabled={isIncomingShareTransferPending}
/>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
@@ -953,21 +1031,6 @@ export function NewTaskDraftScreen(props: {
</>
);
const settingsSheet = (
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={flow.providerGroups}
selectedModel={flow.selectedModel}
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={flow.setSelectedModelOptions}
runtimeMode={flow.runtimeMode}
onUpdateRuntimeMode={flow.setRuntimeMode}
/>
);
const startButton = (
<ComposerToolbarButton
accessibilityLabel={
@@ -1057,7 +1120,6 @@ export function NewTaskDraftScreen(props: {
) : null}
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
@@ -1091,7 +1153,6 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
@@ -235,9 +235,10 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
gap: 12,
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingBottom: 8,
paddingHorizontal: 20,
paddingTop: 8,
}}
@@ -21,7 +21,6 @@ import {
Image,
Platform,
Pressable,
StyleSheet,
useColorScheme,
View,
type ViewStyle,
@@ -51,10 +50,10 @@ import {
ComposerToolbarScroller,
ComposerToolbarTrigger,
} from "../../components/ComposerToolbarTrigger";
import { ControlPill } from "../../components/ControlPill";
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -62,11 +61,14 @@ import {
normalizeSearchQuery,
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
@@ -270,28 +272,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const fallbackInputRef = useRef<ComposerEditorHandle>(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
isEditorFocused: isFocused,
});
const wasExpandedBeforePreviewRef = useRef(false);
const inFlightThreadIdsRef = useRef(new Set<string>());
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
// Opening and closing count as active so the composer stays expanded while
// focus moves between its native editor and the settings modal.
const isExpanded = isFocused || settingsSheetPresentation.isActive;
const isExpanded = isFocused;
const canSend = hasContent;
// Notify the parent from the derived value, not focus events: the parent
// sizes the feed inset from this, and blur-during-sheet would otherwise
// report collapsed while the composer still renders expanded.
useEffect(() => {
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
@@ -309,11 +298,13 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const handleFocus = useCallback(() => {
setIsFocused(true);
}, []);
onExpandedChange?.(true);
}, [onExpandedChange]);
const handleBlur = useCallback(() => {
setIsFocused(false);
}, []);
onExpandedChange?.(false);
}, [onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
@@ -596,12 +587,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[props.serverConfig, currentModelSelection],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
// An existing thread is bound to its harness: sessions can't move between
// provider instances, so the picker only offers the thread's own group.
const threadProviderGroups = useMemo(
() => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
[providerGroups, currentModelSelection.instanceId],
);
const currentModelOption =
modelOptions.find(
(option) =>
@@ -616,12 +601,95 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
interactionMode: currentInteractionMode,
});
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
);
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
currentRuntimeMode === "approval-required"
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: currentRuntimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: currentInteractionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
props.onUpdateInteractionMode(interactionMode);
}
}
return (
<Animated.View
@@ -630,22 +698,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
style={{
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
}}
>
{/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
silently drops experimental_backgroundImage on Android, which left this
strip fully transparent and the feed text legible through the composer. */}
<View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
},
]}
/>
<Animated.View
className="relative w-full self-center"
layout={COMPOSER_LAYOUT_TRANSITION}
@@ -792,15 +849,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -834,21 +904,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</Animated.View>
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={threadProviderGroups}
selectedModel={currentModelSelection}
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={(options) =>
props.onUpdateModelSelection({ ...currentModelSelection, options })
}
runtimeMode={currentRuntimeMode}
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
/>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
+54 -69
View File
@@ -45,7 +45,14 @@ import {
import { TouchableOpacity } from "react-native-gesture-handler";
import ImageViewing from "react-native-image-viewing";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
import Animated, {
FadeIn,
FadeInUp,
useSharedValue,
withTiming,
type LayoutAnimationsValues,
type SharedValue,
} from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
@@ -110,6 +117,14 @@ function formatMessageTime(input: string): string {
return MESSAGE_TIME_FORMATTER.format(timestamp);
}
// Rows shift when content above them grows (streaming text, work-log folds);
// animating the container position turns those jumps into slides. Applied
// conditionally — see the gated transition in ThreadFeed: while browsing
// history the animation must NOT run, or every estimate→actual size
// correction plays as a visible slide against the instant scroll-offset
// compensation from maintainVisibleContentPosition.
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
// classNames. The fold row's min-h-11 (44px) stays taller than its single
// text-sm line at every supported base font size (26px at the 22pt maximum),
@@ -1320,24 +1335,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
);
const [viewportHeight, setViewportHeight] = useState(0);
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
// whenever the viewport drifts back inside its geometric threshold, which
// yanked users off history they were reading every time a stream chunk grew
// a row. Follow breaks when the user scrolls up and away, and re-arms only
// when the list actually returns to the end (or on send / thread switch).
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
const endFollowEnabledRef = useRef(true);
// A "user scroll session" spans from drag start through the end of its
// momentum; only motion inside a session can break follow, so MVCP
// compensations and programmatic scrolls never strand a follower.
const userScrollSessionRef = useRef(false);
const setEndFollow = useCallback((enabled: boolean) => {
if (endFollowEnabledRef.current === enabled) {
return;
}
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
}, []);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1442,6 +1439,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
},
[props.onHeaderMaterialVisibilityChange],
);
// True while the viewport sits within ~one screen of the list end — the
// only region where layout shifts should animate. Starts true because the
// list opens pinned to the end.
const nearListEnd = useSharedValue(true);
const handleScroll = useCallback(
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
// anchorTopInset, not topContentInset: under automatic insets the list
@@ -1449,41 +1451,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
// before invoking this handler, so getState() is current. Returning to
// the end re-arms follow no matter who scrolled (the user, or our own
// scroll-to-end); moving away breaks it only during a user-initiated
// scroll session, so MVCP compensations and programmatic repositioning
// can never strand a follower.
const listState = props.listRef.current?.getState();
if (listState) {
if (listState.isWithinMaintainScrollAtEndThreshold) {
setEndFollow(true);
} else if (userScrollSessionRef.current) {
setEndFollow(false);
}
}
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
nearListEnd.value =
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
},
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
);
const handleScrollBeginDrag = useCallback(() => {
userScrollSessionRef.current = true;
}, []);
// The session must survive past finger-lift so momentum that carries the
// user away from the end still breaks follow; a drag released with no
// momentum ends its session at the release itself, otherwise at momentum
// end. Leaving a session open would let a later animated maintain-scroll
// read as user motion and break follow spuriously.
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
const velocity = event.nativeEvent.velocity?.y ?? 0;
if (Math.abs(velocity) < 0.05) {
userScrollSessionRef.current = false;
}
}, []);
const handleMomentumScrollEnd = useCallback(() => {
userScrollSessionRef.current = false;
}, []);
// Gated variant of the 180ms feed layout slide. Instant while browsing
// history: maintainVisibleContentPosition compensates the scroll offset in
// the same frame a row's measured size lands, so an instant reposition is
// invisible — animating it is exactly what made cold upward scrolls slide
// and jump. Near the end the slide stays on: streaming growth and sends
// shift rows at rest, where the animation is the thing preventing a hard
// visual snap.
const feedItemLayoutTransition = useMemo(() => {
return (values: LayoutAnimationsValues) => {
"worklet";
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
return {
initialValues: {
originX: values.currentOriginX,
originY: values.currentOriginY,
width: values.currentWidth,
height: values.currentHeight,
},
animations: {
originX: withTiming(values.targetOriginX, { duration }),
originY: withTiming(values.targetOriginY, { duration }),
width: withTiming(values.targetWidth, { duration }),
height: withTiming(values.targetHeight, { duration }),
},
};
};
}, [nearListEnd]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
const nextHeight = Math.round(event.nativeEvent.layout.height);
@@ -1495,20 +1496,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
reportHeaderMaterialVisibility(false);
}, [props.threadId, reportHeaderMaterialVisibility]);
// A thread switch opens pinned to the end; a send explicitly returns to the
// live edge (ThreadDetailScreen scrolls the new message into place). Both
// re-arm follow regardless of where the user had scrolled before.
useEffect(() => {
userScrollSessionRef.current = false;
setEndFollow(true);
}, [props.threadId, setEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
userScrollSessionRef.current = false;
setEndFollow(true);
}
}, [props.anchorMessageId, setEndFollow]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
@@ -1835,6 +1822,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
}
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
itemLayoutAnimation={feedItemLayoutTransition}
// Patched LegendList prop (patches/@[email protected]):
// lets its scroll math clamp programmatic scrolls to -headerInset
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
@@ -1859,7 +1847,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// anchor scrolls also lets it correct a scroll that landed on a
// stale end target once the anchor row finishes measuring.
maintainScrollAtEnd={
disclosureToggleSettling || !endFollowEnabled
disclosureToggleSettling
? false
: {
animated: true,
@@ -1908,9 +1896,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
alignItemsAtEnd
initialScrollAtEnd
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onMomentumScrollEnd={handleMomentumScrollEnd}
scrollEventThrottle={16}
ListHeaderComponent={
<>
@@ -11,7 +11,6 @@ import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import type { EnvironmentId } from "@t3tools/contracts";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
@@ -56,10 +55,8 @@ import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThrea
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
import { useThreadListActions } from "../home/useThreadListActions";
import {
getConnectionAwareBrandHeaderOptions,
WorkspaceConnectionTitle,
} from "../home/WorkspaceConnectionTitle";
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
import { SidebarHeaderActions } from "./sidebar-header-actions";
import { SidebarFilterButton } from "./sidebar-filter-button";
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
@@ -210,7 +207,6 @@ function ThreadNavigationSidebarPane(
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -496,28 +492,6 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const pinReorderEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinReorder === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
const pinned = sortPinnedThreadsByOrderKey(
threads.filter(
(thread) =>
thread.pinnedAt != null &&
thread.archivedAt === null &&
pinReorderEnvironmentIds.has(thread.environmentId),
),
);
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
}, [pinReorderEnvironmentIds, threads]);
const threadListV2Layout = useMemo(() => {
if (!threadListV2Enabled)
return {
@@ -626,6 +600,7 @@ function ThreadNavigationSidebarPane(
threadListV2Enabled,
threadListV2Layout,
]);
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
const listMenuActions = useMemo<MenuAction[]>(
() => [
{
@@ -954,20 +929,11 @@ function ThreadNavigationSidebarPane(
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
canMovePinnedUp={
arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0
}
canMovePinnedDown={(() => {
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
return index !== -1 && index < arrangedPinnedKeys.length - 1;
})()}
onSnoozeThread={snoozeThread}
onUnsnoozeThread={unsnoozeThread}
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onChangeRequestState={handleChangeRequestState}
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
onSwipeableClose={handleSwipeableClose}
@@ -1088,16 +1054,13 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
arrangedPinnedKeys,
confirmDeletePendingTask,
confirmDeleteThread,
handleChangeRequestState,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
movePinnedThread,
openPendingTask,
pinReorderEnvironmentIds,
pinThread,
pinningEnvironmentIds,
projectByKey,
@@ -1190,13 +1153,6 @@ function ThreadNavigationSidebarPane(
<NativeStackScreenOptions
optionsVersion={nativeHeaderItems}
options={{
// Re-applies the shell's static brand slot with the
// connection-status swap so reconnects surface in the header
// instead of shifting the list.
...getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: props.onOpenEnvironmentSettings,
fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
}),
headerSearchBarOptions: {
ref: searchBarRef,
autoCapitalize: "none",
@@ -1247,6 +1203,17 @@ function ThreadNavigationSidebarPane(
scrollEventThrottle={16}
showsVerticalScrollIndicator={false}
style={styles.threadList}
ListHeaderComponent={
showsConnectionStatus ? (
<View className="px-1.5 pt-0.5 pb-2">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
variant="sidebar"
/>
</View>
) : null
}
ListEmptyComponent={listEmpty}
/>
</GestureDetector>
@@ -1337,19 +1304,9 @@ function ThreadNavigationSidebarPane(
</Svg>
</View>
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
{/* Title slot doubles as the connection status surface: while an
environment reconnects, "Threads" fades to a status label in
place (no layout shift in the list below). */}
<WorkspaceConnectionTitle
grow
onPress={props.onOpenEnvironmentSettings}
size="pageTitle"
brand={
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
Threads
</Text>
}
/>
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
Threads
</Text>
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
<ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
<SidebarFilterButton
@@ -1378,6 +1335,16 @@ function ThreadNavigationSidebarPane(
value={props.searchQuery}
/>
</View>
{showsConnectionStatus ? (
<View className="px-3.5 pt-2.5">
<WorkspaceConnectionStatus
onPress={props.onOpenEnvironmentSettings}
state={catalogState}
variant="sidebar"
/>
</View>
) : null}
</View>
</View>
);
@@ -1,678 +0,0 @@
import type {
ModelSelection,
ProviderInteractionMode,
ProviderOptionDescriptor,
ProviderOptionSelection,
RuntimeMode,
} from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import * as Haptics from "expo-haptics";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Modal,
Platform,
Pressable,
ScrollView,
Switch,
useWindowDimensions,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
import { useThemeColor } from "../../lib/useThemeColor";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
/**
* The everyday harnesses stay expanded; every other provider (OpenRouter
* catalogs and friends) folds behind its header so a 300-model catalog can't
* bury the list.
*/
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
/**
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
* covering model, provider options, runtime mode, and plan mode in one label.
*/
export function threadSettingsSummaryLabel(input: {
readonly modelLabel: string;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
}): string {
const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
return [
input.modelLabel,
...providerOptionValueLabels(input.optionDescriptors),
...(runtime ? [runtime.shortLabel] : []),
...(input.interactionMode === "plan" ? ["Plan"] : []),
].join(" · ");
}
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
function ModelRow(props: {
readonly option: ModelOption;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
// Selected rows get the same primary treatment as the submenu rows.
// Subtle backgrounds (bg-subtle-strong) get overridden by the OS
// selection chrome on iOS 26, so use the explicit high-contrast style
// everywhere instead.
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{props.option.label}
</Text>
{props.option.isDefault ? (
<View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
</View>
) : null}
{props.option.isLegacy ? (
<View className="rounded-md bg-subtle px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
</View>
) : null}
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
/**
* Provider section header with the harness logo. Secondary providers render
* as a tappable fold (count + chevron while collapsed); primary providers
* and the group holding the current selection are static headers.
*/
function ProviderHeader(props: {
readonly driver: string | undefined;
readonly label: string;
readonly collapsible: boolean;
readonly collapsed: boolean;
readonly modelCount: number;
readonly onToggle: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole={props.collapsible ? "button" : "header"}
accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
accessibilityLabel={
props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
}
disabled={!props.collapsible}
onPress={props.onToggle}
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
)}
>
<ProviderIcon provider={props.driver} size={15} />
<Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{props.label}
</Text>
{props.collapsible ? (
<>
<View className="flex-1" />
{props.collapsed ? (
<Text className="text-2xs font-t3-medium text-foreground-muted">
{props.modelCount}
</Text>
) : null}
<SymbolView
name={props.collapsed ? "chevron.down" : "chevron.up"}
size={11}
tintColor={iconSubtle}
type="monochrome"
/>
</>
) : null}
</Pressable>
);
}
/** Compact row that opens a single-choice submenu panel. */
function DisclosureRow(props: {
readonly label: string;
readonly value: string | undefined;
readonly disabled?: boolean;
readonly onPress: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"flex-row items-center gap-2 px-5 py-3 active:opacity-70",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<View className="flex-1" />
{props.value ? (
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
{props.value}
</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
);
}
/** Single option inside a submenu panel. */
function ChoiceRow(props: {
readonly label: string;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
className={cn(
"mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
>
{props.label}
</Text>
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
function SwitchRow(props: {
readonly label: string;
readonly value: boolean;
readonly disabled?: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
return (
<View
className={cn(
"flex-row items-center justify-between px-5 py-2.5",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
type SubmenuPage =
| { readonly kind: "descriptor"; readonly id: string }
| { readonly kind: "runtime" };
/**
* Unified thread settings: the sheet is the provider-grouped model list
* (primary harnesses expanded, other providers folded, legacy behind the
* top-right pill) with a Save button, plus compact disclosure rows whose
* single-choice submenus stack in a small panel over the sheet so it never
* changes size. Model changes stage until Save — while staged, the settings
* rows edit the staged model's options and Save applies everything together.
*
* Callers control which harnesses are offered via providerGroups: an
* existing thread must pass only its own provider's group, since a session
* can't switch harness mid-thread.
*
* Rendered through an RN Modal (not the root OverlayPortal) so it also
* presents above natively-presented form sheets like the new-task draft.
* Callers must dismiss the keyboard when opening — the iOS keyboard window
* would otherwise cover the lower half of the sheet.
*/
export function ThreadSettingsSheet(props: {
readonly visible: boolean;
/**
* "save" = the Save/Done button (the user is finished configuring);
* "dismiss" = backdrop, grabber, or system back. Hosts only restore the
* keyboard for "save" so a stray tap outside a control never pops it.
*/
readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
readonly onDismissed: () => void;
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly onSelectModel: (option: ModelOption) => void;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
readonly runtimeMode: RuntimeMode;
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
}) {
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
const wasPresentedRef = useRef(false);
const notifyDismissed = useCallback(() => {
if (!wasPresentedRef.current) {
return;
}
wasPresentedRef.current = false;
props.onDismissed();
}, [props.onDismissed]);
// Every open starts fresh: no staged model, no submenu, legacy hidden,
// secondary providers folded. The sheet stays mounted between opens, so
// state would otherwise stick around.
useEffect(() => {
if (props.visible) {
wasPresentedRef.current = true;
setShowLegacyToggle(false);
setExpandedProviders(new Set());
setPendingModel(null);
setSubmenu(null);
} else if (Platform.OS === "android" && wasPresentedRef.current) {
// React Native only emits Modal.onDismiss on iOS. Android uses no exit
// animation below, so the post-commit effect is its dismissal boundary.
notifyDismissed();
}
}, [notifyDismissed, props.visible]);
const isApplied = (option: ModelOption) =>
option.selection.instanceId === props.selectedModel?.instanceId &&
option.selection.model === props.selectedModel.model;
// The list highlights the staged pick; Save turns it into the applied one.
const isDisplayed = (option: ModelOption) =>
pendingModel ? option.key === pendingModel.key : isApplied(option);
// While a model is staged, the settings rows describe and edit the staged
// model's options (kept on its pending selection); Save applies model and
// options together. Otherwise they edit the applied selection directly.
const displayedDescriptors = pendingModel
? pendingModel.capabilities
? getProviderOptionDescriptors({
caps: pendingModel.capabilities,
selections: pendingModel.selection.options,
})
: []
: props.optionDescriptors;
const hasLegacyModels = props.providerGroups.some((group) =>
group.models.some((model) => model.isLegacy),
);
// Legacy stays hidden unless the pill is toggled this open; a highlighted
// legacy model is exempted from the filter instead of forcing the whole
// legacy list visible.
const showLegacy = showLegacyToggle;
// Stable settings rows: the union of descriptors across the primary
// harnesses' current models (plus whatever the displayed model advertises)
// always renders, with unsupported rows disabled instead of vanishing when
// the selection changes. Keyed by label, not id — Claude and Codex use
// different ids for the same "Reasoning" concept.
const descriptorTemplate = (() => {
const seen = new Map<string, { type: "select" | "boolean" }>();
for (const group of props.providerGroups) {
const driver = group.models[0]?.providerDriver;
if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
continue;
}
for (const model of group.models) {
if (model.isLegacy) {
continue;
}
for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
}
}
for (const descriptor of displayedDescriptors) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
})();
const handleSave = () => {
if (pendingModel) {
void Haptics.selectionAsync();
props.onSelectModel(pendingModel);
}
props.onClose("save");
};
const handleOptionChange = (id: string, value: string | boolean) => {
const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
if (!next) {
return;
}
if (pendingModel) {
setPendingModel({
...pendingModel,
selection: { ...pendingModel.selection, options: next },
});
} else {
props.onUpdateOptionSelections(next);
}
};
const toggleProvider = (providerKey: string) => {
setExpandedProviders((current) => {
const next = new Set(current);
if (!next.delete(providerKey)) {
next.add(providerKey);
}
return next;
});
};
const activeDescriptor =
submenu?.kind === "descriptor"
? displayedDescriptors.find(
(descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
)
: undefined;
const submenuContent =
submenu?.kind === "runtime"
? {
title: "Runtime",
rows: RUNTIME_MODE_CHOICES.map((choice) => ({
id: choice.mode,
label: choice.label,
selected: choice.mode === props.runtimeMode,
onPress: () => {
void Haptics.selectionAsync();
props.onUpdateRuntimeMode(choice.mode);
setSubmenu(null);
},
})),
}
: activeDescriptor?.type === "select"
? {
title: activeDescriptor.label,
rows: selectableChoices(activeDescriptor).map((choice) => ({
id: choice.id,
label: choice.label,
selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
onPress: () => {
void Haptics.selectionAsync();
handleOptionChange(activeDescriptor.id, choice.id);
setSubmenu(null);
},
})),
}
: null;
return (
<Modal
transparent
statusBarTranslucent
navigationBarTranslucent
animationType={Platform.OS === "ios" ? "fade" : "none"}
visible={props.visible}
onDismiss={notifyDismissed}
onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
>
<View className="flex-1 justify-end">
<Pressable
accessibilityLabel="Close thread settings"
className="absolute inset-0 bg-backdrop"
onPress={() => props.onClose("dismiss")}
/>
<View
className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
style={{ maxHeight: windowHeight * 0.85 }}
>
{/* The grabber doubles as the accessible close control: the dim
backdrop above a tall sheet is a sliver, and VoiceOver can't
reach it at all. */}
<Pressable
accessibilityLabel="Close thread settings"
accessibilityRole="button"
onPress={() => props.onClose("dismiss")}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
{hasLegacyModels ? (
<View className="flex-row justify-end px-4 pb-1.5">
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: showLegacy }}
hitSlop={8}
onPress={() => {
void Haptics.selectionAsync();
setShowLegacyToggle(!showLegacy);
}}
className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
>
<Text className="text-2xs font-t3-medium text-foreground-muted">
{showLegacy ? "Hide legacy models" : "Show legacy models"}
</Text>
</Pressable>
</View>
) : null}
{/* Only the model list scrolls. Provider catalogs can run to
hundreds of models (OpenRouter), so the rows below stay pinned
and reachable instead of living at the end of that scroll. */}
<ScrollView
style={{ flexShrink: 1 }}
contentContainerStyle={{ paddingBottom: 8 }}
showsVerticalScrollIndicator={false}
>
{props.providerGroups.map((group) => {
const driver = group.models[0]?.providerDriver;
const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
const visibleModels = showLegacy
? group.models
: group.models.filter((model) => !model.isLegacy || isDisplayed(model));
if (visibleModels.length === 0) {
return null;
}
const containsSelection = group.models.some(isDisplayed);
const collapsible = !isPrimary && !containsSelection;
const collapsed = collapsible && !expandedProviders.has(group.providerKey);
return (
<View key={group.providerKey}>
<ProviderHeader
driver={driver}
label={group.providerLabel}
collapsible={collapsible}
collapsed={collapsed}
modelCount={visibleModels.length}
onToggle={() => toggleProvider(group.providerKey)}
/>
{collapsed
? null
: visibleModels.map((option) => (
<ModelRow
key={option.key}
option={option}
selected={isDisplayed(option)}
onPress={() => {
void Haptics.selectionAsync();
// Re-tapping the applied model cancels staging.
setPendingModel((current) =>
pendingModelAfterPress({
current,
pressed: option,
pressedIsApplied: isApplied(option),
}),
);
}}
/>
))}
</View>
);
})}
</ScrollView>
<View className="mx-5 h-px bg-border" />
<View style={{ paddingBottom: insets.bottom + 12 }}>
{descriptorTemplate.map((entry) => {
const live = displayedDescriptors.find(
(descriptor) => descriptor.label === entry.label,
);
if ((live?.type ?? entry.type) === "select") {
return (
<DisclosureRow
key={entry.label}
label={entry.label}
value={live ? getProviderOptionCurrentLabel(live) : undefined}
disabled={!live}
onPress={() => {
if (live) {
setSubmenu({ kind: "descriptor", id: live.id });
}
}}
/>
);
}
return (
<SwitchRow
key={entry.label}
label={entry.label}
value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
disabled={!live}
onValueChange={(value) => {
if (live) {
handleOptionChange(live.id, value);
}
}}
/>
);
})}
<DisclosureRow
label="Runtime"
value={
RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
}
onPress={() => setSubmenu({ kind: "runtime" })}
/>
<Pressable
accessibilityRole="button"
onPress={handleSave}
className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{pendingModel ? "Save" : "Done"}
</Text>
</Pressable>
</View>
</View>
{/* Submenus stack over the sheet instead of replacing its content,
so the main sheet keeps its size while drilling in and out. */}
{submenuContent ? (
<View className="absolute inset-0 justify-end">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
className="absolute inset-0 bg-backdrop"
onPress={() => setSubmenu(null)}
/>
<View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
accessibilityRole="button"
onPress={() => setSubmenu(null)}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
<Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{submenuContent.title}
</Text>
<ScrollView
style={{ maxHeight: windowHeight * 0.5 }}
contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
showsVerticalScrollIndicator={false}
bounces={false}
>
{submenuContent.rows.map((row) => (
<ChoiceRow
key={row.id}
label={row.label}
selected={row.selected}
onPress={row.onPress}
/>
))}
</ScrollView>
</View>
</View>
) : null}
</View>
</Modal>
);
}
@@ -25,7 +25,6 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { scopedProjectKey } from "../../lib/scopedEntities";
@@ -148,10 +147,7 @@ type NewTaskFlowContextValue = {
readonly reset: () => void;
readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (
key: string | null,
options?: ReadonlyArray<ProviderOptionSelection>,
) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
readonly setStartFromOrigin: (value: boolean) => void;
@@ -363,16 +359,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections only count while their provider is usable on the
// server; otherwise the server's default model wins instead of silently
// targeting a disabled provider. The draft selection is an explicit pick
// and passes through as-is; the project default (last used, possibly from
// desktop) is implicit and additionally never resolves to a legacy model.
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveDefaultableModelSelection(
const projectDefaultModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
@@ -410,9 +404,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
// Options ride along in the same write: a follow-up setSelectedModelOptions
// call would rebuild the selection from the stale pre-switch model.
(key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
(key: string | null) => {
if (!key || !selectedProjectDraftKey) {
return;
}
@@ -421,7 +413,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: options ? { ...option.selection, options } : option.selection,
modelSelection: option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
@@ -354,14 +354,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
readonly onMovePinnedThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
/** Position flags for the pinned block so the menu disables the move that
would fall off the end of the list. */
readonly canMovePinnedUp?: boolean;
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
@@ -390,7 +382,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onArchiveThread,
onPinThread,
onUnpinThread,
onMovePinnedThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
@@ -425,14 +416,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
const handleMovePinnedUp = useCallback(
() => onMovePinnedThread?.(thread, "up"),
[onMovePinnedThread, thread],
);
const handleMovePinnedDown = useCallback(
() => onMovePinnedThread?.(thread, "down"),
[onMovePinnedThread, thread],
);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
// Swipe: the v2 primary action is the lifecycle transition. Every settled
@@ -476,34 +459,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
() =>
props.pinningSupported
? [
...(pinnedRow && props.pinReorderSupported === true
? [
{
id: "move-pin-up",
title: "Move up",
image: "arrow.up",
attributes: { disabled: props.canMovePinnedUp !== true },
} satisfies MenuAction,
{
id: "move-pin-down",
title: "Move down",
image: "arrow.down",
attributes: { disabled: props.canMovePinnedDown !== true },
} satisfies MenuAction,
]
: []),
pinnedRow
? { id: "unpin", title: "Unpin", image: "pin.slash" }
: { id: "pin", title: "Pin", image: "pin" },
]
: [],
[
pinnedRow,
props.canMovePinnedDown,
props.canMovePinnedUp,
props.pinReorderSupported,
props.pinningSupported,
],
[pinnedRow, props.pinningSupported],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
@@ -530,8 +491,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "unsnooze") handleUnsnooze();
if (nativeEvent.event === "pin") handlePin();
if (nativeEvent.event === "unpin") handleUnpin();
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
@@ -548,8 +507,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
handleSettle,
handleSnooze,
@@ -1,64 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
import type { ModelOption } from "../../lib/modelOptions";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
function modelOption(
model: string,
options: ReadonlyArray<ProviderOptionSelection> = [],
): ModelOption {
return {
key: `codex:${model}`,
label: model,
subtitle: "Codex",
providerKey: "codex",
providerLabel: "Codex",
providerDriver: "codex",
isDefault: false,
isLegacy: false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make("codex"),
model,
options,
},
};
}
describe("thread settings sheet state", () => {
it("clears staging when the applied model is pressed", () => {
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed: modelOption("gpt-current"),
pressedIsApplied: true,
}),
).toBeNull();
});
it("preserves staged options when the highlighted model is pressed again", () => {
const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]);
expect(
pendingModelAfterPress({
current: pending,
pressed: modelOption("gpt-next"),
pressedIsApplied: false,
}),
).toBe(pending);
});
it("stages a different model", () => {
const pressed = modelOption("gpt-other");
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed,
pressedIsApplied: false,
}),
).toBe(pressed);
});
});
@@ -1,13 +0,0 @@
import type { ModelOption } from "../../lib/modelOptions";
/** Preserve staged provider options when the highlighted model is tapped again. */
export function pendingModelAfterPress(input: {
readonly current: ModelOption | null;
readonly pressed: ModelOption;
readonly pressedIsApplied: boolean;
}): ModelOption | null {
if (input.pressedIsApplied) {
return null;
}
return input.current?.key === input.pressed.key ? input.current : input.pressed;
}
@@ -104,24 +104,20 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => {
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }),
).toBe(true);
});
it("honors an explicit legacy opt-in", () => {
expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe(
false,
);
expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe(
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
true,
);
});
it("honors an explicit device opt-out", () => {
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
});
it("holds the default while preferences are still loading so the list does not remount", () => {
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }),
).toBe(true);
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
true,
);
});
});
@@ -9,7 +9,6 @@ import {
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -103,23 +102,23 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* The flat Thread List v2 is the default on every app variant; the Settings →
* Legacy toggle opts a device back into the grouped legacy list. Preferences
* persist as sparse patches, so `undefined` genuinely means "never chosen".
* Thread List v2 is on by default on every app variant; the Settings → Beta
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
* genuinely means "never chosen".
*
* `preferencesLoaded` guards the startup window: preferences load
* asynchronously, and rendering one list before the stored choice arrives would
* remount the whole thing a tick later. While loading, hold the default — that
* is where every device without an explicit legacy opt-in lands anyway.
* is where every device without an explicit opt-out lands anyway.
*/
export function resolveThreadListV2Enabled(input: {
readonly legacyPreference: boolean | undefined;
readonly preference: boolean | undefined;
readonly preferencesLoaded: boolean;
}): boolean {
if (!input.preferencesLoaded) {
return true;
}
return input.legacyPreference !== true;
return input.preference ?? true;
}
export function resolveThreadListV2Status(
@@ -384,8 +383,8 @@ export function buildThreadListV2Items(input: {
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
// thread reappears at its exact spot in the pinned block.
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -445,7 +444,7 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortPinnedThreadsByOrderKey(pinned)) {
for (const thread of sortThreadsForListV2(pinned)) {
items.push({
thread,
variant: "card",
@@ -5,15 +5,15 @@ import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveThreadListV2Enabled } from "./threadListV2";
/**
* Resolved Thread List v2 state: on unless the device opted into the legacy
* grouped list (Settings → Legacy). Every consumer must read through this
* Resolved Thread List v2 state: the device-local preference if the user has
* set one, otherwise the default (on). Every consumer must read through this
* rather than the raw preference, which is undefined until explicitly chosen.
*/
export function useThreadListV2Enabled(): boolean {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferencesResult);
return resolveThreadListV2Enabled({
legacyPreference: loaded ? preferencesResult.value.legacyThreadListEnabled : undefined,
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
preferencesLoaded: loaded,
});
}
@@ -1,98 +0,0 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { KeyboardController } from "react-native-keyboard-controller";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
export type ThreadSettingsSheetCloseReason = "save" | "dismiss";
type PresentationPhase = "closed" | "opening" | "visible" | "closing";
/**
* Keeps the custom native composer and the settings modal from owning focus at
* the same time. Opening waits for the keyboard dismissal to finish, while
* focus restoration waits for the modal's dismissal callback.
*/
export function useThreadSettingsSheetPresentation(input: {
readonly editorRef: RefObject<ComposerEditorHandle | null>;
readonly isEditorFocused: boolean;
}) {
const [phase, setPhase] = useState<PresentationPhase>("closed");
const isActiveRef = useRef(false);
const isMountedRef = useRef(true);
const openingIdRef = useRef(0);
const restoreFocusOnSaveRef = useRef(false);
const shouldRestoreAfterDismissRef = useRef(false);
useEffect(
() => () => {
isMountedRef.current = false;
isActiveRef.current = false;
openingIdRef.current += 1;
},
[],
);
const open = useCallback(() => {
if (isActiveRef.current) {
return;
}
isActiveRef.current = true;
restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();
shouldRestoreAfterDismissRef.current = false;
setPhase("opening");
const openingId = openingIdRef.current + 1;
openingIdRef.current = openingId;
// Keyboard.dismiss() only tracks React Native TextInputs. The composer is
// a custom native text view, so explicitly resign its first responder too.
input.editorRef.current?.blur();
void KeyboardController.dismiss().then(() => {
if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
return;
}
setPhase("visible");
});
}, [input.editorRef, input.isEditorFocused]);
const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {
if (!isActiveRef.current) {
return;
}
openingIdRef.current += 1;
shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;
setPhase("closing");
}, []);
const onDismissed = useCallback(() => {
const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;
shouldRestoreAfterDismissRef.current = false;
restoreFocusOnSaveRef.current = false;
isActiveRef.current = false;
setPhase("closed");
if (shouldRestoreFocus) {
input.editorRef.current?.focus();
}
}, [input.editorRef]);
// The new-task screen can have an autofocus queued before the sheet opens.
// Preserve that intent for Save without allowing it to focus under the modal.
const restoreFocusAfterSave = useCallback(() => {
if (isActiveRef.current) {
restoreFocusOnSaveRef.current = true;
}
}, []);
return {
isActive: phase !== "closed",
isActiveRef,
isVisible: phase === "visible",
open,
close,
onDismissed,
restoreFocusAfterSave,
} as const;
}
+46 -43
View File
@@ -3,14 +3,14 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "./modelOptions";
describe("mobile model options", () => {
it("groups models by provider and flags legacy entries", () => {
it("folds legacy models into a provider-scoped menu", () => {
const config = {
providers: [
{
@@ -39,14 +39,51 @@ describe("mobile model options", () => {
],
} as unknown as ServerConfig;
expect(groupByProvider(buildModelOptions(config, null))).toMatchObject([
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
expect(actions).toMatchObject([
{
providerKey: "codex",
providerLabel: "Codex",
models: [
{ key: "codex:gpt-5.6-sol", label: "GPT-5.6 Sol", isLegacy: false },
{ key: "codex:gpt-5.4", label: "GPT-5.4", isLegacy: true },
],
title: "Codex",
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
},
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
},
]);
});
it("omits an empty provider menu when every model is legacy", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
expect(
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
).toMatchObject([
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4" }],
},
]);
});
@@ -137,38 +174,4 @@ describe("mobile model options", () => {
// No config (environment offline) — nothing to validate against.
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
});
it("keeps legacy models out of implicit defaults", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{ slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null },
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const current = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" };
const legacy = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
expect(resolveDefaultableModelSelection(config, current)).toBe(current);
// A legacy last-used selection falls through to the provider default.
expect(resolveDefaultableModelSelection(config, legacy)).toBeNull();
// Offline: nothing to validate against, selection passes through.
expect(resolveDefaultableModelSelection(null, legacy)).toBe(legacy);
});
});
+51 -20
View File
@@ -3,6 +3,7 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -84,26 +85,6 @@ export function resolveSelectableModelSelection(
: null;
}
/**
* Like resolveSelectableModelSelection, but additionally rejects legacy
* models. Used for implicit defaults (stored draft, project last-used): a
* new thread should never quietly start on a legacy model, so those fall
* through to the provider's default instead. Explicit picks in the settings
* sheet are unaffected.
*/
export function resolveDefaultableModelSelection(
config: T3ServerConfig | null | undefined,
selection: ModelSelection | null,
): ModelSelection | null {
const usable = resolveSelectableModelSelection(config, selection);
if (!usable || !config) {
return usable;
}
const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
const model = provider?.models.find((candidate) => candidate.slug === usable.model);
return model?.isLegacy === true ? null : usable;
}
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
@@ -187,3 +168,53 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+37 -15
View File
@@ -3,8 +3,9 @@ import { describe, expect, it } from "vite-plus/test";
import type { ModelCapabilities } from "@t3tools/contracts";
import {
applyProviderOptionSelection,
providerOptionValueLabels,
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "./providerOptions";
@@ -34,13 +35,31 @@ const CODEX_CAPABILITIES: ModelCapabilities = {
};
describe("mobile provider options", () => {
it("summarizes the option values currently in effect", () => {
it("renders the option descriptors advertised by the selected model", () => {
const descriptors = resolveProviderOptionDescriptors({
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
expect(providerOptionValueLabels(descriptors)).toEqual(["Medium", "Standard"]);
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Reasoning",
subtitle: "Medium",
subactions: [
{ title: "Medium (default)", state: "on" },
{ title: "High", state: undefined },
],
},
{
title: "Service Tier",
subtitle: "Standard",
subactions: [
{ title: "Standard (default)", state: "on" },
{ title: "Fast", state: undefined },
],
},
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Medium · Standard");
});
it("updates generic select options without knowing provider-specific ids", () => {
@@ -48,18 +67,14 @@ describe("mobile provider options", () => {
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
const actions = buildProviderOptionMenuActions(descriptors);
const fastEvent = actions[1]?.subactions?.[1]?.id;
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "priority" }),
).toEqual([
expect(fastEvent).toBeDefined();
expect(applyProviderOptionMenuEvent(descriptors, fastEvent!)).toEqual([
{ id: "reasoningEffort", value: "medium" },
{ id: "serviceTier", value: "priority" },
]);
// Choices the model doesn't advertise are rejected, not stored.
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "turbo" }),
).toBeNull();
expect(applyProviderOptionSelection(descriptors, { id: "unknown", value: "high" })).toBeNull();
});
it("treats an unspecified boolean capability as off", () => {
@@ -70,9 +85,16 @@ describe("mobile provider options", () => {
selections: undefined,
});
expect(providerOptionValueLabels(descriptors)).toEqual([]);
expect(applyProviderOptionSelection(descriptors, { id: "fastMode", value: true })).toEqual([
{ id: "fastMode", value: true },
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Fast Mode",
subtitle: "Off",
subactions: [
{ title: "Off", state: "on" },
{ title: "On", state: undefined },
],
},
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Configuration");
});
});
+87 -20
View File
@@ -3,12 +3,48 @@ import type {
ProviderOptionDescriptor,
ProviderOptionSelection,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
const PROVIDER_OPTION_EVENT_PREFIX = "provider-option:";
function providerOptionEvent(id: string, value: string | boolean): string {
return `${PROVIDER_OPTION_EVENT_PREFIX}${encodeURIComponent(JSON.stringify({ id, value }))}`;
}
function parseProviderOptionEvent(
event: string,
): { readonly id: string; readonly value: string | boolean } | null {
if (!event.startsWith(PROVIDER_OPTION_EVENT_PREFIX)) {
return null;
}
try {
const parsed: unknown = JSON.parse(
decodeURIComponent(event.slice(PROVIDER_OPTION_EVENT_PREFIX.length)),
);
if (
typeof parsed === "object" &&
parsed !== null &&
"id" in parsed &&
typeof parsed.id === "string" &&
"value" in parsed &&
(typeof parsed.value === "string" || typeof parsed.value === "boolean")
) {
return { id: parsed.id, value: parsed.value };
}
} catch {
return null;
}
return null;
}
export function resolveProviderOptionDescriptors(input: {
readonly capabilities: ModelCapabilities | null | undefined;
readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
@@ -22,41 +58,72 @@ export function resolveProviderOptionDescriptors(input: {
});
}
/**
* Labels for the option values currently in effect (select values plus
* enabled booleans), used to summarize the thread configuration in the
* composer trigger pill.
*/
export function providerOptionValueLabels(
export function buildProviderOptionMenuActions(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): ReadonlyArray<string> {
return descriptors.flatMap((descriptor) => {
): ReadonlyArray<MenuAction> {
return descriptors.map((descriptor) => {
const currentValue =
descriptor.type === "boolean"
? (descriptor.currentValue ?? false)
: getProviderOptionCurrentValue(descriptor);
const choices =
descriptor.type === "select"
? descriptor.options.map((option) => ({
id: providerOptionEvent(descriptor.id, option.id),
title: `${option.label}${option.isDefault ? " (default)" : ""}`,
state: currentValue === option.id ? ("on" as const) : undefined,
}))
: ([false, true] as const).map((value) => ({
id: providerOptionEvent(descriptor.id, value),
title: value ? "On" : "Off",
state: currentValue === value ? ("on" as const) : undefined,
}));
return {
id: `provider-option-menu:${descriptor.id}`,
title: descriptor.label,
subtitle:
descriptor.type === "boolean"
? currentValue
? "On"
: "Off"
: getProviderOptionCurrentLabel(descriptor),
subactions: choices,
};
});
}
export function providerOptionsConfigurationLabel(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): string {
const labels = descriptors.flatMap((descriptor) => {
if (descriptor.type === "boolean") {
return descriptor.currentValue ? [descriptor.label] : [];
}
const label = getProviderOptionCurrentLabel(descriptor);
return label ? [label] : [];
});
return labels.length > 0 ? labels.join(" · ") : "Configuration";
}
/**
* Applies one option change (by descriptor id) and returns the full selection
* list to store on the model selection, or null when the change doesn't match
* an advertised descriptor / choice.
*/
export function applyProviderOptionSelection(
export function applyProviderOptionMenuEvent(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
change: ProviderOptionSelection,
event: string,
): ReadonlyArray<ProviderOptionSelection> | null {
const descriptor = descriptors.find((candidate) => candidate.id === change.id);
const selection = parseProviderOptionEvent(event);
if (!selection) {
return null;
}
const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
if (!descriptor) {
return null;
}
if (
(descriptor.type === "boolean" && typeof change.value !== "boolean") ||
(descriptor.type === "boolean" && typeof selection.value !== "boolean") ||
(descriptor.type === "select" &&
(typeof change.value !== "string" ||
!descriptor.options.some((option) => option.id === change.value)))
(typeof selection.value !== "string" ||
!descriptor.options.some((option) => option.id === selection.value)))
) {
return null;
}
@@ -65,7 +132,7 @@ export function applyProviderOptionSelection(
candidate.id === descriptor.id
? {
...candidate,
currentValue: change.value,
currentValue: selection.value,
}
: candidate,
) as ReadonlyArray<ProviderOptionDescriptor>;
@@ -27,13 +27,12 @@ export interface Preferences {
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
/**
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into
* per device. Deliberately a fresh key (was `threadListV2Enabled`, an
* opt-out): sanitizing drops the old key, so every device resets to the
* default flat list — see `resolveThreadListV2Enabled`.
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted out of per
* device. Undefined means the user has never chosen, which resolves to on —
* see `resolveThreadListV2Enabled`.
*/
readonly legacyThreadListEnabled?: boolean;
readonly threadListV2Enabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -85,7 +84,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
legacyThreadListEnabled?: boolean;
threadListV2Enabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -122,8 +121,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
}
return preferences;
}
@@ -1,177 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off - Measures the real Node HTTP and WebSocket transports.
import * as NodeHttp from "node:http";
import * as NodeZlib from "node:zlib";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import { WsRpcGroup } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import * as Socket from "effect/unstable/socket/Socket";
export class TransferHttpRequestError extends Schema.TaggedErrorClass<TransferHttpRequestError>()(
"TransferHttpRequestError",
{
url: Schema.String,
cause: Schema.Defect(),
},
) {}
export interface HttpTransferMeasurement {
readonly status: number;
readonly contentEncoding: string | null;
readonly encodedBody: Uint8Array;
readonly encodedBodyBytes: number;
readonly decodedBody: Uint8Array;
readonly decodedBodyBytes: number;
/** HTTP response bytes read from the socket, including status line and headers. */
readonly wireBytes: number;
}
export const measureHttpGet = Effect.fn("TransferBudget.measureHttpGet")(function* (input: {
readonly url: string;
readonly headers?: Readonly<Record<string, string>>;
}) {
return yield* Effect.tryPromise({
try: () =>
new Promise<HttpTransferMeasurement>((resolve, reject) => {
let socketBytesBeforeResponse = 0;
const request = NodeHttp.get(
input.url,
{
agent: false,
headers: {
"accept-encoding": "gzip",
connection: "close",
...input.headers,
},
},
(response) => {
const chunks: Buffer[] = [];
response.on("data", (chunk: Buffer) => chunks.push(chunk));
response.once("error", reject);
response.once("end", () => {
try {
const encodedBody = Buffer.concat(chunks);
const header = response.headers["content-encoding"];
const contentEncoding = Array.isArray(header)
? (header[0] ?? null)
: (header ?? null);
const decodedBody =
contentEncoding === "gzip" ? NodeZlib.gunzipSync(encodedBody) : encodedBody;
resolve({
status: response.statusCode ?? 0,
contentEncoding,
encodedBody,
encodedBodyBytes: encodedBody.byteLength,
decodedBody,
decodedBodyBytes: decodedBody.byteLength,
wireBytes: Math.max(0, response.socket.bytesRead - socketBytesBeforeResponse),
});
} catch (cause) {
reject(cause);
}
});
},
);
request.once("socket", (socket) => {
socketBytesBeforeResponse = socket.bytesRead;
});
request.once("error", reject);
request.setTimeout(10_000, () => {
request.destroy(new Error(`Timed out reading ${input.url}`));
});
}),
catch: (cause) => new TransferHttpRequestError({ url: input.url, cause }),
});
});
export interface WebSocketTransferTotals {
readonly wireBytes: number;
readonly decodedBytes: number;
readonly messages: number;
}
export interface WebSocketTransferRecorder {
readonly connect: (
url: string,
protocols: string | string[] | undefined,
cookie: string,
) => globalThis.WebSocket;
readonly totals: () => WebSocketTransferTotals;
readonly negotiatedExtensions: () => string;
}
interface NodeWebSocketWithTransport extends NodeSocket.NodeWS.WebSocket {
readonly _socket?: {
readonly bytesRead: number;
};
}
function rawDataBytes(data: NodeSocket.NodeWS.RawData): number {
if (Array.isArray(data)) {
return data.reduce((total, chunk) => total + chunk.byteLength, 0);
}
return data.byteLength;
}
export function makeWebSocketTransferRecorder(): WebSocketTransferRecorder {
let socket: NodeWebSocketWithTransport | null = null;
let decodedBytes = 0;
let messages = 0;
return {
connect: (url, protocols, cookie) => {
const nextSocket = new NodeSocket.NodeWS.WebSocket(url, protocols, {
headers: { cookie },
perMessageDeflate: true,
}) as NodeWebSocketWithTransport;
socket = nextSocket;
nextSocket.on("message", (data) => {
const bytes = rawDataBytes(data);
decodedBytes += bytes;
messages += 1;
});
return nextSocket as unknown as globalThis.WebSocket;
},
totals: () => ({
wireBytes: socket?._socket?.bytesRead ?? 0,
decodedBytes,
messages,
}),
negotiatedExtensions: () => socket?.extensions ?? "",
};
}
export function transferDelta(
start: WebSocketTransferTotals,
end: WebSocketTransferTotals,
): WebSocketTransferTotals {
return {
wireBytes: Math.max(0, end.wireBytes - start.wireBytes),
decodedBytes: Math.max(0, end.decodedBytes - start.decodedBytes),
messages: Math.max(0, end.messages - start.messages),
};
}
export function countingWsRpcProtocolLayer(input: {
readonly url: string;
readonly cookie: string;
readonly recorder: WebSocketTransferRecorder;
}) {
const webSocketConstructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url, protocols) =>
input.recorder.connect(url, protocols, input.cookie),
);
return RpcClient.layerProtocolSocket().pipe(
Layer.provide(
Socket.layerWebSocket(input.url, { openTimeout: "10 seconds" }).pipe(
Layer.provide(webSocketConstructorLayer),
),
),
Layer.provide(RpcSerialization.layerJson),
);
}
export const makeCountingWsRpcClient = RpcClient.make(WsRpcGroup);
export type CountingWsRpcClient = Effect.Success<typeof makeCountingWsRpcClient>;
@@ -37,7 +37,6 @@ import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapte
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import * as AccountLimitsService from "../src/usage/AccountLimitsService.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
import {
@@ -52,13 +51,10 @@ import { OrchestrationEngineLive } from "../src/orchestration/Layers/Orchestrati
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../src/orchestration/ThreadPlanProgress.ts";
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
import { CheckpointReactor } from "../src/orchestration/Services/CheckpointReactor.ts";
import { ProviderRuntimeIngestionService } from "../src/orchestration/Services/ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -222,8 +218,6 @@ export interface OrchestrationIntegrationHarness {
timeoutMs?: number,
): Effect.Effect<Receipt, never>;
};
readonly drainProviderRuntime: Effect.Effect<void>;
readonly drainCheckpointReactor: Effect.Effect<void>;
readonly dispose: Effect.Effect<void, never>;
}
@@ -312,14 +306,10 @@ export const makeOrchestrationIntegrationHarness = (
checkpointStoreLayer,
providerLayer,
RuntimeReceiptBusTest,
).pipe(
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
);
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(AccountLimitsService.layerTest),
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
@@ -402,13 +392,6 @@ export const makeOrchestrationIntegrationHarness = (
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
runtime.runPromise(Effect.service(OrchestrationReactor)),
).pipe(Effect.orDie);
const providerRuntimeIngestion = yield* tryRuntimePromise(
"load ProviderRuntimeIngestion service",
() => runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)),
).pipe(Effect.orDie);
const checkpointReactor = yield* tryRuntimePromise("load CheckpointReactor service", () =>
runtime.runPromise(Effect.service(CheckpointReactor)),
).pipe(Effect.orDie);
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
).pipe(Effect.orDie);
@@ -573,8 +556,6 @@ export const makeOrchestrationIntegrationHarness = (
waitForDomainEvent,
waitForPendingApproval,
waitForReceipt,
drainProviderRuntime: providerRuntimeIngestion.drain,
drainCheckpointReactor: checkpointReactor.drain,
dispose,
} satisfies OrchestrationIntegrationHarness;
});
@@ -11,6 +11,7 @@ import {
ProviderDriverKind,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Crypto from "effect/Crypto";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
@@ -225,9 +226,9 @@ function missingSessionEffect(
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
Effect.gen(function* () {
const provider = options?.provider ?? ProviderDriverKind.make("codex");
const crypto = yield* Crypto.Crypto;
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
let sessionCount = 0;
let eventCount = 0;
const sessions = new Map<ThreadId, SessionState>();
const queuedResponsesForNextSession: TestTurnResponse[] = [];
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
@@ -241,10 +242,18 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const nextEventId = (threadId: ThreadId) => {
eventCount += 1;
return EventId.make(`test-provider:${provider}:${threadId}:${eventCount}`);
};
const randomUUIDv4 = (threadId: ThreadId) =>
crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterValidationError({
provider,
operation: "crypto/randomUUIDv4",
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
cause,
}),
),
);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
@@ -313,7 +322,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: nextEventId(input.threadId),
eventId: yield* randomUUIDv4(input.threadId),
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
};
@@ -370,7 +379,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: nextEventId(input.threadId),
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
@@ -1,212 +0,0 @@
import type { ProviderDriverKind } from "@t3tools/contracts";
import type {
HttpTransferMeasurement,
WebSocketTransferTotals,
} from "./NetworkTransferMeasurement.integration.ts";
import {
TRANSFER_HISTORY_MCP_RESULT_BYTES,
TRANSFER_HISTORY_TOOLS_PER_TURN,
TRANSFER_HISTORY_TURN_COUNT,
TRANSFER_MEASURED_MCP_RESULT_BYTES,
TRANSFER_MEASURED_TOOLS,
} from "./fixtures/transferBudget.ts";
export interface TransferBudgetRun {
readonly provider: ProviderDriverKind;
readonly threadSnapshot: HttpTransferMeasurement;
readonly measuredTurnWebSocket: WebSocketTransferTotals;
}
interface ProviderTransferBudget {
readonly totalWireBytes: number;
readonly threadSnapshotWireBytes: number;
readonly measuredTurnWebSocketWireBytes: number;
readonly measuredTurnWebSocketDecodedBytes: number;
readonly measuredTurnWebSocketMessages: number;
}
// These caps leave roughly 30% headroom above the client projection of the
// deterministic 9 MB retained-result fixture. Full MCP results stay in
// persistence, so accidentally shipping them again exceeds these caps by
// orders of magnitude. The CI report preserves exact values for review.
const TRANSFER_BUDGET = {
totalWireBytes: 15_500,
threadSnapshotWireBytes: 7_500,
measuredTurnWebSocketWireBytes: 8_000,
measuredTurnWebSocketDecodedBytes: 68_000,
measuredTurnWebSocketMessages: 21,
} satisfies ProviderTransferBudget;
export const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
codex: TRANSFER_BUDGET,
claudeAgent: TRANSFER_BUDGET,
};
function totalWireBytes(run: TransferBudgetRun): number {
return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
}
function observedTransfer(run: TransferBudgetRun) {
return {
totalWireBytes: totalWireBytes(run),
threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
};
}
/** Machine-readable input for the trusted PR comment publisher. */
export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
const providers = Object.fromEntries(
runs.flatMap((run) => {
const ceiling = TRANSFER_BUDGETS[run.provider];
return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
}),
);
return `${JSON.stringify(
{
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: TRANSFER_HISTORY_TURN_COUNT,
historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
measuredCommandTools: TRANSFER_MEASURED_TOOLS,
measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
},
providers,
},
null,
2,
)}\n`;
}
function formatBytes(bytes: number): string {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) {
return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
}
return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
}
function row(
provider: ProviderDriverKind,
phase: string,
metric: string,
observed: number,
maximum: number,
format: (value: number) => string = formatBytes,
): string {
const status = observed <= maximum ? "PASS" : "FAIL";
return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
}
export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
const violations: string[] = [];
for (const run of runs) {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) {
violations.push(`${run.provider}: no transfer budget is configured`);
continue;
}
const checks = [
["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
[
"measured-turn WebSocket wire bytes",
run.measuredTurnWebSocket.wireBytes,
budget.measuredTurnWebSocketWireBytes,
],
[
"measured-turn WebSocket decoded bytes",
run.measuredTurnWebSocket.decodedBytes,
budget.measuredTurnWebSocketDecodedBytes,
],
[
"measured-turn WebSocket messages",
run.measuredTurnWebSocket.messages,
budget.measuredTurnWebSocketMessages,
],
] as const;
for (const [metric, observed, maximum] of checks) {
if (observed > maximum) {
violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
}
}
}
return violations;
}
export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
const lines = [
"# T3 Code thread transfer budget",
"",
"Wire values are thread data bytes read from local HTTP and WebSocket sockets. HTTP includes response headers; WebSocket measurement starts after the resumed thread subscription synchronizes. TCP/IP, TLS framing, and the WebSocket upgrade are excluded. WebSocket permessage-deflate is negotiated.",
`Scenario: ${TRANSFER_HISTORY_TURN_COUNT} historical turns with ${TRANSFER_HISTORY_TOOLS_PER_TURN} command tools and one retained ${formatBytes(TRANSFER_HISTORY_MCP_RESULT_BYTES)} MCP result each, followed by one measured turn with ${TRANSFER_MEASURED_TOOLS} command tools and a retained ${formatBytes(TRANSFER_MEASURED_MCP_RESULT_BYTES)} MCP result. Payload sizes are calibrated from heavy local Codex and Claude histories and contain no user data.`,
"",
"| Provider | Total thread wire | Budget | Result |",
"| --- | ---: | ---: | --- |",
...runs.flatMap((run) => {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) return [];
const observed = observedTransfer(run).totalWireBytes;
return [
`| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
];
}),
"",
"## Detailed measurements",
"",
"| Provider | Phase | Metric | Observed | Budget | Result |",
"| --- | --- | --- | ---: | ---: | --- |",
];
for (const run of runs) {
const budget = TRANSFER_BUDGETS[run.provider];
if (!budget) continue;
lines.push(
row(
run.provider,
"thread snapshot",
"HTTP wire",
run.threadSnapshot.wireBytes,
budget.threadSnapshotWireBytes,
),
row(
run.provider,
"measured turn",
"WebSocket wire",
run.measuredTurnWebSocket.wireBytes,
budget.measuredTurnWebSocketWireBytes,
),
row(
run.provider,
"measured turn",
"WebSocket decoded",
run.measuredTurnWebSocket.decodedBytes,
budget.measuredTurnWebSocketDecodedBytes,
),
row(
run.provider,
"measured turn",
"WebSocket messages",
run.measuredTurnWebSocket.messages,
budget.measuredTurnWebSocketMessages,
String,
),
);
}
lines.push("", "## Compression diagnostics", "");
for (const run of runs) {
lines.push(
`- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
);
}
return `${lines.join("\n")}\n`;
}
@@ -1,128 +0,0 @@
import {
CommandId,
defaultInstanceIdForDriver,
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_PROVIDER_INTERACTION_MODE,
MessageId,
ProjectId,
ProviderDriverKind,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import type { TurnProcessingQuiescedReceipt } from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import type { OrchestrationIntegrationHarness } from "./OrchestrationEngineHarness.integration.ts";
import {
expectedRecordedAssistantText,
makeRecordedTransferTurn,
TRANSFER_HISTORY_TURN_COUNT,
} from "./fixtures/transferBudget.ts";
export const TRANSFER_PROJECT_ID = ProjectId.make("transfer-budget-project");
export const TRANSFER_THREAD_ID = ThreadId.make("transfer-budget-thread");
export const TRANSFER_MEASURED_TURN_INDEX = TRANSFER_HISTORY_TURN_COUNT;
export function transferModelSelection(provider: ProviderDriverKind) {
return {
instanceId: defaultInstanceIdForDriver(provider),
model: DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL,
};
}
function turnTimestamp(turnIndex: number): string {
return `2026-06-01T00:${String(turnIndex).padStart(2, "0")}:00.000Z`;
}
export const TRANSFER_MEASURED_TURN_CREATED_AT = turnTimestamp(TRANSFER_MEASURED_TURN_INDEX);
const waitForTurnQuiesced = Effect.fn("TransferBudget.waitForTurnQuiesced")(function* (
harness: OrchestrationIntegrationHarness,
checkpointTurnCount: number,
) {
const receipt = yield* harness.waitForReceipt(
(receipt): receipt is TurnProcessingQuiescedReceipt =>
receipt.type === "turn.processing.quiesced" &&
receipt.threadId === TRANSFER_THREAD_ID &&
receipt.checkpointTurnCount === checkpointTurnCount,
);
yield* harness.drainProviderRuntime;
yield* harness.drainCheckpointReactor;
return receipt;
});
export const seedTransferBudgetHistory = Effect.fn("TransferBudget.seedHistory")(function* (
harness: OrchestrationIntegrationHarness,
provider: ProviderDriverKind,
) {
if (!harness.adapterHarness) {
return yield* Effect.die(new Error("Transfer budget history requires the replay adapter."));
}
const modelSelection = transferModelSelection(provider);
yield* harness.engine.dispatch({
type: "project.create",
commandId: CommandId.make(`transfer:${provider}:project-create`),
projectId: TRANSFER_PROJECT_ID,
title: "Transfer Budget Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: modelSelection,
createdAt: turnTimestamp(0),
});
yield* harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make(`transfer:${provider}:thread-create`),
threadId: TRANSFER_THREAD_ID,
projectId: TRANSFER_PROJECT_ID,
title: `${provider} transfer history`,
modelSelection,
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: "main",
worktreePath: harness.workspaceDir,
createdAt: turnTimestamp(0),
});
for (let turnIndex = 0; turnIndex < TRANSFER_HISTORY_TURN_COUNT; turnIndex += 1) {
const response = makeRecordedTransferTurn(provider, turnIndex);
if (turnIndex === 0) {
yield* harness.adapterHarness.queueTurnResponseForNextSession(response);
} else {
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
}
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make(`transfer:${provider}:turn:${turnIndex + 1}`),
threadId: TRANSFER_THREAD_ID,
message: {
messageId: MessageId.make(`transfer-user-${turnIndex + 1}`),
role: "user",
text: `Inspect transfer behavior for historical turn ${turnIndex + 1}.`,
attachments: [],
},
modelSelection,
runtimeMode: "approval-required",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
createdAt: turnTimestamp(turnIndex),
});
yield* waitForTurnQuiesced(harness, turnIndex + 1);
}
});
export const queueMeasuredTransferTurn = Effect.fn("TransferBudget.queueMeasuredTurn")(function* (
harness: OrchestrationIntegrationHarness,
provider: ProviderDriverKind,
) {
if (!harness.adapterHarness) {
return yield* Effect.die(new Error("Transfer budget measurement requires the replay adapter."));
}
const response = makeRecordedTransferTurn(provider, TRANSFER_MEASURED_TURN_INDEX);
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
});
export function expectedMeasuredAssistantText(provider: ProviderDriverKind): string {
return expectedRecordedAssistantText(provider, TRANSFER_MEASURED_TURN_INDEX);
}
export { TRANSFER_HISTORY_TURN_COUNT, waitForTurnQuiesced };
@@ -1,372 +0,0 @@
import { EventId, ProviderDriverKind } from "@t3tools/contracts";
import type {
FixtureProviderRuntimeEvent,
TestTurnResponse,
} from "../TestProviderAdapter.integration.ts";
const FIXTURE_THREAD_ID = "transfer-budget-thread";
const FIXTURE_TURN_ID = "transfer-budget-turn";
export const TRANSFER_HISTORY_TURN_COUNT = 10;
export const TRANSFER_HISTORY_TOOLS_PER_TURN = 5;
export const TRANSFER_MEASURED_TOOLS = 20;
export const TRANSFER_HISTORY_MCP_RESULT_BYTES = 900_000;
export const TRANSFER_MEASURED_MCP_RESULT_BYTES = 1_100_000;
const sourceModules = [
"connection/session.ts",
"connection/supervisor.ts",
"rpc/client.ts",
"rpc/protocol.ts",
"state/threads.ts",
"state/threadReducer.ts",
"state/threadSnapshotHttp.ts",
"orchestration/http.ts",
"orchestration/Normalizer.ts",
"orchestration/ActivityPayloadProjection.ts",
"provider/ProviderService.ts",
"provider/ProviderRuntimeIngestion.ts",
"persistence/ProjectionSnapshotQuery.ts",
"persistence/OrchestrationEventStore.ts",
"checkpointing/CheckpointStore.ts",
"checkpointing/CheckpointDiffQuery.ts",
"server.ts",
] as const;
function fixtureTimestamp(turnIndex: number, eventIndex: number): string {
const minute = String(turnIndex).padStart(2, "0");
const second = String(Math.floor(eventIndex / 1_000)).padStart(2, "0");
const millisecond = String(eventIndex % 1_000).padStart(3, "0");
return `2026-06-01T00:${minute}:${second}.${millisecond}Z`;
}
function mix(value: number): number {
let mixed = value | 0;
mixed ^= mixed >>> 16;
mixed = Math.imul(mixed, 0x7feb352d);
mixed ^= mixed >>> 15;
mixed = Math.imul(mixed, 0x846ca68b);
mixed ^= mixed >>> 16;
return mixed >>> 0;
}
function digest(seed: number): string {
return [0, 1, 2, 3]
.map((offset) =>
mix(seed + offset * 0x9e3779b9)
.toString(16)
.padStart(8, "0"),
)
.join("");
}
/** Produces safe, deterministic output with enough entropy to exercise gzip. */
function diagnosticOutput(input: {
readonly provider: ProviderDriverKind;
readonly turnIndex: number;
readonly toolIndex: number;
readonly targetBytes: number;
}): string {
const chunks: string[] = [];
const providerSeed = input.provider === "codex" ? 0x43_4f_44_45 : 0x43_4c_41_55;
let length = 0;
let lineIndex = 0;
while (length < input.targetBytes) {
const modulePath = sourceModules[(input.toolIndex + lineIndex) % sourceModules.length];
const seed =
providerSeed + input.turnIndex * 100_003 + input.toolIndex * 10_007 + lineIndex * 101;
const line =
`${String(lineIndex + 1).padStart(6, "0")} ${modulePath} ` +
`operation=project-transfer-${input.turnIndex + 1}-${input.toolIndex + 1} ` +
`cursor=${mix(seed)} digest=${digest(seed)} status=completed\n`;
chunks.push(line);
length += line.length;
lineIndex += 1;
}
return chunks.join("").slice(0, input.targetBytes);
}
function assistantChunks(provider: ProviderDriverKind, turnIndex: number): ReadonlyArray<string> {
const providerName = provider === "codex" ? "Codex" : "Claude";
const paragraphs: string[] = [
`I traced the ${providerName} request through the environment connection and orchestration layers. `,
];
let paragraphIndex = 0;
while (paragraphs.join("").length < 4_096) {
const modulePath = sourceModules[paragraphIndex % sourceModules.length];
paragraphs.push(
`Pass ${paragraphIndex + 1} reviewed ${modulePath} for turn ${turnIndex + 1}. ` +
"The shell cursor stayed monotonic, the thread snapshot remained resumable, and the client received only incremental events. ",
);
paragraphIndex += 1;
}
const text = paragraphs.join("").slice(0, 4_096);
return Array.from({ length: Math.ceil(text.length / 256) }, (_, index) =>
text.slice(index * 256, (index + 1) * 256),
);
}
export function expectedRecordedAssistantText(
provider: ProviderDriverKind,
turnIndex: number,
): string {
return assistantChunks(provider, turnIndex).join("");
}
function unifiedDiff(provider: ProviderDriverKind, turnIndex: number): string {
const lines = sourceModules
.slice(0, 8)
.flatMap((modulePath, index) => [
`diff --git a/${modulePath} b/${modulePath}`,
`--- a/${modulePath}`,
`+++ b/${modulePath}`,
`@@ -${index + 1},2 +${index + 1},3 @@`,
` const provider = "${provider}";`,
`+const transferTurn = ${turnIndex + 1};`,
`+const transferSample = ${1_500 + index * 97};`,
]);
return lines.join("\n");
}
function baseEvent(
provider: ProviderDriverKind,
turnIndex: number,
eventIndex: number,
): Pick<FixtureProviderRuntimeEvent, "eventId" | "provider" | "createdAt" | "threadId"> {
return {
eventId: EventId.make(`recorded:${provider}:${turnIndex}:${eventIndex}`),
provider,
createdAt: fixtureTimestamp(turnIndex, eventIndex),
threadId: FIXTURE_THREAD_ID,
};
}
/**
* Synthetic canonical events calibrated from heavy local Codex and Claude
* threads. Ten historical turns produce 9 MB of retained MCP results without
* committing user content. Command output is intentionally modest because the
* client projection strips it.
*/
export function makeRecordedTransferTurn(
provider: ProviderDriverKind,
turnIndex: number,
): TestTurnResponse {
const measuredTurn = turnIndex >= TRANSFER_HISTORY_TURN_COUNT;
const toolCount = measuredTurn ? TRANSFER_MEASURED_TOOLS : TRANSFER_HISTORY_TOOLS_PER_TURN;
const turnId = `${FIXTURE_TURN_ID}-${turnIndex + 1}`;
const events: FixtureProviderRuntimeEvent[] = [];
let eventIndex = 0;
events.push({
type: "turn.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
model: provider === "codex" ? "gpt-5.4" : "claude-opus-4-1",
effort: provider === "codex" ? "high" : "default",
},
});
for (let toolIndex = 0; toolIndex < toolCount; toolIndex += 1) {
const itemId = `tool-${turnIndex + 1}-${toolIndex + 1}`;
const command =
provider === "codex"
? `vp test transfer-budget-${toolIndex + 1}`
: `review transfer budget ${toolIndex + 1}`;
events.push(
{
type: "item.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId,
payload: {
itemType: "command_execution",
status: "inProgress",
title: `Inspect transfer path ${toolIndex + 1}`,
detail: "Inspecting the HTTP snapshot and WebSocket projection boundaries.",
data: {
threadId: FIXTURE_THREAD_ID,
turnId,
startedAtMs: turnIndex * 60_000 + eventIndex,
item: {
id: itemId,
type: "commandExecution",
command,
cwd: "/workspace/transfer-budget",
processId: String(toolIndex + 1),
status: "inProgress",
commandActions: [],
aggregatedOutput: "",
},
},
},
},
{
type: "item.completed",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId,
payload: {
itemType: "command_execution",
status: "completed",
title: `Inspected transfer path ${toolIndex + 1}`,
detail: "Collected a deterministic multi-module transfer diagnostic.",
data: {
threadId: FIXTURE_THREAD_ID,
turnId,
completedAtMs: turnIndex * 60_000 + eventIndex,
item: {
id: itemId,
type: "commandExecution",
command,
cwd: "/workspace/transfer-budget",
processId: String(toolIndex + 1),
status: "completed",
commandActions: [],
aggregatedOutput: diagnosticOutput({
provider,
turnIndex,
toolIndex,
targetBytes: 1_000,
}),
exitCode: 0,
durationMs: 500 + toolIndex,
},
},
},
},
);
}
const mcpItemId = `mcp-${turnIndex + 1}`;
const mcpResultBytes = measuredTurn
? TRANSFER_MEASURED_MCP_RESULT_BYTES
: TRANSFER_HISTORY_MCP_RESULT_BYTES;
events.push(
{
type: "item.started",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: mcpItemId,
payload: {
itemType: "mcp_tool_call",
status: "inProgress",
title: "fixture-history · inspect_transfer_log",
detail: "Reading a retained diagnostic result from the provider history.",
data: {
startedAtMs: turnIndex * 60_000 + eventIndex,
threadId: FIXTURE_THREAD_ID,
turnId,
item: {
type: "mcpToolCall",
id: mcpItemId,
server: "fixture-history",
tool: "inspect_transfer_log",
arguments: { turn: turnIndex + 1 },
status: "inProgress",
},
},
},
},
{
type: "item.completed",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: mcpItemId,
payload: {
itemType: "mcp_tool_call",
status: "completed",
title: "fixture-history · inspect_transfer_log",
detail: "Retained a deterministic diagnostic result in the thread history.",
data: {
completedAtMs: turnIndex * 60_000 + eventIndex,
threadId: FIXTURE_THREAD_ID,
turnId,
item: {
type: "mcpToolCall",
id: mcpItemId,
server: "fixture-history",
tool: "inspect_transfer_log",
arguments: { turn: turnIndex + 1 },
durationMs: 1_000 + turnIndex,
error: null,
result: {
content: [
{
type: "text",
text: diagnosticOutput({
provider,
turnIndex,
toolIndex: toolCount,
targetBytes: mcpResultBytes,
}),
},
],
},
status: "completed",
},
},
},
},
);
const chunks = assistantChunks(provider, turnIndex);
for (const [contentIndex, delta] of chunks.entries()) {
events.push({
type: "content.delta",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
itemId: `assistant-${turnIndex + 1}`,
payload: {
streamKind: "assistant_text",
delta,
contentIndex,
},
});
}
events.push(
{
type: "thread.token-usage.updated",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
usage: {
usedTokens: 18_000 + turnIndex * 1_900,
maxTokens: 200_000,
inputTokens: 15_000 + turnIndex * 1_700,
cachedInputTokens: 9_000 + turnIndex * 1_100,
outputTokens: 3_000 + turnIndex * 200,
toolUses: toolCount,
durationMs: 4_000 + turnIndex * 250,
},
},
},
{
type: "turn.diff.updated",
...baseEvent(provider, turnIndex, eventIndex++),
turnId,
payload: {
unifiedDiff: unifiedDiff(provider, turnIndex),
},
},
{
type: "turn.completed",
...baseEvent(provider, turnIndex, eventIndex),
turnId,
payload: {
state: "completed",
stopReason: "end_turn",
usage: {
inputTokens: 15_000 + turnIndex * 1_700,
outputTokens: 3_000 + turnIndex * 200,
},
},
},
);
return { events };
}
@@ -8,7 +8,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
@@ -23,7 +22,6 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import * as ServerConfig from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
@@ -56,59 +54,35 @@ interface IntegrationFixture {
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
interface RecordedAnalyticsEvent {
readonly event: string;
readonly properties: Readonly<Record<string, unknown>> | undefined;
}
const makeIntegrationFixture = Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
/**
* Analytics layer that keeps captured events in memory so tests can assert on
* telemetry payloads. `AnalyticsService.layerTest` discards them.
*/
const makeRecordingAnalytics = Effect.gen(function* () {
const recorded = yield* Ref.make<ReadonlyArray<RecordedAnalyticsEvent>>([]);
const layer = Layer.succeed(
AnalyticsService,
AnalyticsService.of({
record: (event, properties) =>
Ref.update(recorded, (current) => [...current, { event, properties }]),
flush: Effect.void,
}),
);
return { layer, get: Ref.get(recorded) } as const;
});
const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<AnalyticsService> }) =>
Effect.gen(function* () {
const cwd = yield* makeWorkspaceDirectory;
const harness = yield* makeTestProviderAdapterHarness();
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
options?.analytics ?? AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
const registry = makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: harness.adapter,
});
const directoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntime.layer),
);
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
).pipe(Layer.provide(SqlitePersistenceMemory));
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
return {
cwd,
harness,
layer,
} satisfies IntegrationFixture;
});
const collectEventsDuring = <A, E, R>(
stream: Stream.Stream<ProviderRuntimeEvent>,
count: number,
@@ -152,7 +126,7 @@ const runTurn = (input: {
it.live("replays typed runtime fixture events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const fixture = yield* makeIntegrationFixture;
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
@@ -187,7 +161,7 @@ it.live("replays typed runtime fixture events", () =>
it.live("replays file-changing fixture turn events", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
@@ -224,7 +198,7 @@ it.live("replays file-changing fixture turn events", () =>
it.live("runs multi-turn tool/approval flow", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString } = yield* FileSystem.FileSystem;
@@ -276,7 +250,7 @@ it.live("runs multi-turn tool/approval flow", () =>
it.live("rolls back provider conversation state only", () =>
Effect.gen(function* () {
const fixture = yield* makeIntegrationFixture();
const fixture = yield* makeIntegrationFixture;
const { join } = yield* Path.Path;
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
@@ -328,59 +302,3 @@ it.live("rolls back provider conversation state only", () =>
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
it.live("reports runtime mode per turn and on mode transitions", () =>
Effect.gen(function* () {
const analytics = yield* makeRecordingAnalytics;
const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer });
const threadId = ThreadId.make("thread-integration-runtime-mode");
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const startSession = (runtimeMode: "approval-required" | "full-access") =>
provider.startSession(threadId, {
threadId,
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
cwd: fixture.cwd,
runtimeMode,
});
yield* startSession("approval-required");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "supervised turn",
response: { events: codexTurnTextFixture },
});
// Toggling the mode restarts the session, which is the only place the
// transition is observable.
yield* startSession("full-access");
yield* runTurn({
provider,
harness: fixture.harness,
threadId,
userText: "full access turn",
response: { events: codexTurnTextFixture },
});
const recorded = yield* analytics.get;
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.turn.sent")
.map((entry) => entry.properties?.runtimeMode),
["approval-required", "full-access"],
);
assert.deepEqual(
recorded
.filter((entry) => entry.event === "provider.runtime_mode.changed")
.map((entry) => [entry.properties?.from, entry.properties?.to]),
[["approval-required", "full-access"]],
);
}).pipe(Effect.provide(fixture.layer));
}).pipe(Effect.provide(NodeServices.layer)),
);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.32",
"version": "0.0.31",
"license": "MIT",
"repository": {
"type": "git",
-2
View File
@@ -45,8 +45,6 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetAccountLimits]: AuthOrchestrationReadScope,
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
@@ -146,7 +146,6 @@ export const make = Effect.gen(function* () {
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
-68
View File
@@ -5,7 +5,6 @@ import * as NodeChildProcess from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -949,73 +948,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
}),
);
it.effect("status skips the provider lookup for a branch that was never pushed", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/never-pushed"]);
const { manager, ghCalls } = yield* makeManager();
const status = yield* manager.status({ cwd: repoDir });
expect(status.refName).toBe("feature/never-pushed");
expect(status.pr).toBeNull();
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(0);
}),
);
it.effect("status still looks up PRs for a branch pushed without --set-upstream", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
const remoteDir = yield* createBareRemote();
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
yield* runGit(repoDir, ["checkout", "-b", "feature/pushed-no-upstream"]);
// No `-u`, so the remote-tracking ref exists but branch.<name>.merge does
// not. Most terminal and agent pushes land this way, and they can still
// have a PR, so the skip must not trigger here.
yield* runGit(repoDir, ["push", "origin", "feature/pushed-no-upstream"]);
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 214,
title: "Pushed without upstream",
url: "https://github.com/pingdotgg/t3code/pull/214",
baseRefName: "main",
headRefName: "feature/pushed-no-upstream",
state: "OPEN",
updatedAt: "2026-04-01T15:00:00Z",
},
]),
],
},
});
const status = yield* manager.status({ cwd: repoDir });
expect(status.pr?.number).toBe(214);
expect(ghCalls.filter((call) => call.startsWith("pr list ")).length).toBeGreaterThan(0);
}),
);
it("backs off repeated PR lookup failures past the healthy refresh cadence", () => {
expect(Duration.toMillis(GitManager.prLookupFailureTtl(1))).toBe(20_000);
expect(Duration.toMillis(GitManager.prLookupFailureTtl(2))).toBe(40_000);
// The point of the backoff: by the third retry a failing branch must not be
// asking more often than a healthy one, which refreshes every 2 minutes.
expect(Duration.toMillis(GitManager.prLookupFailureTtl(4))).toBeGreaterThan(120_000);
expect(Duration.toMillis(GitManager.prLookupFailureTtl(20))).toBe(900_000);
});
it.effect(
"status ignores unrelated fork PRs when the current branch tracks the same repository",
() =>
+9 -89
View File
@@ -110,25 +110,8 @@ const TOAST_DESCRIPTION_MAX = 72;
const STATUS_RESULT_CACHE_TTL = Duration.seconds(1);
const STATUS_RESULT_CACHE_CAPACITY = 2_048;
const PR_LOOKUP_CACHE_TTL = Duration.minutes(2);
const PR_LOOKUP_FAILURE_BASE_TTL = Duration.seconds(20);
const PR_LOOKUP_FAILURE_MAX_TTL = Duration.minutes(15);
const PR_LOOKUP_FAILURE_TTL = Duration.seconds(20);
const PR_LOOKUP_CACHE_CAPACITY = 2_048;
/**
* How long a failed PR lookup is cached, given the number of consecutive
* failures for that branch.
*
* A hosting provider rejects a throttled request immediately, so caching every
* failure for a flat 20s made a rate-limited poller re-ask *faster* than a
* healthy one does (which waits PR_LOOKUP_CACHE_TTL), turning a transient 429
* into sustained pressure. Backing off per branch keeps the retry rate below
* the healthy rate once a branch has failed more than a couple of times.
*/
export function prLookupFailureTtl(consecutiveFailures: number): Duration.Duration {
const exponent = Math.max(0, consecutiveFailures - 1);
const backoffMs = Duration.toMillis(PR_LOOKUP_FAILURE_BASE_TTL) * Math.pow(2, exponent);
return Duration.min(Duration.millis(backoffMs), PR_LOOKUP_FAILURE_MAX_TTL);
}
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
type GitActionProgressEmitter = (event: GitActionProgressPayload) => Effect.Effect<void, never>;
@@ -906,23 +889,6 @@ export const make = Effect.gen(function* () {
// back to a null upstreamRef.
const prLookupCacheKey = (cwd: string, details: { branch: string; upstreamRef: string | null }) =>
[cwd, details.branch, details.upstreamRef ?? "", String(prLookupEpoch(cwd))].join("\u0000");
// Consecutive failures per cache key, so a branch that keeps failing waits
// longer before the next attempt. Cleared as soon as a lookup succeeds.
const prLookupFailureStreakByKey = new Map<string, number>();
const nextPrLookupFailureTtl = (key: string) => {
if (
!prLookupFailureStreakByKey.has(key) &&
prLookupFailureStreakByKey.size >= PR_LOOKUP_CACHE_CAPACITY
) {
const oldestKey = prLookupFailureStreakByKey.keys().next().value;
if (oldestKey !== undefined) {
prLookupFailureStreakByKey.delete(oldestKey);
}
}
const streak = (prLookupFailureStreakByKey.get(key) ?? 0) + 1;
prLookupFailureStreakByKey.set(key, streak);
return prLookupFailureTtl(streak);
};
const prLookupCache = yield* Cache.makeWith(
(key: string) => {
const [cwd = "", branch = "", upstreamRef = ""] = key.split("\u0000");
@@ -930,26 +896,17 @@ export const make = Effect.gen(function* () {
branch,
upstreamRef: upstreamRef.length > 0 ? upstreamRef : null,
};
return Effect.gen(function* () {
const headContext = yield* resolveBranchHeadContext(cwd, details);
// Only skip when the branch is untracked as well: anything carrying an
// upstream keeps the old behaviour.
if (details.upstreamRef === null && (yield* isUnpublishedBranch(cwd, headContext))) {
return { latest: null, headContext };
}
const latest = yield* findLatestPrForHeadContext(cwd, headContext);
return { latest, headContext };
});
return resolveBranchHeadContext(cwd, details).pipe(
Effect.flatMap((headContext) =>
findLatestPrForHeadContext(cwd, headContext).pipe(
Effect.map((latest) => ({ latest, headContext })),
),
),
);
},
{
capacity: PR_LOOKUP_CACHE_CAPACITY,
timeToLive: (exit, key) => {
if (Exit.isSuccess(exit)) {
prLookupFailureStreakByKey.delete(key);
return PR_LOOKUP_CACHE_TTL;
}
return nextPrLookupFailureTtl(key);
},
timeToLive: (exit) => (Exit.isSuccess(exit) ? PR_LOOKUP_CACHE_TTL : PR_LOOKUP_FAILURE_TTL),
},
);
// A transient lookup failure (rate limit, network blip) must not clear an
@@ -1212,43 +1169,6 @@ export const make = Effect.gen(function* () {
} satisfies BranchHeadContext;
});
/**
* Whether git has no record of this branch on any remote, so a change request
* cannot exist for it and asking the provider is a guaranteed-empty API call.
*
* `git push` writes the remote-tracking ref even without `-u` (how most
* terminal and agent pushes land), which makes this a safer "did it ever
* reach the host" test than looking for upstream config, and the glob spans
* every remote so a fork branch still counts. A repository that tracks no
* remotes at all cannot answer the question, because then every branch looks
* unpublished; it, and any failed probe, keeps the lookup.
*/
const isUnpublishedBranch = Effect.fn("isUnpublishedBranch")(function* (
cwd: string,
headContext: Pick<BranchHeadContext, "headBranch">,
) {
if (headContext.headBranch.length === 0) {
return false;
}
const matchesRef = (pattern: string) =>
gitCore
.execute({
operation: "GitManager.isUnpublishedBranch",
cwd,
args: ["for-each-ref", "--count=1", "--format=%(refname)", pattern],
timeoutMs: 5_000,
})
.pipe(Effect.map((result) => result.stdout.trim().length > 0));
return yield* Effect.all(
[matchesRef("refs/remotes"), matchesRef(`refs/remotes/*/${headContext.headBranch}`)],
{ concurrency: "unbounded" },
).pipe(
Effect.map(([tracksAnyRemote, tracksThisBranch]) => tracksAnyRemote && !tracksThisBranch),
Effect.orElseSucceed(() => false),
);
});
const findOpenPr = Effect.fn("findOpenPr")(function* (
cwd: string,
headContext: Pick<
-1
View File
@@ -198,7 +198,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("themeEditor.toggle"), "mod+alt+shift+t");
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
@@ -40,7 +40,6 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -297,7 +296,6 @@ describe("CheckpointReactor", () => {
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -306,7 +304,6 @@ describe("CheckpointReactor", () => {
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -32,7 +32,6 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
@@ -58,7 +57,6 @@ async function createOrchestrationSystem() {
OrchestrationProjectionSnapshotQueryLive,
).pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
@@ -822,7 +820,6 @@ describe("OrchestrationEngine", () => {
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -929,7 +926,6 @@ describe("OrchestrationEngine", () => {
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -1074,7 +1070,6 @@ describe("OrchestrationEngine", () => {
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -32,7 +32,6 @@ import {
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -2674,7 +2673,6 @@ const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -612,7 +612,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinOrderKey: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -729,9 +728,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
...(event.payload.pinOrderKey !== undefined
? { pinOrderKey: event.payload.pinOrderKey }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -747,22 +743,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
pinOrderKey: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pin-reordered": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinOrderKey: event.payload.orderKey,
updatedAt: event.payload.updatedAt,
});
return;
@@ -18,7 +18,6 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
@@ -31,7 +30,6 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
@@ -87,8 +85,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
pinned_at,
pin_order_key,
created_at,
updated_at,
deleted_at
@@ -107,8 +103,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
1,
0,
0,
'2026-02-24T00:00:01.000Z',
'gm',
'2026-02-24T00:00:02.000Z',
'2026-02-24T00:00:03.000Z',
NULL
@@ -321,8 +315,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
pinnedAt: null,
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -438,8 +431,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
pinnedAt: null,
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -455,7 +447,6 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingUserInput: false,
hasActionableProposedPlan: false,
backgroundLiveness: null,
planProgress: null,
},
]);
@@ -1839,7 +1830,6 @@ it.effect(
const resolveCalls: string[] = [];
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provideMerge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (cwd: string) =>
@@ -44,7 +44,6 @@ import {
} from "../../persistence/Errors.ts";
import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
@@ -345,7 +344,6 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const threadPlanProgress = yield* ThreadPlanProgressService;
const sql = yield* SqlClient.SqlClient;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const repositoryIdentityResolutionConcurrency = 4;
@@ -423,7 +421,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -459,7 +456,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -497,7 +493,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -935,7 +930,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1566,7 +1560,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1771,7 +1764,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1907,7 +1899,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -1917,7 +1908,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -2052,7 +2042,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
@@ -2062,7 +2051,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -2329,7 +2317,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
@@ -2339,7 +2326,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
threadRow.value.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(threadRow.value.threadId),
} satisfies OrchestrationThreadShell);
});
@@ -2450,7 +2436,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -49,7 +49,6 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
@@ -348,7 +347,6 @@ describe("ProviderCommandReactor", () => {
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -357,7 +355,6 @@ describe("ProviderCommandReactor", () => {
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -1,84 +0,0 @@
import {
EventId,
ProviderDriverKind,
RuntimeTaskId,
ThreadId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { runtimeEventToActivities } from "./ProviderRuntimeIngestion.ts";
const base = {
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-08-06T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
};
describe("runtimeEventToActivities task progress", () => {
it("persists usage independently from replaceable activity", () => {
const taskId = RuntimeTaskId.make("agent-1");
const usageOnly = {
...base,
type: "task.progress",
eventId: EventId.make("evt-usage"),
payload: {
taskId,
description: "Agent one",
typedUsage: { totalTokens: 73_700_000 },
},
} satisfies ProviderRuntimeEvent;
const command = {
...base,
type: "task.progress",
eventId: EventId.make("evt-command"),
payload: {
taskId,
description: "Agent one",
summary: "Running tests",
lastToolName: "exec_command",
},
} satisfies ProviderRuntimeEvent;
const usageActivities = runtimeEventToActivities(usageOnly);
const commandActivities = runtimeEventToActivities(command);
expect(usageActivities.map((activity) => activity.id)).toEqual(["task-usage:thread-1:agent-1"]);
expect(commandActivities.map((activity) => activity.id)).toEqual([
"task-progress:thread-1:agent-1",
]);
const usagePayload = usageActivities[0]?.payload as Record<string, unknown> | undefined;
expect(usagePayload?.typedUsage).toEqual({ totalTokens: 73_700_000 });
expect(usagePayload?.usageSnapshot).toBe(true);
});
it("splits combined progress and usage into their independent snapshots", () => {
const event = {
...base,
type: "task.progress",
eventId: EventId.make("evt-combined"),
payload: {
taskId: RuntimeTaskId.make("agent-2"),
description: "Agent two",
summary: "Inspecting the panel",
typedUsage: { totalTokens: 4_200, toolUses: 7 },
status: "running",
},
} satisfies ProviderRuntimeEvent;
const activities = runtimeEventToActivities(event);
const progressPayload = activities[0]?.payload as Record<string, unknown>;
const usagePayload = activities[1]?.payload as Record<string, unknown>;
expect(activities.map((activity) => activity.id)).toEqual([
"task-progress:thread-1:agent-2",
"task-usage:thread-1:agent-2",
]);
expect(progressPayload.summary).toBe("Inspecting the panel");
expect(progressPayload.status).toBe("running");
expect(progressPayload).not.toHaveProperty("typedUsage");
expect(usagePayload.typedUsage).toEqual({ totalTokens: 4_200, toolUses: 7 });
expect(usagePayload.usageSnapshot).toBe(true);
expect(usagePayload).not.toHaveProperty("status");
});
});
@@ -16,7 +16,6 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
type OrchestrationCommand,
ProjectId,
ProviderItemId,
type ServerSettings,
@@ -46,14 +45,12 @@ import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import * as AccountLimitsService from "../../usage/AccountLimitsService.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
@@ -244,10 +241,8 @@ describe("ProviderRuntimeIngestion", () => {
// Single shared liveness instance across ingestion (writer), the
// engine, and the snapshot query (reader).
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(AccountLimitsService.layerTest),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
@@ -259,52 +254,57 @@ describe("ProviderRuntimeIngestion", () => {
scope = await Effect.runPromise(Scope.make("sequential"));
await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(ingestion.drain);
const dispatch = (command: OrchestrationCommand) => Effect.runPromise(engine.dispatch(command));
const createdAt = "2026-01-01T00:00:00.000Z";
await dispatch({
type: "project.create",
commandId: CommandId.make("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
});
await dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
});
await dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed"),
threadId: ThreadId.make("thread-1"),
session: {
await Effect.runPromise(
engine.dispatch({
type: "project.create",
commandId: CommandId.make("cmd-provider-project-create"),
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
createdAt,
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create"),
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
});
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
);
provider.setSession({
provider: ProviderDriverKind.make("codex"),
status: "ready",
@@ -316,7 +316,6 @@ describe("ProviderRuntimeIngestion", () => {
return {
engine,
dispatch,
readModel: () => Effect.runPromise(snapshotQuery.getSnapshot()),
emit: provider.emit,
setProviderSession: provider.setSession,
@@ -842,82 +841,6 @@ describe("ProviderRuntimeIngestion", () => {
);
});
it("rejects an untargeted turn.completed when no turn is active", async () => {
const harness = await createHarness();
const seededAt = "2026-01-01T00:00:00.000Z";
// A turn start is pending: the session reads "starting" with no active
// turn tracked yet. This is the window the Claude resume handshake's
// phantom (turn.completed with no turnId) used to slip through, stomping
// "starting" back to "ready" for a turn that never existed.
await harness.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed-untargeted-completion"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "starting",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
});
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-untargeted"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: seededAt,
threadId: asThreadId("thread-1"),
status: "completed",
});
await harness.drain();
const readModel = await harness.readModel();
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(thread?.session?.status).toBe("starting");
expect(thread?.session?.activeTurnId).toBeNull();
});
it("accepts a targeted turn.completed when no turn is active", async () => {
const harness = await createHarness();
const seededAt = "2026-01-01T00:00:00.000Z";
// A completion that names its turn still lands even when no active turn
// is tracked (e.g. its turn.started was lost). Only untargeted
// completions are rejected.
await harness.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-seed-targeted-completion"),
threadId: ThreadId.make("thread-1"),
session: {
threadId: ThreadId.make("thread-1"),
status: "starting",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: seededAt,
lastError: null,
},
createdAt: seededAt,
});
harness.emit({
type: "turn.completed",
eventId: asEventId("evt-turn-completed-targeted-late"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: seededAt,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-late"),
status: "completed",
});
await waitForThread(harness.readModel, (thread) => thread.session?.status === "ready");
});
it("ignores non-active turn completion when runtime omits thread id", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
@@ -2274,7 +2197,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("starts a new streaming assistant message segment after approval", async () => {
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const startedAt = "2026-03-28T07:00:00.000Z";
const pausedAt = "2026-03-28T07:00:01.000Z";
const resumedAt = "2026-03-28T07:00:02.000Z";
@@ -2381,7 +2304,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
@@ -35,7 +35,6 @@ import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/Projectio
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderRuntimeIngestionService,
@@ -43,7 +42,6 @@ import {
} from "../Services/ProviderRuntimeIngestion.ts";
import { forkParked } from "../../serverActivation.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { AccountLimitsService } from "../../usage/AccountLimitsService.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
@@ -565,80 +563,39 @@ export function runtimeEventToActivities(
}
case "task.progress": {
const linkage = taskLinkageActivityFields(event.payload as Record<string, unknown>);
// Usage and activity are independent latest-state streams. Keeping them
// under separate stable ids prevents a command/reasoning update from
// replacing the last known token count (and prevents a usage-only tick
// from blanking the last meaningful activity).
const identityLinkage = { ...linkage };
delete identityLinkage.typedUsage;
delete identityLinkage.status;
delete identityLinkage.error;
const title =
event.payload.description.trim().length > 0
? { title: truncateDetail(event.payload.description, 120) }
: {};
const hasProgressState =
event.payload.typedUsage === undefined ||
event.payload.summary !== undefined ||
event.payload.lastToolName !== undefined ||
event.payload.status !== undefined ||
event.payload.error !== undefined;
return [
...(hasProgressState
? [
{
// Stable per-task id: activity is "latest state", not
// history, so each meaningful tick replaces the last. This
// bounds a large fleet to one activity row per task.
id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info" as const,
kind: "task.progress" as const,
summary:
event.payload.description.trim().length > 0
? truncateDetail(event.payload.description, 120)
: "Reasoning update",
payload: {
taskId: event.payload.taskId,
...title,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary
? { summary: truncateDetail(event.payload.summary) }
: {}),
...(event.payload.lastToolName
? { lastToolName: event.payload.lastToolName }
: {}),
...(event.payload.status ? { status: event.payload.status } : {}),
...(event.payload.error ? { error: event.payload.error } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...identityLinkage,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
]
: []),
...(event.payload.typedUsage !== undefined
? [
{
id: EventId.make(`task-usage:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info" as const,
kind: "task.progress" as const,
summary: "Task usage updated",
payload: {
taskId: event.payload.taskId,
...title,
...identityLinkage,
usageSnapshot: true,
typedUsage: event.payload.typedUsage,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
]
: []),
{
// Stable per-task id: progress is "latest state", not history, so
// each tick REPLACES the last via the activity upsert (PK + the
// replace-by-id apply in projector and client reducer). Keeps one
// progress row per task instead of thousands, so a large fleet's
// ticks can no longer evict its own start/terminal rows out of
// the 500-row retention window. Thread-scoped: activity_id is a
// GLOBAL primary key and Claude task ids are session-local, so a
// bare taskId could collide across threads and steal another
// thread's row (review finding).
id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
summary:
event.payload.description.trim().length > 0
? truncateDetail(event.payload.description, 120)
: "Reasoning update",
payload: {
taskId: event.payload.taskId,
...(event.payload.description.trim().length > 0
? { title: truncateDetail(event.payload.description, 120) }
: {}),
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
@@ -869,14 +826,12 @@ export function runtimeEventToActivities(
const make = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const threadPlanProgress = yield* ThreadPlanProgressService;
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const accountLimits = yield* AccountLimitsService;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
@@ -1476,17 +1431,6 @@ const make = Effect.gen(function* () {
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
// Rate-limit payloads feed the server-wide limits cache, not a thread
// projection, so they are folded in before the thread lookup: a
// snapshot must not be lost because its thread is already gone.
if (event.type === "account.rate-limits.updated") {
yield* accountLimits.ingest({
provider: event.provider,
payload: event.payload.rateLimits,
createdAt: event.createdAt,
});
}
const thread = yield* resolveThreadShell(event.threadId);
if (!thread) return;
@@ -1545,14 +1489,8 @@ const make = Effect.gen(function* () {
if (activeTurnId !== null && eventTurnId !== undefined) {
return sameId(activeTurnId, eventTurnId);
}
// No active turn tracked: accept only completions that name their
// turn (covers a real completion whose turn.started was lost). An
// untargeted completion cannot prove it belongs to any turn this
// thread ran — the known emitter was the Claude resume handshake
// (system/init + result(num_turns: 0)), which is not a turn at
// all — and applying it here stomps the "starting" lifecycle
// state while a turn start is pending.
return eventTurnId !== undefined;
// If no active turn is tracked, accept completion scoped to this thread.
return true;
default:
return true;
}
@@ -1674,7 +1612,7 @@ const make = Effect.gen(function* () {
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
@@ -1710,7 +1648,7 @@ const make = Effect.gen(function* () {
const detailedThread = yield* getLoadedThreadDetail();
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
const flushedMessageIds =
assistantDeliveryMode === "buffered"
@@ -1956,21 +1894,6 @@ const make = Effect.gen(function* () {
yield* rememberTaskDescription(thread.id, event.payload.taskId, description);
}
}
// Working-indicator plan progress: current step while the turn runs,
// cleared on settle so a finished plan never lingers as stale UI.
// Events carrying a turn id that conflicts with the active turn are
// stale (superseded turn) and must neither overwrite nor clear the
// active turn's progress; session.exited always clears.
if (event.type === "session.exited") {
threadPlanProgress.clearThreadPlanProgress(thread.id);
} else if (!conflictsWithActiveTurn) {
if (event.type === "turn.plan.updated") {
threadPlanProgress.recordPlanProgress(thread.id, event.payload.plan);
} else if (event.type === "turn.completed" || event.type === "turn.aborted") {
threadPlanProgress.clearThreadPlanProgress(thread.id);
}
}
// Sidebar background liveness: fed from the same lifecycle stream,
// read by the shell query at mapping time (no persistence).
switch (event.type) {
-2
View File
@@ -15,7 +15,6 @@ import {
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -47,7 +46,6 @@ export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -1,44 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";
describe("ThreadPlanProgress", () => {
it("tracks the in-progress step and clears when the plan completes", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-1";
progress.recordPlanProgress(threadId, [
{ step: "Audit failure paths", status: "completed" },
{ step: "Implement the fix", status: "inProgress" },
{ step: "Run targeted tests", status: "pending" },
]);
expect(progress.getThreadPlanProgress(threadId)).toEqual({
step: "Implement the fix",
completedSteps: 1,
totalSteps: 3,
});
progress.recordPlanProgress(threadId, [
{ step: "Audit failure paths", status: "completed" },
{ step: "Implement the fix", status: "completed" },
{ step: "Run targeted tests", status: "completed" },
]);
expect(progress.getThreadPlanProgress(threadId)).toBeNull();
});
it("falls back to the first non-completed step when nothing is in progress", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-2";
progress.recordPlanProgress(threadId, [
{ step: "First", status: "pending" },
{ step: "Second", status: "pending" },
]);
expect(progress.getThreadPlanProgress(threadId)?.step).toBe("First");
});
it("clearThreadPlanProgress removes the entry (turn settled / session died)", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-3";
progress.recordPlanProgress(threadId, [{ step: "Only step", status: "inProgress" }]);
progress.clearThreadPlanProgress(threadId);
expect(progress.getThreadPlanProgress(threadId)).toBeNull();
});
});
@@ -1,76 +0,0 @@
/**
* ThreadPlanProgressService - in-memory per-thread plan progress for the
* Working indicators (sidebar rows, in-chat working line).
*
* Plans are a progress annotation, not a surface of their own: the useful
* kernel of a turn.plan.updated event is "which step is the agent on right
* now". Ingestion records the current step here and the shell query reads it
* at mapping time — no persistence, no migration (same pattern as
* ThreadBackgroundLivenessService). Cleared when the turn settles or the
* session dies, so a finished plan never lingers as stale UI.
*
* @module ThreadPlanProgressService
*/
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export interface ThreadPlanProgress {
readonly step: string;
readonly completedSteps: number;
readonly totalSteps: number;
}
interface PlanStepInput {
readonly step: string;
readonly status: string;
}
export class ThreadPlanProgressService extends Context.Service<
ThreadPlanProgressService,
{
/**
* Feed one turn.plan.updated payload. An all-completed plan clears the
* entry (the turn is wrapping up; nothing is "in progress" anymore).
*/
readonly recordPlanProgress: (threadId: string, plan: ReadonlyArray<PlanStepInput>) => void;
/** Turn settled or session died: the working indicator reverts to plain. */
readonly clearThreadPlanProgress: (threadId: string) => void;
readonly getThreadPlanProgress: (threadId: string) => ThreadPlanProgress | null;
}
>()("t3/orchestration/ThreadPlanProgress/ThreadPlanProgressService") {}
export function make(): ThreadPlanProgressService["Service"] {
const progressByThreadId = new Map<string, ThreadPlanProgress>();
return {
recordPlanProgress: (threadId, plan) => {
const totalSteps = plan.length;
const completedSteps = plan.filter((step) => step.status === "completed").length;
// Current step: the in-progress one, else the first pending one (a
// plan that was just written has no in-progress step yet).
const current =
plan.find((step) => step.status === "inProgress") ??
plan.find((step) => step.status !== "completed");
if (totalSteps === 0 || completedSteps === totalSteps || current === undefined) {
progressByThreadId.delete(threadId);
return;
}
progressByThreadId.set(threadId, {
step: current.step,
completedSteps,
totalSteps,
});
},
clearThreadPlanProgress: (threadId) => {
progressByThreadId.delete(threadId);
},
getThreadPlanProgress: (threadId) => progressByThreadId.get(threadId) ?? null,
};
}
export const layer = Layer.effect(ThreadPlanProgressService, Effect.sync(make));
@@ -16,7 +16,6 @@ const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly pinOrderKey?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
@@ -45,7 +44,6 @@ function makeReadModel(input: {
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
pinOrderKey: input.pinOrderKey ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -225,100 +223,4 @@ it.layer(NodeServices.layer)("pinned thread decider", (it) => {
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("a fresh pin carries the client's order key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBe("g");
}
}),
);
it.effect(
"re-pinning ignores the incoming order key so raced pins cannot move a placed thread",
() =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed-again"),
threadId: ThreadId.make("thread-1"),
orderKey: "t",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBeUndefined();
}
}),
);
it.effect("reorders a pinned thread, stamping the new key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.orderKey).toBe("m");
// A real move stamps the command time (the test clock), not the
// thread's previous updatedAt.
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("reordering onto the same key preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-noop"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("rejects reordering an unpinned thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-unpinned"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
-43
View File
@@ -676,12 +676,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
// A fresh pin takes the client's slot in the arranged order; on a
// re-pin the existing key wins so raced duplicates cannot move a
// thread the user already placed.
...(existingPinnedAt === null && command.orderKey !== undefined
? { pinOrderKey: command.orderKey }
: {}),
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
@@ -751,43 +745,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin.reorder": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Only pinned threads have a slot in the arranged order. Rejecting
// (rather than silently pinning) keeps a raced reorder-after-unpin
// from resurrecting a pin the user just cleared.
if (thread.pinnedAt == null) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
}),
);
}
// Idempotent by re-emission (see thread.settle): a duplicate drop on
// the same slot keeps the existing updatedAt so it projects as a no-op.
const keyUnchanged = thread.pinOrderKey === command.orderKey;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pin-reordered",
payload: {
threadId: command.threadId,
orderKey: command.orderKey,
updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
@@ -75,80 +75,3 @@ it.effect("projects pin lifecycle events", () =>
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
it.effect("projects pin order key lifecycle", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinOrderKey ?? null).toBeNull();
// Fresh pin carries the client's slot in the arranged order.
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: {
threadId: ThreadId.make("thread-1"),
pinnedAt: now,
pinOrderKey: "g",
updatedAt: now,
},
}),
);
expect(pinned.threads[0]?.pinOrderKey).toBe("g");
// Re-pins and events from pre-reorder servers omit the field entirely;
// the existing key must survive rather than being nulled out.
const repinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(repinned.threads[0]?.pinOrderKey).toBe("g");
// A drag persists the new slot.
const reordered = yield* projectEvent(
repinned,
makeEvent({
sequence: 4,
type: "thread.pin-reordered",
payload: { threadId: ThreadId.make("thread-1"), orderKey: "m", updatedAt: now },
}),
);
expect(reordered.threads[0]?.pinOrderKey).toBe("m");
// Unpin clears the slot: re-pinning is "pin again", not "restore an
// ancient position".
const unpinned = yield* projectEvent(
reordered,
makeEvent({
sequence: 5,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinOrderKey).toBeNull();
}),
);
@@ -24,7 +24,6 @@ import {
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadPinReorderedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
@@ -403,7 +402,6 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),
updatedAt: payload.updatedAt,
}),
})),
@@ -415,20 +413,6 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
// Unpin clears the slot: re-pinning is "pin again", not "restore
// an ancient position".
pinOrderKey: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.pin-reordered":
return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinOrderKey: payload.orderKey,
updatedAt: payload.updatedAt,
}),
})),
@@ -6,7 +6,6 @@ import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";
export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
@@ -21,14 +20,10 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
// Shared background-liveness and plan-progress registries: written by
// runtime ingestion, read by the snapshot query. provideMerge feeds the
// same instance to the snapshot query here and re-exports it for runtime
// ingestion.
).pipe(
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
);
// Shared background-liveness registry: written by runtime ingestion,
// read by the snapshot query. provideMerge feeds the same instance to
// the snapshot query here and re-exports it for runtime ingestion.
).pipe(Layer.provideMerge(ThreadBackgroundLiveness.layer));
export const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
@@ -48,7 +48,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until,
snoozed_at,
pinned_at,
pin_order_key,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
@@ -75,7 +74,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
${row.pinOrderKey ?? null},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
@@ -102,7 +100,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
pin_order_key = excluded.pin_order_key,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
@@ -136,7 +133,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -172,7 +168,6 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -50,7 +50,6 @@ import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
/**
* Migration loader with all migrations defined inline.
@@ -100,7 +99,6 @@ export const migrationEntries = [
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
[37, "ProjectionTurnsKeysetIndex", Migration0037],
[38, "ProjectionThreadsPinOrderKey", Migration0038],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "pin_order_key")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pin_order_key TEXT
`;
}
});
@@ -42,7 +42,6 @@ export const ProjectionThread = Schema.Struct({
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
@@ -2,13 +2,11 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
@@ -157,130 +155,6 @@ it.effect("discovers editors through the service API", () =>
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("memoizes editor discovery and refreshes after the cache window", () => {
let statCalls = 0;
const fileInfo = { type: "File" } as FileSystem.File.Info;
const launcherLayer = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
stat: () =>
Effect.sync(() => {
statCalls += 1;
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const first = yield* launcher.resolveAvailableEditors();
assert.equal(first.includes("vscode"), true);
const statCallsAfterFirstScan = statCalls;
assert.isAbove(statCallsAfterFirstScan, 0);
// Past the shared command-resolution cache TTL (30s) but within the
// discovery cache window: the memoized set is reused without any scan.
yield* TestClock.adjust("31 seconds");
const second = yield* launcher.resolveAvailableEditors();
assert.deepEqual([...second], [...first]);
assert.equal(statCalls, statCallsAfterFirstScan);
// Past the discovery cache window the next call rescans.
yield* TestClock.adjust("30 seconds");
yield* launcher.resolveAvailableEditors();
assert.isAbove(statCalls, statCallsAfterFirstScan);
}).pipe(
Effect.provide(
Layer.mergeAll(
launcherLayer,
Layer.succeed(HostProcessPlatform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-cache-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
TestClock.layer(),
),
),
);
});
// A client that disconnects mid-scan interrupts the shared discovery effect on
// the connection fiber. The cache must not retain that interrupt: doing so
// replayed it to every later connect for the whole TTL, so `server.getConfig`
// failed and no client could reconnect until the server restarted.
it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => {
const fileInfo = { type: "File" } as FileSystem.File.Info;
let blockFirstScan = true;
let scans = 0;
const launcherLayer = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
// The first scan parks inside `stat` so the interrupt lands while
// discovery is in flight, which is what a client disconnecting
// mid-connect does to the shared effect.
stat: () =>
Effect.gen(function* () {
scans += 1;
if (blockFirstScan) {
return yield* Effect.never;
}
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
yield* Effect.yieldNow;
yield* Fiber.interrupt(fiber);
// The next connect must still get a real answer well inside the TTL.
blockFirstScan = false;
scans = 0;
const editors = yield* launcher.resolveAvailableEditors();
assert.equal(editors.includes("vscode"), true);
assert.isAbove(scans, 0);
}).pipe(
Effect.provide(
Layer.mergeAll(
launcherLayer,
Layer.succeed(HostProcessPlatform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-interrupt-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
),
),
);
});
it.effect("rejects unknown editors through the service API", () =>
Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
+1 -45
View File
@@ -19,7 +19,6 @@ import {
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -28,7 +27,6 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -300,28 +298,6 @@ const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEdit
return yield* buildAvailableEditors(platform, env);
});
// Editor discovery walks PATH for every known editor and runs for every
// client connect (the server config embeds the available editors). Memoize
// the discovered set for a bounded window so repeat connects skip even the
// per-command cache lookups in @t3tools/shared/shell.
//
// This deliberately does not use `Effect.cachedWithTTL`: that memoizes the
// first caller's Exit whatever it is, including an interrupt. Callers run this
// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`),
// so one client disconnecting mid-scan would cache the interrupt and replay it
// to every later connect for the whole TTL, breaking `server.getConfig`
// permanently. Storing only on success means an interrupted scan leaves the
// cache untouched and the next connect simply rescans.
// Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the
// command-resolution cache in @t3tools/shared/shell, so a backward wall-clock
// adjustment cannot keep an expired entry alive.
const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
interface EditorDiscoveryCacheEntry {
readonly editors: ReadonlyArray<EditorId>;
readonly expiresAtNanos: bigint;
}
/**
* ExternalLauncher - Service tag for browser/editor launch operations.
*/
@@ -467,28 +443,8 @@ export const make = Effect.gen(function* () {
Effect.provideService(Path.Path, path),
);
const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
Option.none(),
);
const cachedAvailableEditors = Effect.gen(function* () {
const nowNanos = yield* Clock.currentTimeNanos;
const entry = yield* Ref.get(editorDiscoveryCache);
if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) {
return entry.value.editors;
}
const editors = yield* provideCommandResolutionServices(resolveAvailableEditors());
yield* Ref.set(
editorDiscoveryCache,
Option.some({
editors,
expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS,
}),
);
return editors;
});
return ExternalLauncher.of({
resolveAvailableEditors: () => cachedAvailableEditors,
resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),
launchBrowser: (target) =>
launchBrowser(target).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -978,75 +978,6 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("does not emit turn.completed for a result with no active turn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Collect through session.exited so the window after the second result
// is deterministically inside the collection: both results are queued
// after sendTurn returns and drain in order on the one stream consumer.
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
Stream.takeUntil((event) => event.type === "session.exited"),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
num_turns: 1,
session_id: "sdk-session-1",
uuid: "result-real",
} as unknown as SDKMessage);
// Second result with no turn in flight — the shape the resume
// handshake (system/init + result(num_turns: 0)) delivers, and the
// same completeTurn branch every no-turnState result lands in. This
// used to emit an untargeted turn.completed; it must emit nothing.
harness.query.emit({
type: "result",
subtype: "success",
is_error: false,
errors: [],
num_turns: 0,
usage: { input_tokens: 0, output_tokens: 0 },
session_id: "sdk-session-1",
uuid: "result-handshake",
} as unknown as SDKMessage);
harness.query.finish();
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
const completions = runtimeEvents.filter((event) => event.type === "turn.completed");
// Exactly one completion — the real turn's, targeted at its turn id.
// The buggy branch produced a second, untargeted one here.
assert.equal(completions.length, 1);
const completed = completions[0];
if (completed?.type === "turn.completed") {
assert.equal(String(completed.turnId), String(turn.turnId));
assert.equal(completed.payload.state, "completed");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1580,7 +1511,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("interruptTurn settles every acknowledged live task before interrupting", () => {
it.effect("interruptTurn stops every live task before interrupting the turn", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -1637,28 +1568,11 @@ describe("ClaudeAdapterLive", () => {
yield* Fiber.join(taskEventsFiber);
const stoppedTaskEventFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type === "task.completed"),
Stream.take(1),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.interruptTurn(session.threadId);
// Only the still-live task is stopped; interrupt always fires after.
assert.deepEqual(harness.query.stopTaskCalls, ["task-live"]);
assert.equal(harness.query.interruptCalls.length, 1);
const stoppedTaskEvents = Array.from(yield* Fiber.join(stoppedTaskEventFiber));
assert.equal(stoppedTaskEvents.length, 1);
const stoppedTaskEvent = stoppedTaskEvents[0];
assert.equal(stoppedTaskEvent?.type, "task.completed");
if (stoppedTaskEvent?.type === "task.completed") {
assert.equal(String(stoppedTaskEvent.payload.taskId), "task-live");
assert.equal(stoppedTaskEvent.payload.status, "stopped");
assert.equal(stoppedTaskEvent.payload.taskType, "local_agent");
assert.equal(stoppedTaskEvent.payload.title, "Agent A");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
+24 -141
View File
@@ -15,7 +15,6 @@ import {
type PermissionUpdate,
type SDKMessage,
type SDKControlGetContextUsageResponse,
type SDKControlGetUsageResponse,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
@@ -59,7 +58,6 @@ import {
resolvePromptInjectedEffort,
} from "@t3tools/shared/model";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
@@ -67,7 +65,6 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
@@ -101,13 +98,6 @@ const encodeUnknownJsonStringExit = Schema.encodeUnknownExit(Schema.fromJsonStri
const decodeUnknownJsonStringExit = Schema.decodeUnknownExit(Schema.fromJsonString(Schema.Unknown));
const PROVIDER = ProviderDriverKind.make("claudeAgent");
/**
* Minimum spacing between account usage control requests. The request proxies
* the claude.ai usage endpoint, which rate limits aggressively, and sessions
* start often enough that fetching on every init would hammer it.
*/
const ACCOUNT_USAGE_MIN_INTERVAL_MS = 3 * 60_000;
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
type ClaudeToolResultStreamKind = Extract<
RuntimeContentStreamKind,
@@ -265,11 +255,6 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
/**
* SDK Query usage control request - the full rate-limit window set. The
* name is the SDK's own; optional for test doubles and older SDKs.
*/
readonly usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET?: () => Promise<SDKControlGetUsageResponse>;
readonly close: () => void;
}
@@ -2262,24 +2247,24 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: result ?? { status },
});
// A result with no local turn is never a turn this adapter started:
// real turns get turnState in sendTurn, and assistant messages that
// arrive outside a turn auto-start a synthetic one. What lands here is
// the resume handshake (system/init + result(num_turns: 0)), a late
// result for a turn already completed locally (steer auto-close,
// stream teardown), or a stream failure with no turn in flight. The
// untargeted turn.completed this branch used to emit carried no turnId,
// so ingestion could not attribute it — and whenever the projection had
// no active turn (a pending turn start included) it flipped the session
// lifecycle for a turn that never existed. Keep the usage emission,
// drop the lifecycle event, and leave a tripwire so the upstream
// trigger stays measurable in the field.
yield* Effect.logInfo("claude.turn.result-without-active-turn", {
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
status,
numTurns: result?.num_turns,
hasUsage: result?.usage !== undefined,
...(errorMessage ? { errorMessage } : {}),
payload: {
state: status,
...(result?.stop_reason !== undefined ? { stopReason: result.stop_reason } : {}),
...(result?.usage ? { usage: result.usage } : {}),
...(result?.modelUsage ? { modelUsage: result.modelUsage } : {}),
...(typeof result?.total_cost_usd === "number"
? { totalCostUsd: result.total_cost_usd }
: {}),
...(errorMessage ? { errorMessage } : {}),
},
providerRefs: {},
});
return;
}
@@ -3091,9 +3076,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
config: message as Record<string, unknown>,
},
});
// Session start is the one reliable moment a query handle exists, so
// it doubles as the account-limits refresh point (throttled inside).
yield* refreshAccountUsageSnapshot(context);
return;
case "status":
yield* offerRuntimeEvent({
@@ -3422,64 +3404,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
});
let lastAccountUsageFetchAtMs = 0;
/**
* Pulls the full rate-limit window set (5h, weekly, model-scoped) through
* the SDK usage control request and re-emits it as
* `account.rate-limits.updated`. The streamed `rate_limit_event` only ever
* names the single window currently binding, and Claude limits never reach
* disk, so this pull is the only source that shows every window at once.
*/
const emitAccountUsageSnapshot = Effect.fn("emitAccountUsageSnapshot")(function* (
context: ClaudeSessionContext,
) {
if (!context.query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET) return;
const now = yield* Clock.currentTimeMillis;
const elapsed = now - lastAccountUsageFetchAtMs;
// A negative elapsed means the wall clock stepped backwards; treat it as
// expired rather than freezing refreshes until the clock catches up.
if (elapsed >= 0 && elapsed < ACCOUNT_USAGE_MIN_INTERVAL_MS) return;
lastAccountUsageFetchAtMs = now;
const usage = yield* Effect.promise(async () => {
try {
// Called through the query object so the SDK method keeps its
// receiver; an extracted reference loses `this` and throws.
return await context.query.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET?.();
} catch {
return undefined;
}
});
if (!usage || usage.rate_limits === null || usage.rate_limits === undefined) return;
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
providerRefs: nativeProviderRefs(context),
type: "account.rate-limits.updated",
// Only the limit fields travel: the full response also carries session
// cost and a local behaviors scan that have no consumer here.
payload: {
rateLimits: {
subscription_type: usage.subscription_type,
rate_limits: usage.rate_limits,
},
},
});
});
/** Fire-and-forget wrapper: a slow claude.ai fetch must not stall the pump. */
const refreshAccountUsageSnapshot = (context: ClaudeSessionContext) =>
emitAccountUsageSnapshot(context).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach,
Effect.asVoid,
);
const handleSdkTelemetryMessage = Effect.fn("handleSdkTelemetryMessage")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
@@ -3586,10 +3510,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "auth_status":
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
if (message.type === "rate_limit_event") {
// The streamed event names one window; refresh the full set too.
yield* refreshAccountUsageSnapshot(context);
}
return;
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
@@ -4169,14 +4089,6 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...(ultracode ? { ultracode: true } : {}),
};
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
// The attachments dir grant lets the agent Read/copy pasted images at
// the paths ProviderService injects into the turn text, without an
// approval prompt. It is a leaf directory holding only attachment
// files; siblings like secrets/ and state.sqlite stay ungranted.
const additionalDirectories = [
...(input.cwd ? [input.cwd] : []),
serverConfig.attachmentsDir,
];
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(apiModelId ? { model: apiModelId } : {}),
@@ -4200,7 +4112,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
includePartialMessages: true,
canUseTool,
env: claudeEnvironment,
additionalDirectories,
...(input.cwd ? { additionalDirectories: [input.cwd] } : {}),
...(Object.keys(extraArgs).length > 0 ? { extraArgs } : {}),
...(mcpSession
? {
@@ -4235,7 +4147,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
"claude.query.resume": existingResumeSessionId ?? "",
"claude.query.session_id": newSessionId ?? "",
"claude.query.include_partial_messages": true,
"claude.query.additional_directories": additionalDirectories,
"claude.query.additional_directories": input.cwd ? [input.cwd] : [],
"claude.query.setting_sources": [...CLAUDE_SETTING_SOURCES],
"claude.query.settings_json": encodeJsonStringForDiagnostics(settings) ?? "",
"claude.query.extra_args_json": encodeJsonStringForDiagnostics(extraArgs) ?? "",
@@ -4507,40 +4419,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
yield* Effect.forEach(
liveIds,
(taskId) =>
Effect.gen(function* () {
const stopAcknowledged = yield* Effect.tryPromise({
// Invoke through the query object: SDK methods rely on `this`.
try: () => context.query.stopTask!(taskId),
catch: () => undefined,
}).pipe(
Effect.timeoutOption("3 seconds"),
Effect.orElseSucceed(() => Option.none()),
);
if (Option.isNone(stopAcknowledged) || !context.liveTaskIds.delete(taskId)) {
return;
}
// stopTask only acknowledges the control request. Its separate
// task_notification can lose the race with interrupt(), so make
// the acknowledged stop authoritative for the durable UI state.
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? { turnId: asCanonicalTurnId(context.turnState.turnId) }
: {}),
payload: {
taskId: RuntimeTaskId.make(taskId),
status: "stopped",
...taskLinkageFor(context.taskAgents, taskId),
},
providerRefs: nativeProviderRefs(context),
});
}).pipe(Effect.ignore),
Effect.tryPromise({
// Invoke through the query object: SDK methods rely on `this`.
try: () => context.query.stopTask!(taskId),
catch: () => undefined,
}).pipe(Effect.timeoutOption("3 seconds"), Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
}
@@ -34,6 +34,36 @@ const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
*/
function buildScript() {
const captured = wireFixture.notifications;
// Re-address the capture's schema-valid tool lifecycle pair to child A.
// Hand-written item shapes can drift from the generated Codex schema.
const childToolLifecycle = captured
.filter(
(entry) =>
(entry.method === "item/started" || entry.method === "item/completed") &&
(entry.params as { item?: { type?: string } }).item?.type === "collabAgentToolCall",
)
.map((entry) => {
const params = entry.params as {
readonly threadId: string;
readonly turnId: string;
readonly item: Record<string, unknown>;
};
return {
...entry,
params: {
...params,
threadId: CHILD_A,
turnId: `${CHILD_A}-turn-1`,
item: {
...params.item,
id: "call_fixture_child_tool",
senderThreadId: CHILD_A,
},
},
};
});
const childCompletionOnly = childToolLifecycle.find((entry) => entry.method === "item/completed");
assert.isDefined(childCompletionOnly);
const extras = [
{
method: "item/completed",
@@ -49,6 +79,19 @@ function buildScript() {
},
},
},
// Codex emits started + completed for one child item. They are one
// logical activity and must not become two synthetic agent updates.
...childToolLifecycle,
{
...childCompletionOnly,
params: {
...childCompletionOnly.params,
item: {
...childCompletionOnly.params.item,
id: "call_fixture_child_completion_only",
},
},
},
// Child terminal lifecycle AFTER the receiver map knows the children —
// pre-fix, the legacy suppressor dropped these before interception saw
// them, so no synthetic agent events were emitted.
@@ -123,6 +166,29 @@ describe("CodexSessionRuntime collab integration", () => {
);
assert.isDefined(childClosed, "child B's close becomes an agent event");
const childToolItems = events.filter(
(event) =>
event.method === "collabAgent/item" &&
(event.payload as { item?: { id?: string } }).item?.id === "call_fixture_child_tool",
);
assert.lengthOf(childToolItems, 1, "one child item must emit one agent activity");
assert.equal(childToolItems[0]?.itemId, "call_fixture_child_tool");
assert.equal(
(childToolItems[0]?.payload as { itemLifecycle?: string }).itemLifecycle,
"started",
);
const completionOnly = events.find(
(event) =>
event.method === "collabAgent/item" &&
(event.payload as { item?: { id?: string } }).item?.id ===
"call_fixture_child_completion_only",
);
assert.equal(
(completionOnly?.payload as { itemLifecycle?: string }).itemLifecycle,
"completed",
);
// Parent-owned resolution passes through — not swallowed, not
// re-labelled as an agent event.
assert.include(methods, "serverRequest/resolved");
@@ -245,53 +311,4 @@ describe("CodexSessionRuntime collab integration", () => {
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.live("Stop targets the active turn when Codex has accepted a queued follow-up", () =>
Effect.gen(function* () {
const activeTurnId = "019fe3e8-f908-7f31-8d51-283f4a47897a";
const queuedTurnId = "019fe3eb-8faf-7de3-a85b-ac64c7f9c8c3";
const script = {
rootThreadId: ROOT,
holdTurnOpen: true,
onlyFirstTurnStarts: true,
turnIds: [activeTurnId, queuedTurnId],
expectedActiveTurnId: activeTurnId,
notifications: [],
};
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
const interruptsPath = `${scriptPath}.interrupts`;
NodeFS.rmSync(interruptsPath, { force: true });
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
NodeFS.rmSync(scriptPath, { force: true });
NodeFS.rmSync(interruptsPath, { force: true });
}),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-codex-queued-stop"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
yield* runtime.start();
yield* runtime.sendTurn({ input: "keep working" });
yield* runtime.sendTurn({ input: "queued follow-up" });
yield* runtime.interruptTurn();
const interrupts = NodeFS.readFileSync(interruptsPath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as { threadId?: string; turnId?: string });
assert.deepEqual(interrupts.at(-1), {
threadId: ROOT,
turnId: activeTurnId,
});
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -814,13 +814,13 @@ function currentProviderThreadId(session: ProviderSession): string | undefined {
function updateSession(
sessionRef: Ref.Ref<ProviderSession>,
updates: Partial<ProviderSession> | ((session: ProviderSession) => Partial<ProviderSession>),
updates: Partial<ProviderSession>,
): Effect.Effect<void> {
return Effect.gen(function* () {
const updatedAt = DateTime.formatIso(yield* DateTime.now);
yield* Ref.update(sessionRef, (session) => ({
...session,
...(typeof updates === "function" ? updates(session) : updates),
...updates,
updatedAt,
}));
});
@@ -855,6 +855,8 @@ export const makeCodexSessionRuntime = (
const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());
/** Child provider-thread id → item ids already emitted during its lifetime. */
const collabChildSeenItemsRef = yield* Ref.make(new Map<string, ReadonlySet<string>>());
/** Child provider-thread id → its currently running provider turn id. */
const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());
const closedRef = yield* Ref.make(false);
@@ -1179,18 +1181,38 @@ export const makeCodexSessionRuntime = (
});
return true;
case "item/started":
case "item/completed":
case "item/completed": {
const item = notification.params.item;
const shouldEmit = yield* Ref.modify(collabChildSeenItemsRef, (current) => {
const seen = current.get(child.agentThreadId);
if (seen?.has(item.id) === true) {
return [false, current];
}
const next = new Map(current);
next.set(child.agentThreadId, new Set([...(seen ?? []), item.id]));
return [true, next];
});
// Codex emits both lifecycle notifications for the same child
// tool item. The adapter turns each synthetic event into agent
// activity, so only the first one is useful; completion-only
// items still pass through when no start was observed.
if (!shouldEmit) {
return true;
}
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
itemId: ProviderItemId.make(item.id),
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/item",
payload: {
...childIdentity,
item: notification.params.item,
itemLifecycle: notification.method === "item/started" ? "started" : "completed",
item,
},
});
return true;
}
case "thread/closed":
// The child is gone: drop its live-turn entry so a later Stop
// doesn't waste a turn/interrupt RPC on a closed thread before
@@ -1200,6 +1222,11 @@ export const makeCodexSessionRuntime = (
next.delete(child.agentThreadId);
return next;
});
yield* Ref.update(collabChildSeenItemsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
@@ -1782,14 +1809,11 @@ export const makeCodexSessionRuntime = (
),
);
const turnId = TurnId.make(response.turn.id);
yield* updateSession(sessionRef, (session) => ({
yield* updateSession(sessionRef, {
status: "running",
// Codex accepts follow-ups while the current turn is still
// running. The response contains the queued turn id, but
// turn/interrupt only accepts the id that is active now.
activeTurnId: session.activeTurnId ?? turnId,
activeTurnId: turnId,
...(normalizedModel ? { model: normalizedModel } : {}),
}));
});
const resumedProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
return {
threadId: options.threadId,
@@ -55,15 +55,11 @@ import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as AnalyticsService from "../../telemetry/AnalyticsService.ts";
import { makeAdapterRegistryMock } from "../testUtils/providerAdapterRegistryMock.ts";
const defaultServerSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
const serverConfigTestLayer = ServerConfig.layerTest(process.cwd(), process.cwd()).pipe(
Layer.provide(NodeServices.layer),
);
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
const asEventId = (value: string): EventId => EventId.make(value);
@@ -296,7 +292,6 @@ function makeProviderServiceLayer() {
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -348,7 +343,6 @@ it.effect("ProviderServiceLive catches stopAll failures during shutdown", () =>
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -408,7 +402,6 @@ it.effect("ProviderServiceLive rejects new sessions for disabled providers", ()
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -493,7 +486,6 @@ it.effect(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(serverSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -564,7 +556,6 @@ it.effect("ProviderServiceLive rejects new sessions for disabled custom instance
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -620,7 +611,6 @@ it.effect("ProviderServiceLive writes canonical events to the emitting thread se
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -681,7 +671,6 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
Layer.provide(Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -748,7 +737,6 @@ it.effect(
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -808,7 +796,6 @@ it.effect(
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -940,54 +927,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}),
);
it.effect("appends attachment file paths to the turn input text", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const session = yield* provider.startSession(asThreadId("thread-attach"), {
provider: ProviderDriverKind.make("codex"),
providerInstanceId: codexInstanceId,
threadId: asThreadId("thread-attach"),
cwd: "/tmp/project",
runtimeMode: "full-access",
});
const attachment = {
type: "image" as const,
id: "thread-attach-12345678-1234-1234-1234-123456789abc",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 123,
};
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: session.threadId,
input: "use this screenshot",
attachments: [attachment],
});
const turnInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
assert.equal(typeof turnInput.input, "string");
const turnText = turnInput.input ?? "";
assert.equal(turnText.startsWith("use this screenshot"), true);
assert.include(turnText, '[Attached image "screenshot.png" is saved at: ');
assert.equal(turnText.endsWith(`${attachment.id}.png]`), true);
// An attachment-only turn stays valid and the injected line becomes the
// whole input text, so the agent still learns the path.
routing.codex.sendTurn.mockClear();
yield* provider.sendTurn({
threadId: session.threadId,
attachments: [attachment],
});
const imageOnlyInput = routing.codex.sendTurn.mock.calls[0]?.[0] as ProviderSendTurnInput;
assert.equal(imageOnlyInput.input?.startsWith('[Attached image "screenshot.png"'), true);
yield* provider.stopSession({ threadId: session.threadId });
}),
);
it.effect("recovers stale persisted sessions for rollback by resuming thread identity", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
@@ -1368,7 +1307,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1407,7 +1345,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1476,7 +1413,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -1510,7 +1446,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(serverConfigTestLayer),
Layer.provide(AnalyticsService.layerTest),
Layer.provide(
Layer.succeed(
@@ -35,8 +35,6 @@ import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Stream from "effect/Stream";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import * as ServerConfig from "../../config.ts";
import {
increment,
providerMetricAttributes,
@@ -205,7 +203,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
options?: ProviderServiceLiveOptions,
) {
const analytics = yield* Effect.service(AnalyticsService.AnalyticsService);
const serverConfig = yield* ServerConfig.ServerConfig;
const eventLoggers = yield* ProviderEventLoggers.ProviderEventLoggers;
// Options-provided logger wins (test overrides); otherwise we take whatever
// the `ProviderEventLoggers` tag exposes — `undefined` means "no canonical
@@ -462,7 +459,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter,
instanceId,
threadId: input.threadId,
runtimeMode: binding.runtimeMode,
isActive: true,
} as const;
}
@@ -472,7 +468,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter,
instanceId,
threadId: input.threadId,
runtimeMode: binding.runtimeMode,
isActive: false,
} as const;
}
@@ -485,7 +480,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter: recovered.adapter,
instanceId,
threadId: input.threadId,
runtimeMode: recovered.session.runtimeMode,
isActive: true,
} as const;
});
@@ -635,19 +629,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
input.modelSelection.model.trim().length > 0,
});
// Changing runtime mode restarts the session, so the transition is only
// observable here, by diffing against the mode the previous session for
// this thread was bound to. Recording it separately is what makes the
// "started supervised, switched to full access" funnel answerable.
const previousRuntimeMode = persistedBinding?.runtimeMode;
if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {
yield* analytics.record("provider.runtime_mode.changed", {
provider: sessionWithInstance.provider,
from: previousRuntimeMode,
to: input.runtimeMode,
});
}
return sessionWithInstance;
}).pipe(
withMetrics({
@@ -668,44 +649,16 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
payload: rawInput,
});
const attachments = parsed.attachments ?? [];
if (!parsed.input && attachments.length === 0) {
const input = {
...parsed,
attachments: parsed.attachments ?? [],
};
if (!input.input && input.attachments.length === 0) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
);
}
// Adapters inline attachment pixels into the model prompt, but the model's
// tools cannot dereference pixels. Appending the on-disk path is what lets
// a turn like "include this screenshot in the PR" copy the actual file.
// This runs after schema decode, so the appended lines are exempt from the
// PROVIDER_SEND_TURN_MAX_INPUT_CHARS check; attachment count is capped, so
// the overhead is bounded. Unresolvable ids are skipped here and surface
// as adapter errors when the file is read for inlining.
const attachmentPathLines = attachments.flatMap((attachment) => {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
return attachmentPath === null
? []
: [`[Attached ${attachment.type} "${attachment.name}" is saved at: ${attachmentPath}]`];
});
const inputTextWithAttachmentPaths =
attachmentPathLines.length === 0
? parsed.input
: [parsed.input, attachmentPathLines.join("\n")]
.filter((part): part is string => typeof part === "string" && part.length > 0)
.join("\n\n");
const input = {
...parsed,
...(inputTextWithAttachmentPaths !== undefined
? { input: inputTextWithAttachmentPaths }
: {}),
attachments,
};
yield* Effect.annotateCurrentSpan({
"provider.operation": "send-turn",
"provider.thread_id": input.threadId,
@@ -750,10 +703,6 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
// Session-start events alone skew runtime mode toward users who toggle
// often, since every toggle restarts the session. Recording it per turn
// gives a usage-weighted view and lets it cross with interactionMode.
runtimeMode: routed.runtimeMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
Loaded 100 of 327 files, more files were not shown because too many files have changed in this diff. Show more