Compare commits
233
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
993407dd9e | ||
|
|
0c68291bc6 | ||
|
|
4442054fc7 | ||
|
|
4ef9640d2e | ||
|
|
0730577f7a | ||
|
|
05c236b2e9 | ||
|
|
70fc7b9e82 | ||
|
|
2d325c5a58 | ||
|
|
f875dff07d | ||
|
|
8fac43950a | ||
|
|
0e370e7521 | ||
|
|
c3c01cba3d | ||
|
|
4511210a45 | ||
|
|
893c04b94b | ||
|
|
3b08f94ccc | ||
|
|
44f7b15a35 | ||
|
|
0a2a1a775f | ||
|
|
a325fa337e | ||
|
|
f3d2958518 | ||
|
|
f096e0717b | ||
|
|
5d3740b01a | ||
|
|
733afbc6fa | ||
|
|
4ceb892265 | ||
|
|
aded5afa3f | ||
|
|
807072b7c1 | ||
|
|
4cd4e62417 | ||
|
|
e992d844b6 | ||
|
|
cc44d43b4b | ||
|
|
18a91d6822 | ||
|
|
b5cada5e89 | ||
|
|
3b903fc423 | ||
|
|
e538616255 | ||
|
|
8ada620ce8 | ||
|
|
482c46f6e2 | ||
|
|
5133fdbed5 | ||
|
|
a6216cf3dc | ||
|
|
7b1d62e39c | ||
|
|
2d379a19fa | ||
|
|
0285d41813 | ||
|
|
298d797e72 | ||
|
|
c2b4f965a3 | ||
|
|
22d79b30ff | ||
|
|
2a6f05fb43 | ||
|
|
89886c403b | ||
|
|
0dd6b54c8a | ||
|
|
28d429d047 | ||
|
|
d2d785cebf | ||
|
|
1e52051723 | ||
|
|
80b181c6a8 | ||
|
|
65f11099fe | ||
|
|
17a2932583 | ||
|
|
0e7452f059 | ||
|
|
08ab4239d5 | ||
|
|
ef433a39ec | ||
|
|
49375b88db | ||
|
|
fefd57fc54 | ||
|
|
3305785508 | ||
|
|
5e058ee234 | ||
|
|
ba05523ed2 | ||
|
|
dbf97e42bf | ||
|
|
f5d80b1d16 | ||
|
|
e77b08358d | ||
|
|
e4b59b169e | ||
|
|
6f459c12d0 | ||
|
|
808dd3d7e7 | ||
|
|
18c2458673 | ||
|
|
fff6e73842 | ||
|
|
729304a428 | ||
|
|
55ff7a676f | ||
|
|
af6060be1c | ||
|
|
7d185275db | ||
|
|
2c0125489a | ||
|
|
ef08c6fa53 | ||
|
|
9d089a5430 | ||
|
|
a151a77206 | ||
|
|
6750918ab1 | ||
|
|
b324a91812 | ||
|
|
c5f20fbc57 | ||
|
|
d9ea5b182c | ||
|
|
c2a1c56596 | ||
|
|
926be24e17 | ||
|
|
2e6f21179e | ||
|
|
c63da0a2cb | ||
|
|
fdf06c403a | ||
|
|
a40a1d8630 | ||
|
|
4c743ff634 | ||
|
|
997289b565 | ||
|
|
b115390123 | ||
|
|
d8a198a2c0 | ||
|
|
25abd50f8d | ||
|
|
38c7a868a1 | ||
|
|
a434c32e93 | ||
|
|
d8fd8c0edc | ||
|
|
76d35a2f3c | ||
|
|
ee78e27154 | ||
|
|
aece3cb2f3 | ||
|
|
63231d74c5 | ||
|
|
12737831e9 | ||
|
|
6d07a156d8 | ||
|
|
221d15181b | ||
|
|
b8a596f666 | ||
|
|
1827fb2959 | ||
|
|
6ef497fc24 | ||
|
|
50030b4e61 | ||
|
|
47beb7da4e | ||
|
|
97d935cfdd | ||
|
|
28e55c211d | ||
|
|
08b97fe6df | ||
|
|
e11eb373f6 | ||
|
|
4fc73fd290 | ||
|
|
661f21eb72 | ||
|
|
07ce295e8d | ||
|
|
cb3fc2a81a | ||
|
|
9b547f9e4f | ||
|
|
c9fff5904f | ||
|
|
3cbd672e13 | ||
|
|
144b309868 | ||
|
|
dee3de20fd | ||
|
|
d957b368d6 | ||
|
|
c7d47abd42 | ||
|
|
9e258c2b99 | ||
|
|
cd4ef48406 | ||
|
|
d6a607aceb | ||
|
|
c71c7b4331 | ||
|
|
411be44733 | ||
|
|
8d6e0490e1 | ||
|
|
78153d5ef3 | ||
|
|
2760da1395 | ||
|
|
7f74aa3594 | ||
|
|
c974f41b50 | ||
|
|
333d7ef8b7 | ||
|
|
0f78716903 | ||
|
|
496b8755e4 | ||
|
|
6e1b1334e9 | ||
|
|
9a7d3ec4ed | ||
|
|
bf8fa545bd | ||
|
|
e16d4e514b | ||
|
|
0282ab8608 | ||
|
|
fc1fb688d0 | ||
|
|
6d82418637 | ||
|
|
e59cf5d967 | ||
|
|
4a9421d53c | ||
|
|
e1d14b2895 | ||
|
|
40af3e26a8 | ||
|
|
1bd9e00990 | ||
|
|
76bdcd9548 | ||
|
|
e70df336e8 | ||
|
|
f182e5f605 | ||
|
|
4aeeddd20f | ||
|
|
8a192fdf44 | ||
|
|
fe79930e0b | ||
|
|
ee5098e75f | ||
|
|
f141e20ec3 | ||
|
|
ec5ac9564a | ||
|
|
20bea8ebdd | ||
|
|
2f75c8d119 | ||
|
|
a78a813910 | ||
|
|
cabab2bce8 | ||
|
|
aab3fdafe5 | ||
|
|
3104ecf322 | ||
|
|
f3d8017c76 | ||
|
|
0c2e9627f6 | ||
|
|
dfd6e9ec1d | ||
|
|
ed2ca16bcc | ||
|
|
2c5aa70cf3 | ||
|
|
928e72a23d | ||
|
|
25862ffc34 | ||
|
|
86941636d7 | ||
|
|
9b22fa56f2 | ||
|
|
af04d37c1c | ||
|
|
686be78b69 | ||
|
|
a39d2fda26 | ||
|
|
97736c47a5 | ||
|
|
c8aea5db0b | ||
|
|
4d64e80184 | ||
|
|
661dbc96d4 | ||
|
|
5073b0356d | ||
|
|
f456ee9630 | ||
|
|
1bbbaafb1e | ||
|
|
a2944d622a | ||
|
|
6ee48838d8 | ||
|
|
355ee8f130 | ||
|
|
f527603a6f | ||
|
|
a86fc05aa3 | ||
|
|
f19bb07de6 | ||
|
|
c61153b467 | ||
|
|
be6b66cd1b | ||
|
|
9355809b65 | ||
|
|
bb14bae94d | ||
|
|
fdcbae983d | ||
|
|
1f90765b5f | ||
|
|
a9fd14e824 | ||
|
|
ce64e37094 | ||
|
|
4fae73ee08 | ||
|
|
b493c4bd53 | ||
|
|
4b9f0e78cc | ||
|
|
b78320f249 | ||
|
|
5038b3a756 | ||
|
|
9a8eaf33d3 | ||
|
|
d3449cdf1d | ||
|
|
49a3ba50c1 | ||
|
|
fd3c09aa08 | ||
|
|
823bb8a4a0 | ||
|
|
1a681d2904 | ||
|
|
b0d0f71dbc | ||
|
|
b041b6256a | ||
|
|
e0790df1e9 | ||
|
|
bfa2c8773a | ||
|
|
732a25aad6 | ||
|
|
4b2542dd46 | ||
|
|
640460fae4 | ||
|
|
b8e9869b78 | ||
|
|
d80ca8e8ae | ||
|
|
5a789cb875 | ||
|
|
37dc60d3cf | ||
|
|
08813d1097 | ||
|
|
e8eb83a738 | ||
|
|
fa376a9e52 | ||
|
|
6df0bfbf2b | ||
|
|
99b24dfa2f | ||
|
|
4b6ae7be55 | ||
|
|
6b5e216667 | ||
|
|
96143bcb5f | ||
|
|
40f01b13d3 | ||
|
|
9beb0c049d | ||
|
|
76a4227729 | ||
|
|
cd35a10904 | ||
|
|
b113ff14b4 | ||
|
|
0c9ec3a664 | ||
|
|
90b3e90700 | ||
|
|
53ae164a1e | ||
|
|
c90c67e62a | ||
|
|
5740af634a |
No files matched your search
@@ -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);
|
||||
});
|
||||
@@ -70,6 +70,16 @@ jobs:
|
||||
!/.repos/
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
|
||||
# but ACP process-tree live tests compile a small pthread fixture with `cc`
|
||||
# and soft-skip when it is missing. Install build-essential so that path
|
||||
# always runs in CI instead of silently no-oping.
|
||||
- name: Install C toolchain for process-tree fixtures
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends build-essential
|
||||
command -v cc
|
||||
|
||||
- name: Setup Vite+
|
||||
uses: voidzero-dev/setup-vp@v1
|
||||
with:
|
||||
|
||||
@@ -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 });
|
||||
@@ -0,0 +1,246 @@
|
||||
# Plan: Thread Lineage And Lazy Context Transfer
|
||||
|
||||
## Summary
|
||||
|
||||
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
|
||||
|
||||
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
|
||||
|
||||
## Goals
|
||||
|
||||
- Support user-created fork threads for exploration.
|
||||
- Keep fork creation provider-neutral and cheap.
|
||||
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
|
||||
- Prefer native same-provider fork at first dispatch when available.
|
||||
- Fall back to portable context only when native transfer is unavailable or target provider differs.
|
||||
- Keep all behavior replayable through V2 events/projections.
|
||||
|
||||
## Non-Goals For First Slice
|
||||
|
||||
- Full portable context generation quality.
|
||||
- Cross-provider adapter implementation beyond the data/runtime hook.
|
||||
- Merge-back UI.
|
||||
- Native or custom subagent orchestration.
|
||||
- Forking from actively streaming provider state.
|
||||
- Backward compatibility with old dev databases.
|
||||
|
||||
## Core Data Model
|
||||
|
||||
Add schema/contracts for:
|
||||
|
||||
```ts
|
||||
type ContextTransferType =
|
||||
| "fork"
|
||||
| "provider_handoff"
|
||||
| "merge_back"
|
||||
| "subagent_spawn"
|
||||
| "subagent_result";
|
||||
|
||||
type ContextSourcePoint = {
|
||||
threadId: ThreadId;
|
||||
runId?: RunId;
|
||||
checkpointId?: CheckpointId;
|
||||
turnItemId?: TurnItemId;
|
||||
providerThreadRef?: NativeThreadRef;
|
||||
providerTurnRef?: NativeTurnRef;
|
||||
};
|
||||
|
||||
type ContextTransferStatus =
|
||||
| "pending"
|
||||
| "resolved_native"
|
||||
| "resolved_portable"
|
||||
| "failed"
|
||||
| "consumed"
|
||||
| "superseded";
|
||||
```
|
||||
|
||||
Persist:
|
||||
|
||||
- `orchestration_v2_projection_context_transfers`
|
||||
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
|
||||
|
||||
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
|
||||
|
||||
## Events
|
||||
|
||||
Add V2 events:
|
||||
|
||||
- `context-transfer.created`
|
||||
- `context-transfer.updated`
|
||||
- possibly `context-handoff.created` later
|
||||
|
||||
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
|
||||
|
||||
## Commands
|
||||
|
||||
Add:
|
||||
|
||||
```ts
|
||||
type ThreadForkCommand = {
|
||||
type: "thread.fork";
|
||||
commandId: CommandId;
|
||||
sourceThreadId: ThreadId;
|
||||
targetThreadId: ThreadId;
|
||||
sourcePoint:
|
||||
| { type: "latest_stable" }
|
||||
| { type: "run"; runId: RunId }
|
||||
| { type: "checkpoint"; checkpointId: CheckpointId };
|
||||
title?: string;
|
||||
createdAt: string;
|
||||
};
|
||||
```
|
||||
|
||||
First-slice policy:
|
||||
|
||||
- `latest_stable` resolves to latest completed run checkpoint.
|
||||
- explicit completed run/checkpoint is accepted.
|
||||
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
|
||||
- target thread starts idle.
|
||||
- no provider session/thread is created by `thread.fork`.
|
||||
|
||||
## Runtime Hook
|
||||
|
||||
Add a provider-neutral start-context resolver used by run startup:
|
||||
|
||||
```ts
|
||||
resolveStartContext({
|
||||
threadId,
|
||||
runId,
|
||||
provider,
|
||||
modelSelection,
|
||||
userMessage,
|
||||
}): Effect<StartContextResolution, StartContextResolutionError>
|
||||
```
|
||||
|
||||
Resolution order:
|
||||
|
||||
1. No pending transfer targeting the thread/run: normal run start.
|
||||
2. Pending fork transfer and same provider with native fork support: resolve native fork.
|
||||
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
|
||||
4. Failed resolution: fail command before provider side effects.
|
||||
|
||||
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
|
||||
|
||||
## Codex Native Fork Path
|
||||
|
||||
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
|
||||
|
||||
Implementation target:
|
||||
|
||||
- use native fork only when source provider is Codex and source native refs are strong;
|
||||
- create or bind a new `ProviderThread` for the forked native thread;
|
||||
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
|
||||
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
|
||||
- preserve source app thread lineage separately from native thread refs.
|
||||
|
||||
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
|
||||
|
||||
## Portable Context Fallback
|
||||
|
||||
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
|
||||
|
||||
Minimum viable fallback:
|
||||
|
||||
- detect cross-provider fork/handoff need;
|
||||
- create failed/unsupported transfer resolution with a clear command error, or
|
||||
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
|
||||
|
||||
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
|
||||
|
||||
## Merge-Back Preparation
|
||||
|
||||
Do not implement merge-back in the first slice, but keep model support:
|
||||
|
||||
- `ContextTransfer.type = "merge_back"`
|
||||
- `basePoint` on transfer
|
||||
- source thread may differ from target thread
|
||||
|
||||
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
|
||||
|
||||
## Subagent Preparation
|
||||
|
||||
Do not implement subagents in this slice, but keep model support:
|
||||
|
||||
- `createdBy: "agent"`
|
||||
- `type: "subagent_spawn"` and `"subagent_result"`
|
||||
- source/target thread relationship fields
|
||||
|
||||
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
|
||||
|
||||
## Projection And Debugger
|
||||
|
||||
Backend projection first:
|
||||
|
||||
- expose thread lineage in thread projection;
|
||||
- expose context transfers in debug projection;
|
||||
- expose transfer status and resolution strategy.
|
||||
|
||||
Debugger after backend:
|
||||
|
||||
- fork button/control from stable source point;
|
||||
- show thread lineage/source point;
|
||||
- show pending/resolved/failed transfers;
|
||||
- show native vs portable resolution.
|
||||
|
||||
Do not build debugger controls before the backend projection is authoritative.
|
||||
|
||||
## Tests
|
||||
|
||||
Use `bun run test`, not `bun test`.
|
||||
|
||||
Required backend tests:
|
||||
|
||||
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
|
||||
- fork command is idempotent through command receipts.
|
||||
- fork does not create provider session/thread eagerly.
|
||||
- first run on same-provider fork invokes native resolution path when capability exists.
|
||||
- unsupported native fork falls back or fails according to explicit policy.
|
||||
- active-run fork policy is deterministic.
|
||||
- replay/recovery preserves target thread lineage and pending transfer.
|
||||
|
||||
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
|
||||
|
||||
## Implementation Order
|
||||
|
||||
1. Add contract schemas and ids for context transfers/source points.
|
||||
2. Add migration/projection table for context transfers.
|
||||
3. Add event store/projection handling for transfer events.
|
||||
4. Add `thread.fork` command policy and orchestrator path.
|
||||
5. Add tests for cheap idle fork creation and recovery.
|
||||
6. Add start-context resolver interface.
|
||||
7. Wire resolver into run startup with no-op behavior.
|
||||
8. Add Codex native fork capability investigation and adapter path.
|
||||
9. Add tests for same-provider native fork resolution.
|
||||
10. Add debug projection surface after backend behavior is stable.
|
||||
|
||||
## Validation
|
||||
|
||||
Before considering the slice complete:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- targeted backend tests with `bun run test`
|
||||
|
||||
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
|
||||
|
||||
## Implementation Status
|
||||
|
||||
Implemented in this slice:
|
||||
|
||||
- context transfer ids, schemas, JSON codecs, events, and projection storage
|
||||
- app-thread lineage on thread creation and fork creation
|
||||
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
|
||||
- cheap idle fork creation with no eager provider session/thread/run
|
||||
- Codex same-provider native `thread/fork` resolution on first target dispatch
|
||||
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
|
||||
- transfer status progression through `pending`, `resolved_native`, and `consumed`
|
||||
- command receipt idempotency for duplicate fork commands
|
||||
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
|
||||
|
||||
Explicitly deferred:
|
||||
|
||||
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
|
||||
- merge-back command/runtime
|
||||
- subagent spawn/result runtime
|
||||
- debugger controls for creating/inspecting transfers
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,3 +12,4 @@
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
21. `21-orchestration-v2-application-integration.md`
|
||||
@@ -79,6 +79,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
|
||||
- [Permission modes](./docs/user/permission-modes.md)
|
||||
- [Keyboard shortcuts](./docs/user/keybindings.md)
|
||||
- [Customize a project icon](./docs/user/project-settings.md)
|
||||
- [Appearance preferences](./docs/user/appearance.md)
|
||||
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
|
||||
- [Keeping app and server in sync](./docs/user/updating.md)
|
||||
- [Source control integrations](./docs/user/source-control.md)
|
||||
|
||||
@@ -96,6 +96,8 @@ describe("DesktopEnvironment", () => {
|
||||
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
|
||||
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
|
||||
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
|
||||
assert.equal(environment.userDataDirName, "t3code");
|
||||
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.orElseSucceed(() => null),
|
||||
Effect.orElseSucceed((): string | null => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -31,6 +31,7 @@ const clientSettings: ClientSettings = {
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
persistComposerContextStrip: true,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarAutoSettleOnMerge: true,
|
||||
|
||||
@@ -218,7 +218,7 @@ const mobileEndorsementRows = [
|
||||
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
|
||||
<div class="harness-meta">
|
||||
<div class="harness-name">Cursor</div>
|
||||
<div class="harness-tag">cursor-agent</div>
|
||||
<div class="harness-tag">@cursor/sdk</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="harness">
|
||||
|
||||
@@ -3,14 +3,9 @@ import { Image } from "expo-image";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
const BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
const DEFAULT_STAGE_LABEL =
|
||||
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
|
||||
|
||||
@@ -22,7 +17,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
|
||||
return (
|
||||
<View className="flex-row items-center gap-3">
|
||||
<Image
|
||||
source={BRAND_MARK_SOURCE}
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: iconSize,
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import Constants from "expo-constants";
|
||||
|
||||
const appVariant = Constants.expoConfig?.extra?.appVariant;
|
||||
|
||||
export const T3_CODE_BRAND_MARK_SOURCE =
|
||||
appVariant === "development"
|
||||
? require("../../../../assets/dev/blueprint-ios-1024.png")
|
||||
: appVariant === "preview"
|
||||
? require("../../../../assets/nightly/nightly-ios-1024.png")
|
||||
: require("../../../../assets/prod/black-ios-1024.png");
|
||||
@@ -1,5 +1,16 @@
|
||||
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
|
||||
import { ORCHESTRATION_CACHE_SCHEMA_VERSION } from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
CommandId,
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ShellSnapshot,
|
||||
type OrchestrationV2ThreadDetailSnapshot,
|
||||
type VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
@@ -7,6 +18,124 @@ import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-data
|
||||
import { make } from "./environment-cache-store";
|
||||
|
||||
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
|
||||
const PROJECT_ID = ProjectId.make("project-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
|
||||
const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
|
||||
const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 3,
|
||||
projects: [
|
||||
{
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo",
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-29T12:00:00.000Z",
|
||||
updatedAt: "2026-07-29T12:00:00.000Z",
|
||||
},
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
providerInstanceId: PROVIDER_INSTANCE_ID,
|
||||
modelSelection: {
|
||||
instanceId: PROVIDER_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: THREAD_ID,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: NOW,
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
titleRegeneration: {
|
||||
requestId: CommandId.make("title-regeneration-1"),
|
||||
startedAt: NOW,
|
||||
},
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
archivedThreads: [],
|
||||
};
|
||||
const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
|
||||
snapshotSequence: 4,
|
||||
projection: {
|
||||
thread: {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Thread",
|
||||
providerInstanceId: PROVIDER_INSTANCE_ID,
|
||||
modelSelection: {
|
||||
instanceId: PROVIDER_INSTANCE_ID,
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: {
|
||||
rootThreadId: THREAD_ID,
|
||||
parentThreadId: null,
|
||||
relationshipToParent: null,
|
||||
},
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
createdAt: NOW,
|
||||
updatedAt: NOW,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
attempts: [],
|
||||
nodes: [],
|
||||
subagents: [],
|
||||
providerSessions: [],
|
||||
providerThreads: [],
|
||||
providerTurns: [],
|
||||
runtimeRequests: [],
|
||||
messages: [],
|
||||
plans: [],
|
||||
turnItems: [],
|
||||
checkpointScopes: [],
|
||||
checkpoints: [],
|
||||
contextHandoffs: [],
|
||||
contextTransfers: [],
|
||||
visibleTurnItems: [],
|
||||
updatedAt: NOW,
|
||||
},
|
||||
};
|
||||
const REFS: VcsListRefsResult = {
|
||||
refs: [
|
||||
{
|
||||
@@ -28,13 +157,16 @@ function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey:
|
||||
|
||||
function makeDatabase() {
|
||||
const values = new Map<string, string>();
|
||||
const schemaVersions = new Map<string, number>();
|
||||
const removed: Array<string> = [];
|
||||
const database = MobileDatabase.of({
|
||||
loadCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
|
||||
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
|
||||
saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
|
||||
Effect.sync(() => {
|
||||
values.set(cacheId(environmentId, kind, cacheKey), payload);
|
||||
const id = cacheId(environmentId, kind, cacheKey);
|
||||
values.set(id, payload);
|
||||
schemaVersions.set(id, schemaVersion);
|
||||
}),
|
||||
removeCache: (environmentId, kind, cacheKey) =>
|
||||
Effect.sync(() => {
|
||||
@@ -59,10 +191,40 @@ function makeDatabase() {
|
||||
loadPreferencesJson: Effect.succeed(Option.none()),
|
||||
savePreferencesJson: () => Effect.void,
|
||||
});
|
||||
return { database, removed, values };
|
||||
return { database, removed, schemaVersions, values };
|
||||
}
|
||||
|
||||
describe("mobile SQLite environment cache store", () => {
|
||||
it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
|
||||
|
||||
yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
|
||||
yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
|
||||
|
||||
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
|
||||
const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
|
||||
|
||||
expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
|
||||
expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
|
||||
"2026-07-29T12:00:00.000Z",
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips schema-validated VCS refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import {
|
||||
ConnectionPersistenceError,
|
||||
EnvironmentCacheStore,
|
||||
ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
StoredOrchestrationShellSnapshot,
|
||||
StoredOrchestrationThreadSnapshot,
|
||||
} from "@t3tools/client-runtime/platform";
|
||||
import {
|
||||
type EnvironmentId,
|
||||
OrchestrationShellSnapshot,
|
||||
OrchestrationThreadDetailSnapshot,
|
||||
ServerConfig,
|
||||
VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -16,25 +13,9 @@ import * as Schema from "effect/Schema";
|
||||
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
const StoredShellSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
snapshot: OrchestrationShellSnapshot,
|
||||
});
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
threadId: Schema.String,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
});
|
||||
const StoredServerConfig = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
|
||||
environmentId: Schema.String,
|
||||
@@ -48,13 +29,17 @@ const StoredVcsRefs = Schema.Struct({
|
||||
});
|
||||
|
||||
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredShellSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
|
||||
);
|
||||
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
|
||||
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredThreadSnapshot),
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(
|
||||
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
|
||||
);
|
||||
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
|
||||
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
|
||||
Schema.fromJsonString(StoredServerConfig),
|
||||
);
|
||||
@@ -130,12 +115,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
),
|
||||
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
|
||||
const payload = yield* encodeStoredShellSnapshot({
|
||||
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
|
||||
}),
|
||||
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
|
||||
@@ -153,15 +138,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
|
||||
}),
|
||||
),
|
||||
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
|
||||
const threadId = snapshot.thread.id;
|
||||
const threadId = snapshot.projection.thread.id;
|
||||
const payload = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
|
||||
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
|
||||
environmentId,
|
||||
threadId,
|
||||
snapshot,
|
||||
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
|
||||
yield* database
|
||||
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
|
||||
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
|
||||
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
|
||||
}),
|
||||
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Connection } from "@t3tools/client-runtime/connection";
|
||||
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
|
||||
import {
|
||||
boundedThreadSnapshotLoaderLayer,
|
||||
threadHistoryControllerLayer,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
@@ -15,7 +18,11 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
|
||||
Layer.provide(runtimeContextLayer),
|
||||
);
|
||||
|
||||
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
|
||||
const snapshotLoaderLayer = Layer.mergeAll(
|
||||
boundedThreadSnapshotLoaderLayer,
|
||||
shellSnapshotLoaderLayer,
|
||||
threadHistoryControllerLayer,
|
||||
);
|
||||
|
||||
type ConnectionLayerSource =
|
||||
| typeof Connection.layer
|
||||
|
||||
@@ -17,6 +17,7 @@ import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import * as CatalogStore from "./catalog-store";
|
||||
|
||||
function targetPersistenceError(
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
|
||||
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import { buildArchivedThreadGroups } from "./archivedThreadList";
|
||||
import { makeRawThreadShell } from "../../test-fixtures";
|
||||
|
||||
const environmentId = EnvironmentId.make("environment-1");
|
||||
|
||||
@@ -22,42 +24,30 @@ function makeProject(
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThreadShell> &
|
||||
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
|
||||
): OrchestrationThreadShell {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: "2026-06-02T00:00:00.000Z",
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
|
||||
readonly branch?: string | null;
|
||||
readonly archivedAt?: string | null;
|
||||
},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
|
||||
return makeRawThreadShell({
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
|
||||
});
|
||||
}
|
||||
|
||||
function makeSnapshot(
|
||||
projects: ReadonlyArray<OrchestrationProjectShell>,
|
||||
threads: ReadonlyArray<OrchestrationThreadShell>,
|
||||
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
|
||||
targetEnvironmentId = environmentId,
|
||||
): ArchivedSnapshotEntry {
|
||||
return {
|
||||
environmentId: targetEnvironmentId,
|
||||
snapshot: {
|
||||
schemaVersion: 1,
|
||||
snapshotSequence: 1,
|
||||
projects,
|
||||
threads,
|
||||
updatedAt: "2026-06-04T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,7 +190,7 @@ function deriveEmptyState(props: {
|
||||
|
||||
return {
|
||||
title: "No threads yet",
|
||||
detail: "Create a task to start a new coding session in one of your connected projects.",
|
||||
detail: "Create a task to start a new coding runtime in one of your connected projects.",
|
||||
loading: false,
|
||||
};
|
||||
}
|
||||
@@ -814,7 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
@@ -1101,7 +1101,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
detail="Choose another environment or create a new task."
|
||||
/>
|
||||
) : (
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
|
||||
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
|
||||
)
|
||||
) : null;
|
||||
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
@@ -32,29 +34,41 @@ function makeProject(id: string, title: string): EnvironmentProject {
|
||||
};
|
||||
}
|
||||
|
||||
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
|
||||
|
||||
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
id: ThreadId.make(id),
|
||||
const threadId = ThreadId.make(id);
|
||||
return presentThreadShell(environmentId, {
|
||||
id: threadId,
|
||||
projectId,
|
||||
title: `Thread ${id}`,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: threadTimestamp,
|
||||
updatedAt: threadTimestamp,
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
});
|
||||
}
|
||||
|
||||
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
buildHomeThreadGroups,
|
||||
sortHomeProjectScopes,
|
||||
} from "./homeThreadList";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
@@ -30,25 +31,21 @@ function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { ProviderInstanceId, RunId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
import { threadCanArchive } from "./threadArchive";
|
||||
|
||||
function runtime(
|
||||
status: ThreadRuntimeSummary["status"],
|
||||
activeRunId: ThreadRuntimeSummary["activeRunId"],
|
||||
): ThreadRuntimeSummary {
|
||||
return {
|
||||
status,
|
||||
activeRunId,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
providerName: "codex",
|
||||
lastError: null,
|
||||
updatedAt: "2026-07-28T10:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
describe("threadCanArchive", () => {
|
||||
it("blocks provider-active work", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false);
|
||||
expect(threadCanArchive(runtime("running", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("only allows queued work when no provider run remains active", () => {
|
||||
const activeRunId = RunId.make("run-live");
|
||||
expect(threadCanArchive(runtime("queued", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false);
|
||||
});
|
||||
|
||||
it("allows post-provider waiting work despite a retained active run id", () => {
|
||||
const staleActiveRunId = RunId.make("run-finished");
|
||||
expect(threadCanArchive(runtime("waiting", null))).toBe(true);
|
||||
expect(threadCanArchive(runtime("waiting", staleActiveRunId))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
|
||||
|
||||
/**
|
||||
* Archiving may discard queued work, but it must not detach a provider while
|
||||
* that provider is still executing a turn.
|
||||
*/
|
||||
export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
|
||||
if (runtime?.status === "queued") {
|
||||
return runtime.activeRunId === null;
|
||||
}
|
||||
return (
|
||||
runtime?.status !== "preparing" &&
|
||||
runtime?.status !== "starting" &&
|
||||
runtime?.status !== "running"
|
||||
);
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { threadCanArchive } from "./threadArchive";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
(capability defaults false on decode for older servers). */
|
||||
@@ -128,13 +129,9 @@ function useThreadActionExecutor(
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Archive keeps its original, narrower guard: never interrupt a
|
||||
// thread mid-turn.
|
||||
if (
|
||||
action === "archive" &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId != null
|
||||
) {
|
||||
// The server cancels queued runs on archive. Only an actual provider
|
||||
// turn still needs the user to interrupt it first.
|
||||
if (action === "archive" && !threadCanArchive(thread.runtime)) {
|
||||
Alert.alert(
|
||||
actionFailureTitle(action),
|
||||
"This thread is working. Interrupt it first, then try again.",
|
||||
|
||||
@@ -55,7 +55,10 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
|
||||
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
|
||||
const commandHandlers = handlers.get(command);
|
||||
if (!commandHandlers) return false;
|
||||
for (const handler of [...commandHandlers].toReversed()) {
|
||||
const handlersInRegistrationOrder = Array.from(commandHandlers);
|
||||
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
|
||||
const handler = handlersInRegistrationOrder[index];
|
||||
if (!handler) continue;
|
||||
if (handler() !== false) return true;
|
||||
}
|
||||
return false;
|
||||
|
||||
@@ -604,7 +604,6 @@ function useCreateProject(environment: EnvironmentOption | null) {
|
||||
commandId: CommandId.make(uuidv4()),
|
||||
projectId,
|
||||
workspaceRoot,
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
const result = await createProject({
|
||||
environmentId: environment.environmentId,
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
MessageId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type ReviewDiffPreviewSource,
|
||||
} from "@t3tools/contracts";
|
||||
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
|
||||
import {
|
||||
buildReviewListItems,
|
||||
@@ -18,9 +14,9 @@ import {
|
||||
} from "./reviewModel";
|
||||
|
||||
function makeCheckpoint(
|
||||
input: Partial<OrchestrationCheckpointSummary> &
|
||||
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
|
||||
): OrchestrationCheckpointSummary {
|
||||
input: Partial<ThreadCheckpointSummary> &
|
||||
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
|
||||
): ThreadCheckpointSummary {
|
||||
return {
|
||||
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
|
||||
status: "ready",
|
||||
@@ -52,12 +48,12 @@ describe("buildReviewSectionItems", () => {
|
||||
it("keeps one chip per checkpoint and appends git sources", () => {
|
||||
const checkpoints = [
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-1"),
|
||||
runId: RunId.make("run-1"),
|
||||
checkpointTurnCount: 1,
|
||||
completedAt: "2026-04-01T00:00:00.000Z",
|
||||
}),
|
||||
makeCheckpoint({
|
||||
turnId: TurnId.make("turn-2"),
|
||||
runId: RunId.make("run-2"),
|
||||
checkpointTurnCount: 2,
|
||||
completedAt: "2026-04-02T00:00:00.000Z",
|
||||
}),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
|
||||
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
|
||||
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
|
||||
import * as Arr from "effect/Array";
|
||||
import { pipe } from "effect/Function";
|
||||
import * as Order from "effect/Order";
|
||||
@@ -128,11 +129,11 @@ export type ReviewParsedDiff =
|
||||
readonly notice: string | null;
|
||||
};
|
||||
|
||||
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
return `Turn ${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
|
||||
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
|
||||
const fileCount = checkpoint.files.length;
|
||||
if (checkpoint.status !== "ready") {
|
||||
return `Diff ${checkpoint.status}`;
|
||||
@@ -141,8 +142,8 @@ function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string
|
||||
}
|
||||
|
||||
function compareCheckpointTurnCountDescending(
|
||||
left: OrchestrationCheckpointSummary,
|
||||
right: OrchestrationCheckpointSummary,
|
||||
left: ThreadCheckpointSummary,
|
||||
right: ThreadCheckpointSummary,
|
||||
): -1 | 0 | 1 {
|
||||
if (left.checkpointTurnCount === right.checkpointTurnCount) {
|
||||
return 0;
|
||||
@@ -151,7 +152,7 @@ function compareCheckpointTurnCountDescending(
|
||||
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
|
||||
}
|
||||
|
||||
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
|
||||
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
|
||||
compareCheckpointTurnCountDescending,
|
||||
);
|
||||
|
||||
@@ -510,14 +511,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
|
||||
}
|
||||
|
||||
export function getReviewSectionIdForCheckpoint(
|
||||
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
|
||||
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
|
||||
): string {
|
||||
return `turn:${checkpoint.checkpointTurnCount}`;
|
||||
}
|
||||
|
||||
export function getReadyReviewCheckpoints(
|
||||
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
|
||||
): ReadonlyArray<OrchestrationCheckpointSummary> {
|
||||
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
|
||||
): ReadonlyArray<ThreadCheckpointSummary> {
|
||||
return pipe(
|
||||
checkpoints,
|
||||
Arr.filter((checkpoint) => checkpoint.status === "ready"),
|
||||
@@ -526,7 +527,7 @@ export function getReadyReviewCheckpoints(
|
||||
}
|
||||
|
||||
export function buildReviewSectionItems(input: {
|
||||
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
|
||||
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
|
||||
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
|
||||
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
|
||||
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
deriveThreadCheckpointSummaries,
|
||||
type ThreadCheckpointSummary,
|
||||
} from "@t3tools/client-runtime/state/thread-checkpoints";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { useCheckpointDiff } from "../../state/queries";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
import { reviewEnvironment } from "../../state/review";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
|
||||
import {
|
||||
buildReviewSectionItems,
|
||||
@@ -30,7 +34,7 @@ export function useReviewSections(input: {
|
||||
}) {
|
||||
const { environmentId, reviewCache, threadId } = input;
|
||||
const enabled = input.enabled ?? true;
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const diffPreview = useEnvironmentQuery(
|
||||
enabled && environmentId !== undefined && selectedThreadCwd !== null
|
||||
@@ -49,8 +53,11 @@ export function useReviewSections(input: {
|
||||
}, [diffPreview.data, reviewCache.threadKey]);
|
||||
|
||||
const readyCheckpoints = useMemo(
|
||||
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
|
||||
[selectedThread?.checkpoints],
|
||||
() =>
|
||||
getReadyReviewCheckpoints(
|
||||
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
|
||||
),
|
||||
[selectedThread],
|
||||
);
|
||||
const checkpointBySectionId = useMemo(
|
||||
() =>
|
||||
@@ -59,7 +66,7 @@ export function useReviewSections(input: {
|
||||
getReviewSectionIdForCheckpoint(checkpoint),
|
||||
checkpoint,
|
||||
]),
|
||||
) as Record<string, OrchestrationCheckpointSummary>,
|
||||
) as Record<string, ThreadCheckpointSummary>,
|
||||
[readyCheckpoints],
|
||||
);
|
||||
const reviewSections = useMemo(
|
||||
|
||||
@@ -40,7 +40,7 @@ import {
|
||||
useKnownTerminalSessions,
|
||||
} from "../../state/use-terminal-session";
|
||||
import { useThreadSelection } from "../../state/use-thread-selection";
|
||||
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
|
||||
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { TerminalSurface } from "./NativeTerminalSurface";
|
||||
@@ -172,7 +172,9 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
const params = props.route.params;
|
||||
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
|
||||
useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const selectedThreadDetailWorktreePath =
|
||||
selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
|
||||
const routeThreadIdRaw = firstRouteParam(params.threadId);
|
||||
const routeEnvironmentId = routeEnvironmentIdRaw
|
||||
@@ -283,13 +285,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
|
||||
activeSessionLocation: activeKnownSession?.state.summary ?? null,
|
||||
workspaceRoot: selectedThreadProject.workspaceRoot,
|
||||
threadShellWorktreePath: selectedThread.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
|
||||
});
|
||||
}, [
|
||||
activeKnownSession?.state.summary,
|
||||
pendingLaunch,
|
||||
selectedThread,
|
||||
selectedThreadDetail?.worktreePath,
|
||||
selectedThreadDetailWorktreePath,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
isAtomCommandInterrupted,
|
||||
squashAtomCommandFailure,
|
||||
} from "@t3tools/client-runtime/state/runtime";
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
|
||||
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import {
|
||||
@@ -50,7 +51,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";
|
||||
@@ -717,7 +718,10 @@ export function NewTaskDraftScreen(props: {
|
||||
// finds no work and ends the card within seconds.
|
||||
armAgentAwarenessLiveActivityForLocalWork({
|
||||
environmentId: selectedProject.environmentId,
|
||||
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
|
||||
threadTitle: deriveThreadTitleSeed({
|
||||
text: initialMessageText,
|
||||
attachments: draft.attachments,
|
||||
}),
|
||||
projectTitle: selectedProject.title,
|
||||
});
|
||||
const creationBranch = resolveProjectThreadCreationBranch({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
@@ -6,9 +6,9 @@ import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export interface PendingApprovalCardProps {
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
|
||||
// behind this card, so a translucent surface bleeds messages through it.
|
||||
const canRespond = props.approval.responseCapability === "live";
|
||||
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
@@ -29,17 +31,23 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
{props.approval.detail}
|
||||
</Text>
|
||||
) : null}
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the run
|
||||
to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
@@ -48,7 +56,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
</Pressable>
|
||||
<Pressable
|
||||
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
|
||||
disabled={props.respondingApprovalId === props.approval.requestId}
|
||||
disabled={disabled}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
|
||||
import type { RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
|
||||
import { useCallback, useRef } from "react";
|
||||
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
|
||||
import Animated, {
|
||||
@@ -55,14 +56,14 @@ export interface PendingUserInputCardProps {
|
||||
readonly onInputFocusChange?: (focused: boolean) => void;
|
||||
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly onSelectOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
requestId: RuntimeRequestId,
|
||||
question: ThreadUserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -89,6 +90,9 @@ const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
const questionCount = props.pendingUserInput.questions.length;
|
||||
// V2 runtime requests carry response capability: a dead provider process
|
||||
// cannot accept answers, so the card reads-only until the run restarts.
|
||||
const canRespond = props.pendingUserInput.responseCapability === "live";
|
||||
|
||||
const cardCoverage = props.cardCoverage;
|
||||
const barHeightRef = useRef(0);
|
||||
@@ -247,6 +251,12 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
showsVerticalScrollIndicator
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{!canRespond ? (
|
||||
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
|
||||
The provider process for this request is no longer available. Interrupt or restart the
|
||||
run to continue.
|
||||
</Text>
|
||||
) : null}
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
@@ -263,6 +273,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
disabled={!canRespond}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
@@ -292,6 +303,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
editable={canRespond}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
@@ -311,7 +323,9 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
!canRespond ||
|
||||
props.answers === null ||
|
||||
props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
export function ThreadActivityInspector(props: {
|
||||
readonly activity: ThreadFeedActivity;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: ColorValue;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const navigation = useNavigation();
|
||||
const row = props.activity.projectedItem;
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
});
|
||||
const model = useMemo(
|
||||
() => buildThreadActivityInspector(props.activity, support, props.currentThreadId),
|
||||
[props.activity, props.currentThreadId, support],
|
||||
);
|
||||
const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
|
||||
label: "checkpoint rollback",
|
||||
reportFailure: true,
|
||||
});
|
||||
const [rollingBack, setRollingBack] = useState(false);
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<View className="flex-row flex-wrap gap-x-4 gap-y-2 rounded-lg border border-neutral-300/50 bg-black/[0.025] p-2.5 dark:border-white/[0.1] dark:bg-white/[0.025]">
|
||||
{model.fields.map((field) => (
|
||||
<View key={`${field.label}:${field.value}`} className="min-w-[42%] flex-1 gap-0.5">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{field.label}
|
||||
</Text>
|
||||
<Text selectable className="text-2xs leading-4 text-foreground">
|
||||
{field.value}
|
||||
</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
|
||||
{model.blocks.map((block) => (
|
||||
<View key={`${block.label}:${block.value}`} className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
{block.label}
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 240 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
|
||||
>
|
||||
{block.value}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
))}
|
||||
|
||||
{model.fileLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Files
|
||||
</Text>
|
||||
{model.fileLinks.map((link) => {
|
||||
const relativePath =
|
||||
resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
|
||||
(link.path.startsWith("/") ? null : link.path);
|
||||
return (
|
||||
<Pressable
|
||||
key={`${link.path}:${link.line ?? 0}:${link.label}`}
|
||||
accessibilityRole={relativePath ? "link" : undefined}
|
||||
disabled={relativePath === null}
|
||||
onPress={() => {
|
||||
if (!relativePath) return;
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate(
|
||||
"ThreadFile",
|
||||
buildThreadActivityFileParams({
|
||||
environmentId: props.environmentId,
|
||||
currentThreadId: props.currentThreadId,
|
||||
activitySourceThreadId: row.sourceThreadId,
|
||||
relativePath,
|
||||
line: link.line,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="doc.text"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.webLinks.length > 0 ? (
|
||||
<View className="gap-1">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Sources
|
||||
</Text>
|
||||
{model.webLinks.map((link) => (
|
||||
<Pressable
|
||||
key={link.url}
|
||||
accessibilityRole="link"
|
||||
onPress={() => void Linking.openURL(link.url)}
|
||||
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.up.right.square"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
|
||||
{link.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{model.rollbackTarget ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Roll back to this checkpoint"
|
||||
disabled={rollingBack}
|
||||
onPress={() => {
|
||||
setRollingBack(true);
|
||||
void Haptics.selectionAsync();
|
||||
void revertCheckpoint({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
threadId: model.rollbackTarget!.threadId,
|
||||
checkpointId: model.rollbackTarget!.checkpointId,
|
||||
scopeId: model.rollbackTarget!.scopeId,
|
||||
},
|
||||
}).finally(() => setRollingBack(false));
|
||||
}}
|
||||
className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]"
|
||||
>
|
||||
<SymbolView
|
||||
name={rollingBack ? "hourglass" : "arrow.counterclockwise"}
|
||||
size={14}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-xs text-foreground">
|
||||
{rollingBack ? "Rolling back…" : "Roll back to checkpoint"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
|
||||
<View className="gap-1 border-t border-neutral-300/50 pt-2 dark:border-white/[0.1]">
|
||||
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
|
||||
Structured details
|
||||
</Text>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
style={{ maxHeight: 280 }}
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="text-2xs leading-[17px] text-foreground-muted"
|
||||
style={{ fontFamily: "ui-monospace" }}
|
||||
>
|
||||
{model.structuredDetails}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ServerConfig as T3ServerConfig,
|
||||
@@ -102,9 +103,11 @@ export interface ThreadComposerProps {
|
||||
* are on screen while they reconcile with the server.
|
||||
*/
|
||||
readonly threadSyncPhase?: "loading" | "syncing" | null;
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly serverConfig: T3ServerConfig | null;
|
||||
readonly queueCount: number;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectCwd: string | null;
|
||||
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
|
||||
@@ -321,9 +324,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
setIsFocused(false);
|
||||
onEditorFocusChange?.(false);
|
||||
}, [onEditorFocusChange]);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
const showStopAction = props.canStopThread;
|
||||
|
||||
const sendLabel =
|
||||
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
|
||||
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
|
||||
import type { LegendListRef } from "@legendapp/list/react-native";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import type {
|
||||
ApprovalRequestId,
|
||||
EnvironmentId,
|
||||
MessageId,
|
||||
ModelSelection,
|
||||
OrchestrationThreadShell,
|
||||
ProviderApprovalDecision,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
RuntimeRequestId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
ThreadId,
|
||||
UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import {
|
||||
memo,
|
||||
@@ -57,13 +57,15 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
PendingUserInputDraftAnswer,
|
||||
ThreadFeedEntry,
|
||||
ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import { PendingApprovalCard } from "./PendingApprovalCard";
|
||||
import { PendingUserInputCard } from "./PendingUserInputCard";
|
||||
@@ -77,30 +79,35 @@ import {
|
||||
COMPOSER_EXPANDED_CHROME,
|
||||
ThreadComposer,
|
||||
} from "./ThreadComposer";
|
||||
import { ThreadFeed } from "./ThreadFeed";
|
||||
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
|
||||
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
|
||||
import { ThreadQueueControl } from "./ThreadQueueControl";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
|
||||
export interface ThreadDetailScreenProps {
|
||||
readonly selectedThread: OrchestrationThreadShell;
|
||||
readonly selectedThread: EnvironmentThreadShell;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly screenTone: StatusTone;
|
||||
readonly connectionError: string | null;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activityRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly respondingApprovalId: RuntimeRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
|
||||
readonly respondingUserInputId: ApprovalRequestId | null;
|
||||
readonly respondingUserInputId: RuntimeRequestId | null;
|
||||
readonly draftMessage: string;
|
||||
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
/** Progressive history controls for oversized mobile thread opens. */
|
||||
readonly historyControls?: ThreadFeedHistoryControls;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly canStopThread: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
readonly threadCwd: string | null;
|
||||
@@ -121,16 +128,16 @@ export interface ThreadDetailScreenProps {
|
||||
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
|
||||
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
|
||||
readonly onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<unknown>;
|
||||
readonly onSelectUserInputOption: (
|
||||
requestId: ApprovalRequestId,
|
||||
question: UserInputQuestion,
|
||||
requestId: RuntimeRequestId,
|
||||
question: ThreadUserInputQuestion,
|
||||
label: string,
|
||||
) => void;
|
||||
readonly onChangeUserInputCustomAnswer: (
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
questionId: string,
|
||||
customAnswer: string,
|
||||
) => void;
|
||||
@@ -249,7 +256,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
}
|
||||
}, []);
|
||||
const windowHeight = useWindowDimensions().height;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
|
||||
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
|
||||
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
|
||||
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
|
||||
const composerEditorRef = useRef<ComposerEditorHandle>(null);
|
||||
@@ -298,7 +305,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
// keyboard animations coherent. Collapse state is keyed by request id so a
|
||||
// new request re-expands automatically.
|
||||
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
|
||||
useState<ApprovalRequestId | null>(null);
|
||||
useState<RuntimeRequestId | null>(null);
|
||||
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
|
||||
const userInputCollapsed =
|
||||
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
|
||||
@@ -456,6 +463,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
const lastDispatchedVisitRef = useRef<string | null>(null);
|
||||
const selectedThreadId = props.selectedThread.id;
|
||||
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
|
||||
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
|
||||
useEffect(() => {
|
||||
// Records the server-side visited watermark while the thread is on
|
||||
// screen (mirror of web ChatView), so the "Done" marker clears on every
|
||||
// device. Field absent → the server predates visited tracking.
|
||||
if (selectedThreadLastVisitedAt === undefined) return;
|
||||
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
|
||||
if (Number.isNaN(threadUpdatedAtMs)) return;
|
||||
const lastVisitedAtMs = selectedThreadLastVisitedAt
|
||||
? Date.parse(selectedThreadLastVisitedAt)
|
||||
: NaN;
|
||||
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
|
||||
// Dedupe per watermark — the effect re-runs before the command echo lands.
|
||||
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
|
||||
if (lastDispatchedVisitRef.current === dispatchKey) return;
|
||||
lastDispatchedVisitRef.current = dispatchKey;
|
||||
void visitThread({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
|
||||
});
|
||||
}, [
|
||||
props.environmentId,
|
||||
selectedThreadId,
|
||||
selectedThreadKey,
|
||||
selectedThreadLastVisitedAt,
|
||||
selectedThreadUpdatedAt,
|
||||
visitThread,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
@@ -589,7 +629,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
feed={props.selectedThreadFeed}
|
||||
contentPresentation={props.contentPresentation}
|
||||
agentLabel={agentLabel}
|
||||
latestTurn={props.selectedThread.latestTurn}
|
||||
threadTitle={props.selectedThread.title}
|
||||
latestRun={props.activityRun}
|
||||
activeWorkStartedAt={props.activeWorkStartedAt}
|
||||
listRef={listRef}
|
||||
freeze={freeze}
|
||||
@@ -598,12 +639,18 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
contentTopInset={0}
|
||||
contentBottomInset={estimatedOverlayHeight}
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
historyControls={props.historyControls}
|
||||
topAccessory={
|
||||
<ThreadRelationshipsBanner
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
/>
|
||||
}
|
||||
layoutVariant={layoutVariant}
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
onEndFollowEnabledChange={setEndFollowEnabled}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
@@ -668,6 +715,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
<ThreadQueueControl
|
||||
environmentId={props.environmentId}
|
||||
threadId={props.selectedThread.id}
|
||||
/>
|
||||
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -726,6 +778,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
canStopThread={props.canStopThread}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import {
|
||||
ThreadId,
|
||||
type EnvironmentId,
|
||||
type MessageId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type RunId,
|
||||
} from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
@@ -27,6 +35,7 @@ import {
|
||||
} from "react-native-nitro-markdown";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Image,
|
||||
Platform,
|
||||
type LayoutChangeEvent,
|
||||
@@ -75,6 +84,7 @@ import {
|
||||
import { buildReviewParsedDiff } from "../review/reviewModel";
|
||||
import { cn } from "../../lib/cn";
|
||||
import { deriveCenteredContentHorizontalPadding, type LayoutVariant } from "../../lib/layout";
|
||||
import { uuidv4 } from "../../lib/uuid";
|
||||
import {
|
||||
resolveMarkdownFontSizes,
|
||||
resolveNativeMarkdownTypography,
|
||||
@@ -87,8 +97,9 @@ import { markdownFileIconSource } from "@t3tools/mobile-markdown-text/file-icons
|
||||
import { resolveMarkdownLinkPresentation } from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
type ThreadFeedLatestRun,
|
||||
} from "../../lib/threadActivity";
|
||||
import type { ThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
@@ -103,7 +114,13 @@ import {
|
||||
} from "./thread-work-log";
|
||||
import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
|
||||
import { useAssetUrl } from "../../state/assets";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
|
||||
import { waitForThreadShellReady } from "./threadForkNavigation";
|
||||
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
|
||||
|
||||
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
|
||||
includeOrderedLists: Platform.OS === "android",
|
||||
@@ -140,14 +157,22 @@ function isFreshTimestamp(input: string): boolean {
|
||||
return Number.isFinite(timestamp) && Date.now() - timestamp < FRESH_ENTRY_WINDOW_MS;
|
||||
}
|
||||
|
||||
export interface ThreadFeedHistoryControls {
|
||||
readonly hasMoreHistory: boolean;
|
||||
readonly loading: boolean;
|
||||
readonly error: string | null;
|
||||
readonly onLoadEarlier: () => void;
|
||||
}
|
||||
|
||||
export interface ThreadFeedProps {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly threadTitle: string;
|
||||
readonly workspaceRoot?: string | null;
|
||||
readonly feed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly latestRun: ThreadFeedLatestRun | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
@@ -155,17 +180,98 @@ export interface ThreadFeedProps {
|
||||
readonly contentInsetEndAdjustment: SharedValue<number>;
|
||||
readonly contentTopInset?: number;
|
||||
readonly contentBottomInset?: number;
|
||||
readonly historyControls?: ThreadFeedHistoryControls;
|
||||
readonly topAccessory?: ReactNode;
|
||||
readonly contentMaxWidth?: number;
|
||||
readonly layoutVariant?: LayoutVariant;
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
readonly loading: boolean;
|
||||
readonly onLoadEarlier: () => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
async function waitForThreadShell(
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
): Promise<boolean> {
|
||||
const atom = environmentThreadShells.threadShellAtom(scopeThreadRef(environmentId, threadId));
|
||||
return waitForThreadShellReady({
|
||||
read: () => appAtomRegistry.get(atom) !== null,
|
||||
});
|
||||
}
|
||||
|
||||
function AssistantForkButton(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: ColorValue;
|
||||
readonly projectedItem: OrchestrationV2ProjectedTurnItem;
|
||||
readonly sourceTitle: string;
|
||||
}) {
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: props.projectedItem.sourceThreadId,
|
||||
sourceItemId: props.projectedItem.sourceItemId,
|
||||
});
|
||||
const forkFromRun = useAtomCommand(threadEnvironment.forkFromRun, "fork from response");
|
||||
const navigation = useNavigation();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const canFork = canForkProjectedAssistantItem({
|
||||
projectedItem: props.projectedItem,
|
||||
capabilities: support.providerSession?.capabilities,
|
||||
});
|
||||
const runId = props.projectedItem.item.runId;
|
||||
|
||||
if (!canFork || runId === null) return null;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Fork from this response"
|
||||
disabled={busy}
|
||||
onPress={() => {
|
||||
const targetThreadId = ThreadId.make(uuidv4());
|
||||
setBusy(true);
|
||||
void Haptics.selectionAsync();
|
||||
void forkFromRun({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
sourceThreadId: props.projectedItem.sourceThreadId,
|
||||
targetThreadId,
|
||||
runId,
|
||||
title: `${props.sourceTitle} fork`,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
})
|
||||
.then(async (result) => {
|
||||
if (result._tag !== "Success") return;
|
||||
const targetThreadReady = await waitForThreadShell(props.environmentId, targetThreadId);
|
||||
if (!targetThreadReady) {
|
||||
Alert.alert(
|
||||
"Fork created",
|
||||
"Its thread data did not reach this client. Reconnect and try opening it from the thread list.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: targetThreadId,
|
||||
});
|
||||
})
|
||||
.finally(() => setBusy(false));
|
||||
}}
|
||||
className="h-7 w-7 items-center justify-center disabled:opacity-40"
|
||||
>
|
||||
{busy ? (
|
||||
<ActivityIndicator size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={13}
|
||||
tintColor={props.iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -821,15 +927,16 @@ function useMarkdownStyles(onLinkPress: (href: string) => void): MarkdownStyleSe
|
||||
|
||||
function renderFeedEntry(
|
||||
info: { item: ThreadFeedEntry; index: number },
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills"> & {
|
||||
props: Pick<ThreadFeedProps, "environmentId" | "skills" | "threadId" | "workspaceRoot"> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly unsettledTurnId: RunId | null;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleWorkRow: (rowId: string, anchorKey?: string) => void;
|
||||
readonly onToggleTurnFold: (runId: RunId) => void;
|
||||
readonly onPressImage: (uri: string, headers?: Record<string, string>) => void;
|
||||
readonly onMarkdownLinkPress: (href: string) => void;
|
||||
readonly iconSubtleColor: string | import("react-native").ColorValue;
|
||||
@@ -838,6 +945,7 @@ function renderFeedEntry(
|
||||
readonly reviewCommentColors: ReviewCommentColors;
|
||||
readonly reviewCommentBubbleWidth: number;
|
||||
readonly userBubbleMaxWidth: number;
|
||||
readonly threadTitle: string;
|
||||
},
|
||||
) {
|
||||
const entry = info.item;
|
||||
@@ -847,12 +955,12 @@ function renderFeedEntry(
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
if (entry.type === "run-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: entry.expanded }}
|
||||
onPress={() => props.onToggleTurnFold(entry.turnId)}
|
||||
onPress={() => props.onToggleTurnFold(entry.runId)}
|
||||
hitSlop={4}
|
||||
className="mb-3 min-h-11 flex-row items-center gap-2 border-b border-neutral-200/80 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
@@ -897,7 +1005,7 @@ function renderFeedEntry(
|
||||
const assistantTurnStillInProgress =
|
||||
message.role === "assistant" &&
|
||||
props.unsettledTurnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
message.runId === props.unsettledTurnId;
|
||||
const showAssistantMeta =
|
||||
message.role === "assistant" &&
|
||||
props.terminalAssistantMessageIds.has(message.id) &&
|
||||
@@ -906,11 +1014,17 @@ function renderFeedEntry(
|
||||
|
||||
if (isUser) {
|
||||
const enterAnimated = isFreshTimestamp(message.createdAt);
|
||||
const intentBadge = resolveUserMessageIntentBadge(message.inputIntent);
|
||||
return (
|
||||
<Animated.View
|
||||
className="mb-5 items-end"
|
||||
{...(enterAnimated ? { entering: FadeInUp.duration(220) } : {})}
|
||||
>
|
||||
{message.createdBy === "agent" ? (
|
||||
<Text className="mb-1 pr-1 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
Sent by another agent
|
||||
</Text>
|
||||
) : null}
|
||||
<View
|
||||
className="min-w-0 gap-2 rounded-[20px] px-3.5 py-2.5"
|
||||
style={{
|
||||
@@ -945,6 +1059,30 @@ function renderFeedEntry(
|
||||
})}
|
||||
</View>
|
||||
<View className="mt-1 flex-row items-center justify-end gap-1 pr-0.5">
|
||||
{intentBadge ? (
|
||||
<View
|
||||
accessible
|
||||
accessibilityRole="text"
|
||||
accessibilityLabel={intentBadge.accessibilityLabel}
|
||||
className={cn(
|
||||
"rounded-full border px-1.5 py-0.5",
|
||||
intentBadge.tone === "queued"
|
||||
? "border-amber-500/25 bg-amber-500/10 dark:border-amber-400/25 dark:bg-amber-400/10"
|
||||
: "border-sky-500/25 bg-sky-500/10 dark:border-sky-400/25 dark:bg-sky-400/10",
|
||||
)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-2xs tracking-wide",
|
||||
intentBadge.tone === "queued"
|
||||
? "text-amber-700 dark:text-amber-300"
|
||||
: "text-sky-700 dark:text-sky-300",
|
||||
)}
|
||||
>
|
||||
{intentBadge.label}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
{timestampLabel}
|
||||
</Text>
|
||||
@@ -1006,6 +1144,12 @@ function renderFeedEntry(
|
||||
})}
|
||||
{showAssistantMeta ? (
|
||||
<View className="mt-1 flex-row items-center gap-1">
|
||||
<AssistantForkButton
|
||||
environmentId={props.environmentId}
|
||||
iconColor={iconSubtleColor}
|
||||
projectedItem={message.projectedItem}
|
||||
sourceTitle={props.threadTitle}
|
||||
/>
|
||||
<CopyTextButton
|
||||
accessibilityLabel="Copy message"
|
||||
text={message.text}
|
||||
@@ -1026,10 +1170,15 @@ function renderFeedEntry(
|
||||
<ThreadWorkLog
|
||||
activities={entry.activities}
|
||||
copiedRowId={props.copiedRowId}
|
||||
currentThreadId={props.threadId}
|
||||
environmentId={props.environmentId}
|
||||
expanded={props.expandedWorkGroups[entry.id] ?? false}
|
||||
expandedRows={props.expandedWorkRows}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
onCopyRow={props.onCopyWorkRow}
|
||||
onToggleRow={props.onToggleWorkRow}
|
||||
onToggleGroup={() => props.onToggleWorkGroup(entry.id)}
|
||||
onToggleRow={(rowId) => props.onToggleWorkRow(rowId, entry.id)}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1298,6 +1447,41 @@ function compactFileName(filePath: string): string {
|
||||
return lastSlashIndex >= 0 ? normalized.slice(lastSlashIndex + 1) : normalized;
|
||||
}
|
||||
|
||||
function ThreadFeedLoadEarlierControl(props: ThreadFeedHistoryControls) {
|
||||
const mutedColor = useThemeColor("--color-icon-subtle");
|
||||
const accentColor = useThemeColor("--color-primary");
|
||||
if (!props.hasMoreHistory && props.error === null) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<View className="mb-3 items-center gap-1.5 px-2">
|
||||
{props.hasMoreHistory ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Load earlier activity"
|
||||
disabled={props.loading}
|
||||
onPress={props.onLoadEarlier}
|
||||
className="min-h-9 flex-row items-center justify-center gap-2 rounded-full border border-border/60 bg-surface/80 px-4 py-2 disabled:opacity-50"
|
||||
>
|
||||
{props.loading ? (
|
||||
<ActivityIndicator size="small" color={accentColor} />
|
||||
) : (
|
||||
<SymbolView name="chevron.up" size={12} tintColor={accentColor} type="monochrome" />
|
||||
)}
|
||||
<Text className="text-sm font-medium text-foreground">
|
||||
{props.loading ? "Loading earlier activity…" : "Load earlier activity"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{props.error !== null ? (
|
||||
<Text className="text-center text-xs" style={{ color: mutedColor }}>
|
||||
{props.error}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadFeedPlaceholder(props: {
|
||||
readonly bottomInset: number;
|
||||
readonly detail: string;
|
||||
@@ -1332,10 +1516,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const copyFeedbackTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const foldSettleFrameRef = useRef<number | null>(null);
|
||||
const foldSettleSecondFrameRef = useRef<number | null>(null);
|
||||
const previousLatestTurnRef = useRef(props.latestRun);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const disclosureAnchorKeyRef = useRef<string | null>(null);
|
||||
const headerMaterialVisibleRef = useRef(false);
|
||||
const previousLatestTurnRef = useRef(props.latestTurn);
|
||||
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const { width: windowWidth } = useWindowDimensions();
|
||||
const { appearance } = useAppearancePreferences();
|
||||
const [viewportWidth, setViewportWidth] = useState(() =>
|
||||
@@ -1343,11 +1527,11 @@ 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).
|
||||
// Live-follow latch (#5566). 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
|
||||
@@ -1375,7 +1559,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedTurnIds: ReadonlySet<RunId>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
@@ -1448,6 +1632,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const listAppearanceData = useMemo(
|
||||
() => ({
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1457,6 +1642,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -1549,22 +1735,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
|
||||
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
|
||||
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
// Thread identity is env-scoped: two environments can hold the same
|
||||
// ThreadId, and keying resets (or the list mount) on the bare id would
|
||||
// carry stale scroll/follow state across an environment switch.
|
||||
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, 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.
|
||||
@@ -1581,31 +1755,31 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
if (expanded) {
|
||||
ids.add(groupId);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}, [expandedWorkGroups]);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
setViewportWidth((current) => (Math.abs(current - nextWidth) > 1 ? nextWidth : current));
|
||||
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [feedThreadKey, reportHeaderMaterialVisibility]);
|
||||
|
||||
const presentedFeed = useMemo(
|
||||
() =>
|
||||
deriveThreadFeedPresentation(
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
props.latestRun,
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
new Set(
|
||||
Object.entries(expandedWorkGroups)
|
||||
.filter(([, expanded]) => expanded)
|
||||
.map(([groupId]) => groupId),
|
||||
),
|
||||
props.activeWorkStartedAt,
|
||||
),
|
||||
[
|
||||
expandedTurnIds,
|
||||
expandedWorkGroupIds,
|
||||
props.activeWorkStartedAt,
|
||||
props.feed,
|
||||
props.latestTurn,
|
||||
],
|
||||
[expandedTurnIds, expandedWorkGroups, props.activeWorkStartedAt, props.feed, props.latestRun],
|
||||
);
|
||||
|
||||
// The empty↔filled key below remounts the list, which resets its imperative
|
||||
@@ -1634,29 +1808,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[presentedFeed, props.anchorMessageId, anchorTopInset],
|
||||
);
|
||||
const terminalAssistantMessageIds = useMemo(() => {
|
||||
const terminalIdsByTurn = new Map<TurnId, string>();
|
||||
const terminalIdsByTurn = new Map<RunId, string>();
|
||||
for (const entry of props.feed) {
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.turnId) {
|
||||
terminalIdsByTurn.set(entry.message.turnId, entry.message.id);
|
||||
if (entry.type === "message" && entry.message.role === "assistant" && entry.message.runId) {
|
||||
terminalIdsByTurn.set(entry.message.runId, entry.message.id);
|
||||
}
|
||||
}
|
||||
return new Set(terminalIdsByTurn.values());
|
||||
}, [props.feed]);
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
const unsettledTurnId = threadFeedRunIsUnsettled(props.latestRun) ? props.latestRun.runId : null;
|
||||
|
||||
useEffect(() => {
|
||||
const previous = previousLatestTurnRef.current;
|
||||
previousLatestTurnRef.current = props.latestTurn;
|
||||
if (!props.latestTurn || !previous) {
|
||||
previousLatestTurnRef.current = props.latestRun;
|
||||
if (!props.latestRun || !previous) {
|
||||
return;
|
||||
}
|
||||
if (props.latestTurn.turnId === previous.turnId) {
|
||||
if (previous.state === "running" && props.latestTurn.state === "interrupted") {
|
||||
const interruptedTurnId = props.latestTurn.turnId;
|
||||
if (props.latestRun.runId === previous.runId) {
|
||||
if (previous.status === "running" && props.latestRun.status === "interrupted") {
|
||||
const interruptedTurnId = props.latestRun.runId;
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedTurnIds: new Set(current.expandedTurnIds).add(interruptedTurnId),
|
||||
@@ -1665,14 +1835,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return;
|
||||
}
|
||||
setInteractionState((current) => {
|
||||
if (!current.expandedTurnIds.has(previous.turnId)) {
|
||||
if (!current.expandedTurnIds.has(previous.runId)) {
|
||||
return current;
|
||||
}
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
next.delete(previous.turnId);
|
||||
next.delete(previous.runId);
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
}, [props.latestTurn]);
|
||||
}, [props.latestRun]);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -1753,8 +1923,8 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleWorkRow = useCallback(
|
||||
(rowId: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(rowId);
|
||||
(rowId: string, anchorKey?: string) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(anchorKey ?? null);
|
||||
setInteractionState((current) => ({
|
||||
...current,
|
||||
expandedWorkRows: {
|
||||
@@ -1767,14 +1937,14 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
|
||||
const onToggleTurnFold = useCallback(
|
||||
(turnId: TurnId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`turn-fold:${turnId}`);
|
||||
(runId: RunId) => {
|
||||
suspendEndScrollMaintenanceForDisclosure(`run-fold:${runId}`);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedTurnIds);
|
||||
if (next.has(turnId)) {
|
||||
next.delete(turnId);
|
||||
if (next.has(runId)) {
|
||||
next.delete(runId);
|
||||
} else {
|
||||
next.add(turnId);
|
||||
next.add(runId);
|
||||
}
|
||||
return { ...current, expandedTurnIds: next };
|
||||
});
|
||||
@@ -1799,7 +1969,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
const getFixedItemSize = useCallback(
|
||||
(entry: ThreadFeedEntry) => {
|
||||
switch (entry.type) {
|
||||
case "turn-fold":
|
||||
case "run-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
return WORK_GROUP_TOGGLE_HEIGHT;
|
||||
@@ -1822,7 +1992,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
(info: { item: ThreadFeedEntry; index: number }) =>
|
||||
renderFeedEntry(info, {
|
||||
environmentId: props.environmentId,
|
||||
threadId: props.threadId,
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1838,10 +2010,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reviewCommentColors,
|
||||
reviewCommentBubbleWidth,
|
||||
userBubbleMaxWidth,
|
||||
threadTitle: props.threadTitle,
|
||||
skills: props.skills,
|
||||
workspaceRoot: props.workspaceRoot,
|
||||
}),
|
||||
[
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
@@ -1858,7 +2033,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
props.environmentId,
|
||||
props.threadId,
|
||||
props.threadTitle,
|
||||
props.skills,
|
||||
props.workspaceRoot,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1988,17 +2166,10 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
ListHeaderComponent={
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.loadEarlier != null ? (
|
||||
<Pressable
|
||||
onPress={props.loadEarlier.onLoadEarlier}
|
||||
disabled={props.loadEarlier.loading}
|
||||
className="items-center py-2"
|
||||
>
|
||||
<Text className="text-xs text-foreground-secondary">
|
||||
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
{props.historyControls ? (
|
||||
<ThreadFeedLoadEarlierControl {...props.historyControls} />
|
||||
) : null}
|
||||
{props.topAccessory}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
|
||||
@@ -945,7 +945,7 @@ function ThreadNavigationSidebarPane(
|
||||
?.providers.find(
|
||||
(provider) =>
|
||||
provider.instanceId ===
|
||||
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
import { useMemo, useState } from "react";
|
||||
import { Pressable, ScrollView, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadProjection } from "../../state/use-thread-detail";
|
||||
import {
|
||||
buildCancelQueuedRunCommand,
|
||||
resolveThreadQueueRowControls,
|
||||
} from "./threadQueueControlPresentation";
|
||||
|
||||
export function ThreadQueueControl(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
}) {
|
||||
const scoped = useThreadProjection(props);
|
||||
const workflow = useMemo(
|
||||
() => (scoped ? deriveThreadQueueWorkflowState(scoped.projection) : null),
|
||||
[scoped],
|
||||
);
|
||||
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun, "reorder queued message");
|
||||
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun, "promote queued message");
|
||||
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun, "cancel queued message");
|
||||
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
if (!workflow || workflow.queuedRuns.length === 0) return null;
|
||||
|
||||
const move = async (runId: RunId, beforeRunId: RunId | null) => {
|
||||
setBusyRunId(runId);
|
||||
void Haptics.selectionAsync();
|
||||
await reorder({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: props.threadId, runId, beforeRunId },
|
||||
});
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
const steer = async (queuedRunId: RunId) => {
|
||||
if (!workflow.activeRun || !workflow.canPromoteToSteer) return;
|
||||
setBusyRunId(queuedRunId);
|
||||
void Haptics.selectionAsync();
|
||||
await promote({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
threadId: props.threadId,
|
||||
queuedRunId,
|
||||
targetRunId: workflow.activeRun.id,
|
||||
},
|
||||
});
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
const dismiss = async (runId: RunId) => {
|
||||
setBusyRunId(runId);
|
||||
void Haptics.selectionAsync();
|
||||
await cancel(
|
||||
buildCancelQueuedRunCommand({
|
||||
environmentId: props.environmentId,
|
||||
runId,
|
||||
threadId: props.threadId,
|
||||
}),
|
||||
);
|
||||
setBusyRunId(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<View className="mx-4 mb-3 overflow-hidden rounded-2xl border border-neutral-300/60 bg-card dark:border-white/[0.1]">
|
||||
<View className="flex-row items-center gap-2 border-b border-neutral-300/50 px-3 py-2 dark:border-white/[0.08]">
|
||||
<SymbolView name="list.number" size={13} tintColor={iconColor} type="monochrome" />
|
||||
<Text className="font-t3-medium text-xs text-foreground">Queue</Text>
|
||||
<Text className="ml-auto text-2xs tabular-nums text-foreground-muted">
|
||||
{workflow.queuedRuns.length}
|
||||
</Text>
|
||||
</View>
|
||||
<ScrollView style={{ maxHeight: 156 }} contentContainerStyle={{ paddingVertical: 4 }}>
|
||||
{workflow.queuedRuns.map(({ run, text }, index) => {
|
||||
const controls = resolveThreadQueueRowControls({
|
||||
busy: busyRunId !== null,
|
||||
canPromoteToSteer: workflow.canPromoteToSteer,
|
||||
canReorder: workflow.canReorder,
|
||||
index,
|
||||
queuedCount: workflow.queuedRuns.length,
|
||||
text,
|
||||
});
|
||||
|
||||
return (
|
||||
<View key={run.id} className="min-h-11 flex-row items-center gap-1.5 px-2">
|
||||
<Text className="w-5 text-right text-3xs tabular-nums text-foreground-muted">
|
||||
{index + 1}
|
||||
</Text>
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
{controls.displayText}
|
||||
</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message up"
|
||||
disabled={!controls.canMoveUp}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index - 1]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.up" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Move queued message down"
|
||||
disabled={!controls.canMoveDown}
|
||||
onPress={() => void move(run.id, workflow.queuedRuns[index + 2]?.run.id ?? null)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="arrow.down" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Promote queued message to steer"
|
||||
disabled={!controls.canSteer}
|
||||
onPress={() => void steer(run.id)}
|
||||
className="min-h-8 flex-row items-center gap-1 rounded-lg border border-neutral-300/60 px-2 disabled:opacity-30 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name="arrow.turn.left.up"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">Steer</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={controls.dismissAccessibilityLabel}
|
||||
disabled={!controls.canDismiss}
|
||||
onPress={() => void dismiss(run.id)}
|
||||
className="h-9 w-9 items-center justify-center disabled:opacity-30"
|
||||
>
|
||||
<SymbolView name="xmark" size={13} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { SymbolView, type SFSymbol } from "expo-symbols";
|
||||
import {
|
||||
deriveThreadRelationshipGraph,
|
||||
immediateThreadRelationships,
|
||||
resolveMergeBackTargetThreadId,
|
||||
type ThreadRelationshipEdge,
|
||||
} from "@t3tools/client-runtime/state/thread-relationships";
|
||||
import {
|
||||
canDetachThreadProviderSession,
|
||||
resolveLatestMergeBackRun,
|
||||
} from "@t3tools/client-runtime/state/thread-workflows";
|
||||
import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
|
||||
import { copySorted } from "@t3tools/shared/Array";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useMemo, useState } from "react";
|
||||
import { ActivityIndicator, Modal, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadShells } from "../../state/entities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import { useThreadProjection } from "../../state/use-thread-detail";
|
||||
import { useArchivedThreadSnapshots } from "../archive/useArchivedThreadSnapshots";
|
||||
|
||||
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): string {
|
||||
if (edge.kind === "transfer") {
|
||||
return edge.sourceThreadId === currentThreadId ? "Context sent to" : "Context received from";
|
||||
}
|
||||
if (edge.kind === "subagent") {
|
||||
return edge.sourceThreadId === currentThreadId ? "Subagent" : "Parent agent";
|
||||
}
|
||||
return edge.sourceThreadId === currentThreadId ? "Fork" : "Forked from";
|
||||
}
|
||||
|
||||
function relationshipSymbol(edge: ThreadRelationshipEdge): SFSymbol {
|
||||
if (edge.kind === "subagent") return "person.2";
|
||||
if (edge.kind === "transfer") return "arrow.left.arrow.right";
|
||||
return "arrow.triangle.branch";
|
||||
}
|
||||
|
||||
function threadAvailability(
|
||||
thread: OrchestrationV2ThreadShell | null,
|
||||
missing: boolean,
|
||||
): string | null {
|
||||
if (missing) return "Unavailable";
|
||||
if (thread?.deletedAt !== null && thread?.deletedAt !== undefined) return "Deleted";
|
||||
if (thread?.archivedAt !== null && thread?.archivedAt !== undefined) return "Archived";
|
||||
return null;
|
||||
}
|
||||
|
||||
const EMPTY_THREAD_SHELLS: ReadonlyArray<OrchestrationV2ThreadShell> = [];
|
||||
|
||||
export function ThreadRelationshipsBanner(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
}) {
|
||||
const scopedProjection = useThreadProjection(props);
|
||||
const projection = scopedProjection?.projection ?? null;
|
||||
const threadShells = useThreadShells();
|
||||
const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
|
||||
const archived = useArchivedThreadSnapshots(environmentIds);
|
||||
const archivedShells =
|
||||
archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
|
||||
.threads ?? EMPTY_THREAD_SHELLS;
|
||||
const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
|
||||
const environmentShells: OrchestrationV2ThreadShell[] = [];
|
||||
for (const thread of threadShells) {
|
||||
if (thread.environmentId === props.environmentId) {
|
||||
environmentShells.push(thread.source);
|
||||
}
|
||||
}
|
||||
environmentShells.push(...archivedShells);
|
||||
return environmentShells;
|
||||
}, [archivedShells, props.environmentId, threadShells]);
|
||||
const graph = useMemo(
|
||||
() => deriveThreadRelationshipGraph({ threads: shells, projection }),
|
||||
[projection, shells],
|
||||
);
|
||||
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
copySorted(
|
||||
immediateThreadRelationships(graph, props.threadId),
|
||||
(left, right) =>
|
||||
Number(right.threadId === mergeTargetThreadId) -
|
||||
Number(left.threadId === mergeTargetThreadId),
|
||||
),
|
||||
[graph, mergeTargetThreadId, props.threadId],
|
||||
);
|
||||
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
|
||||
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
|
||||
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
|
||||
const navigation = useNavigation();
|
||||
const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
|
||||
const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
|
||||
const insets = useSafeAreaInsets();
|
||||
const backdropColor = useThemeColor("--color-backdrop");
|
||||
const sheetColor = useThemeColor("--color-sheet");
|
||||
const iconColor = useThemeColor("--color-icon-subtle");
|
||||
|
||||
if (rows.length === 0 && !canDetach) return null;
|
||||
|
||||
const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
|
||||
const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
|
||||
const summary = primaryParent
|
||||
? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
|
||||
: "Agent session connected";
|
||||
|
||||
const openThread = (threadId: ThreadId, archivedThread: boolean) => {
|
||||
setVisible(false);
|
||||
void Haptics.selectionAsync();
|
||||
if (archivedThread) {
|
||||
navigation.navigate("SettingsSheet", {
|
||||
screen: "SettingsContent",
|
||||
params: { screen: "SettingsArchive" },
|
||||
});
|
||||
return;
|
||||
}
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId,
|
||||
});
|
||||
};
|
||||
|
||||
const merge = async () => {
|
||||
if (!canMerge || mergeTargetThreadId === null || latestMergeBackRun === null) return;
|
||||
setBusyAction("merge");
|
||||
const result = await mergeBack({
|
||||
environmentId: props.environmentId,
|
||||
input: {
|
||||
sourceThreadId: props.threadId,
|
||||
targetThreadId: mergeTargetThreadId,
|
||||
runId: latestMergeBackRun.id,
|
||||
creationSource: "mobile",
|
||||
},
|
||||
});
|
||||
setBusyAction(null);
|
||||
if (result._tag === "Success") openThread(mergeTargetThreadId, false);
|
||||
};
|
||||
|
||||
const detach = async () => {
|
||||
if (!canDetach) return;
|
||||
setBusyAction("detach");
|
||||
await stopSession({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: props.threadId },
|
||||
});
|
||||
setBusyAction(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`${summary}. Show thread relationships`}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
setVisible(true);
|
||||
}}
|
||||
className="mb-4 min-h-11 flex-row items-center gap-2 rounded-xl border border-neutral-300/60 bg-card px-3 py-2.5 dark:border-white/[0.1]"
|
||||
>
|
||||
<SymbolView
|
||||
name={primaryParent ? relationshipSymbol(primaryParent.edge) : "link"}
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="min-w-0 flex-1 font-t3-medium text-xs text-foreground" numberOfLines={1}>
|
||||
{summary}
|
||||
</Text>
|
||||
{rows.length > 1 ? (
|
||||
<Text className="text-2xs tabular-nums text-foreground-muted">+{rows.length - 1}</Text>
|
||||
) : null}
|
||||
<SymbolView name="chevron.right" size={12} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
|
||||
<Modal
|
||||
transparent
|
||||
animationType="fade"
|
||||
visible={visible}
|
||||
statusBarTranslucent
|
||||
onRequestClose={() => setVisible(false)}
|
||||
>
|
||||
<View className="flex-1 justify-end">
|
||||
<View
|
||||
pointerEvents="none"
|
||||
className="absolute inset-0"
|
||||
style={{ backgroundColor: backdropColor }}
|
||||
/>
|
||||
<Pressable className="absolute inset-0" onPress={() => setVisible(false)} />
|
||||
<View
|
||||
className="max-h-[78%] rounded-t-[28px] px-4 pt-3"
|
||||
style={{ backgroundColor: sheetColor, paddingBottom: Math.max(insets.bottom, 16) }}
|
||||
>
|
||||
<View className="mb-4 h-1 w-10 self-center rounded-full bg-neutral-400/40" />
|
||||
<View className="mb-3 flex-row items-center justify-between px-1">
|
||||
<View>
|
||||
<Text className="font-t3-bold text-lg text-foreground">Thread lineage</Text>
|
||||
<Text className="text-xs text-foreground-muted">
|
||||
{rows.length} related {rows.length === 1 ? "thread" : "threads"}
|
||||
</Text>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel="Close thread lineage"
|
||||
onPress={() => setVisible(false)}
|
||||
className="h-10 w-10 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/[0.07]"
|
||||
>
|
||||
<SymbolView name="xmark" size={14} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<ScrollView contentContainerStyle={{ gap: 8 }} showsVerticalScrollIndicator={false}>
|
||||
{rows.map(({ threadId, edge }) => {
|
||||
const node = graph.nodes.get(threadId);
|
||||
const availability = threadAvailability(
|
||||
node?.thread ?? null,
|
||||
node?.missing ?? true,
|
||||
);
|
||||
const archivedThread = availability === "Archived";
|
||||
const disabled = availability === "Unavailable" || availability === "Deleted";
|
||||
return (
|
||||
<Pressable
|
||||
key={`${edge.kind}:${threadId}`}
|
||||
accessibilityRole={disabled ? undefined : "link"}
|
||||
accessibilityState={{ disabled }}
|
||||
disabled={disabled}
|
||||
onPress={() => openThread(threadId, archivedThread)}
|
||||
className="min-h-14 flex-row items-center gap-3 rounded-2xl border border-neutral-300/50 bg-card px-3 py-2.5 dark:border-white/[0.08]"
|
||||
>
|
||||
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/60 dark:bg-white/[0.06]">
|
||||
<SymbolView
|
||||
name={relationshipSymbol(edge)}
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-3xs uppercase tracking-wide text-foreground-muted">
|
||||
{relationshipLabel(edge, props.threadId)}
|
||||
</Text>
|
||||
<Text className="font-t3-medium text-sm text-foreground" numberOfLines={1}>
|
||||
{node?.thread?.title ?? threadId}
|
||||
</Text>
|
||||
</View>
|
||||
{availability ? (
|
||||
<Text className="text-2xs text-foreground-muted">{availability}</Text>
|
||||
) : (
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={12}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
{canMerge || canDetach ? (
|
||||
<View className="mt-4 gap-2 border-t border-neutral-300/50 pt-4 dark:border-white/[0.08]">
|
||||
{canMerge ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={busyAction !== null}
|
||||
onPress={() => void merge()}
|
||||
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl bg-primary px-3"
|
||||
>
|
||||
{busyAction === "merge" ? (
|
||||
<ActivityIndicator color="white" />
|
||||
) : (
|
||||
<SymbolView name="arrow.triangle.merge" size={14} tintColor="white" />
|
||||
)}
|
||||
<Text className="font-t3-medium text-sm text-primary-foreground">
|
||||
Merge back to source
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
{canDetach ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={busyAction !== null}
|
||||
onPress={() => void detach()}
|
||||
className="min-h-11 flex-row items-center justify-center gap-2 rounded-xl border border-neutral-300/60 px-3 dark:border-white/[0.1]"
|
||||
>
|
||||
{busyAction === "detach" ? <ActivityIndicator /> : null}
|
||||
<Text className="font-t3-medium text-sm text-foreground">
|
||||
Disconnect agent session
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
</Modal>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -8,10 +8,6 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
requestOlderThreadTurns,
|
||||
threadHasOlderTurns,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -194,26 +190,36 @@ function ThreadRouteContent(
|
||||
useThreadSelection();
|
||||
const selectedThreadDetailState = props.selectedThreadDetailState;
|
||||
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
|
||||
// "Load earlier turns" header state for windowed (paginated) thread loads.
|
||||
const loadEarlierTurns = useMemo(() => {
|
||||
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
loading:
|
||||
selectedThreadDetailState.page._tag === "Some" &&
|
||||
selectedThreadDetailState.page.value.loadingOlder,
|
||||
onLoadEarlier: () => {
|
||||
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
|
||||
},
|
||||
};
|
||||
}, [selectedThread, selectedThreadDetailState]);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
const gitActions = useSelectedThreadGitActions();
|
||||
const requests = useSelectedThreadRequests();
|
||||
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
|
||||
const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
|
||||
label: "load earlier thread history",
|
||||
reportFailure: false,
|
||||
});
|
||||
const historyControls = useMemo(() => {
|
||||
const history = selectedThreadDetailState.history;
|
||||
if (!selectedThread) {
|
||||
return undefined;
|
||||
}
|
||||
if (!history.hasMoreHistory && history.error === null) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
hasMoreHistory: history.hasMoreHistory,
|
||||
loading: history.loading,
|
||||
error: history.error,
|
||||
onLoadEarlier: () => {
|
||||
void loadEarlierHistory({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: { threadId: selectedThread.id },
|
||||
});
|
||||
},
|
||||
};
|
||||
}, [loadEarlierHistory, selectedThread, selectedThreadDetailState.history]);
|
||||
const navigation = useNavigation();
|
||||
const params = props.route.params;
|
||||
const environmentIdRaw = firstRouteParam(params.environmentId);
|
||||
@@ -325,7 +331,7 @@ function ThreadRouteContent(
|
||||
}),
|
||||
[knownTerminalSessions, selectedThreadProject?.workspaceRoot],
|
||||
);
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.worktreePath ?? null;
|
||||
const selectedThreadDetailWorktreePath = selectedThreadDetail?.thread.worktreePath ?? null;
|
||||
const handleReconnectEnvironment = useCallback(() => {
|
||||
if (!environmentId) {
|
||||
return;
|
||||
@@ -479,23 +485,17 @@ function ThreadRouteContent(
|
||||
void navigation.navigate("Connections");
|
||||
}, [navigation]);
|
||||
const handleStopThread = useCallback(() => {
|
||||
if (
|
||||
!selectedThread ||
|
||||
(selectedThread.session?.status !== "running" &&
|
||||
selectedThread.session?.status !== "starting")
|
||||
) {
|
||||
if (!selectedThread || composer.interruptibleRunId === null) {
|
||||
return;
|
||||
}
|
||||
return interruptThreadTurn({
|
||||
environmentId: selectedThread.environmentId,
|
||||
input: {
|
||||
threadId: selectedThread.id,
|
||||
...(selectedThread.session.activeTurnId
|
||||
? { turnId: selectedThread.session.activeTurnId }
|
||||
: {}),
|
||||
runId: composer.interruptibleRunId,
|
||||
},
|
||||
});
|
||||
}, [interruptThreadTurn, selectedThread]);
|
||||
}, [composer.interruptibleRunId, interruptThreadTurn, selectedThread]);
|
||||
|
||||
const handleOpenTerminal = useCallback(
|
||||
(nextTerminalId?: string | null) => {
|
||||
@@ -773,6 +773,7 @@ function ThreadRouteContent(
|
||||
connectionError={routeConnectionError}
|
||||
environmentLabel={selectedEnvironmentConnection?.environmentLabel ?? null}
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activityRun={composer.selectedThreadActivityRun}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
@@ -784,7 +785,9 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
historyControls={historyControls}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
canStopThread={composer.interruptibleRunId !== null}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
threadCwd={selectedThreadCwd}
|
||||
|
||||
@@ -29,10 +29,11 @@ import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
threadHasUnseenCompletion,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
@@ -59,6 +60,8 @@ const STATUS_LABEL_BY_STATUS: Partial<
|
||||
approval: { label: "Approval", className: "text-amber-700 dark:text-amber-300" },
|
||||
input: { label: "Input", className: "text-indigo-600 dark:text-indigo-300" },
|
||||
working: { label: "Working", className: "text-sky-600 dark:text-sky-400" },
|
||||
// Colorless like the web sidebar: parked on background work, not "act now".
|
||||
waiting: { label: "Waiting", className: "text-foreground-tertiary" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
};
|
||||
|
||||
@@ -418,7 +421,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
// "Done" marks a completion the user has not opened yet — same emerald
|
||||
// label as the web sidebar, sourced from the server-side visited watermark
|
||||
// so checking a thread on any device clears it everywhere.
|
||||
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
|
||||
const statusLabel =
|
||||
STATUS_LABEL_BY_STATUS[status] ??
|
||||
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
@@ -714,7 +723,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
) : null}
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
{status === "failed" && thread.runtime?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
@@ -724,7 +733,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
{thread.runtime.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
describe("thread work log overflow labels", () => {
|
||||
it("describes tool-only groups as tool calls", () => {
|
||||
expect(threadWorkLogOverflowNoun(true, 1)).toBe("tool call");
|
||||
expect(threadWorkLogOverflowNoun(true, 2)).toBe("tool calls");
|
||||
});
|
||||
|
||||
it("describes mixed groups as log entries", () => {
|
||||
expect(threadWorkLogOverflowNoun(false, 1)).toBe("log entry");
|
||||
expect(threadWorkLogOverflowNoun(false, 2)).toBe("log entries");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
export function threadWorkLogOverflowNoun(
|
||||
onlyToolRows: boolean,
|
||||
count: number,
|
||||
): "tool call" | "tool calls" | "log entry" | "log entries" {
|
||||
if (onlyToolRows) {
|
||||
return count === 1 ? "tool call" : "tool calls";
|
||||
}
|
||||
return count === 1 ? "log entry" : "log entries";
|
||||
}
|
||||
@@ -1,14 +1,22 @@
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { Image } from "expo-image";
|
||||
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
|
||||
import { LayoutAnimation, Pressable, ScrollView, useColorScheme, View } from "react-native";
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { LayoutAnimation, Pressable, useColorScheme, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { T3_CODE_BRAND_MARK_SOURCE } from "../../components/brandAssets";
|
||||
import { scaledTypographyLineHeight } from "../../lib/appearancePreferences";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ThreadFeedActivity } from "../../lib/threadActivity";
|
||||
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
|
||||
import Animated, { FadeIn } from "react-native-reanimated";
|
||||
import { useV2ItemSupport } from "../../state/v2-item-support";
|
||||
import { ThreadActivityInspector } from "./ThreadActivityInspector";
|
||||
import { threadWorkLogOverflowNoun } from "./thread-work-log-labels";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
const WORK_LOG_LAYOUT_ANIMATION = {
|
||||
duration: 180,
|
||||
create: {
|
||||
@@ -71,6 +79,87 @@ function workRowSymbolName(icon: ThreadFeedActivity["icon"]): AppSymbolName {
|
||||
}
|
||||
}
|
||||
|
||||
function WorkRowIcon(props: {
|
||||
readonly row: ThreadFeedActivity;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
}) {
|
||||
const iconIsDestructive = props.row.icon === "alert" || props.row.icon === "warning";
|
||||
if (props.row.logo === "t3-code") {
|
||||
return (
|
||||
<Image
|
||||
source={T3_CODE_BRAND_MARK_SOURCE}
|
||||
accessibilityIgnoresInvertColors
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
borderRadius: 4,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<SymbolView
|
||||
name={workRowSymbolName(props.row.icon)}
|
||||
size={14}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ThreadActivityThreadLink(props: {
|
||||
readonly activity: ThreadFeedActivity;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly iconColor: import("react-native").ColorValue;
|
||||
}) {
|
||||
const row = props.activity.projectedItem;
|
||||
const support = useV2ItemSupport({
|
||||
environmentId: props.environmentId,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
});
|
||||
const navigation = useNavigation();
|
||||
const item = row.item;
|
||||
let targetThreadId: ThreadId | null = null;
|
||||
let label = "Open related thread";
|
||||
|
||||
if (item.type === "thread_created") {
|
||||
targetThreadId = item.targetThreadId;
|
||||
label = "Open created thread";
|
||||
} else if (item.type === "subagent") {
|
||||
targetThreadId = support.subagent?.childThreadId ?? item.childThreadId;
|
||||
label = "Open subagent thread";
|
||||
} else if (item.type === "fork") {
|
||||
targetThreadId =
|
||||
item.targetThreadId === row.sourceThreadId && item.source.type === "run"
|
||||
? item.source.threadId
|
||||
: item.targetThreadId;
|
||||
label = targetThreadId === item.targetThreadId ? "Open forked thread" : "Open parent thread";
|
||||
}
|
||||
|
||||
if (targetThreadId === null) return null;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="link"
|
||||
accessibilityLabel={label}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: props.environmentId,
|
||||
threadId: targetThreadId,
|
||||
});
|
||||
}}
|
||||
className="mx-2 mb-2 min-h-9 flex-row items-center justify-center gap-1.5 rounded-lg border border-neutral-300/50 px-2 dark:border-white/[0.08]"
|
||||
>
|
||||
<Text className="font-t3-medium text-2xs text-foreground">{label}</Text>
|
||||
<SymbolView name="arrow.right" size={11} tintColor={props.iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
// Entering fades only for rows created moments ago: rows remount whenever the
|
||||
// list scrolls them back into view, and old rows must not replay an entrance.
|
||||
const FRESH_ROW_WINDOW_MS = 3_000;
|
||||
@@ -122,10 +211,15 @@ export function collapsedWorkLogHeight(
|
||||
export function ThreadWorkLog(props: {
|
||||
readonly activities: ReadonlyArray<ThreadFeedActivity>;
|
||||
readonly copiedRowId: string | null;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly expanded: boolean;
|
||||
readonly expandedRows: Readonly<Record<string, boolean>>;
|
||||
readonly iconSubtleColor: import("react-native").ColorValue;
|
||||
readonly onCopyRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleGroup: () => void;
|
||||
readonly onToggleRow: (rowId: string) => void;
|
||||
readonly workspaceRoot?: string | null;
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
@@ -138,10 +232,15 @@ export function ThreadWorkLog(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasOverflow = rows.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleRows =
|
||||
hasOverflow && !props.expanded ? rows.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES) : rows;
|
||||
const hiddenCount = rows.length - visibleRows.length;
|
||||
const onlyToolRows = rows.every((row) => row.toolLike);
|
||||
const overflowNoun = threadWorkLogOverflowNoun(onlyToolRows, hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-3 px-1 py-0.5">
|
||||
{!onlyToolRows ? (
|
||||
<Text className="px-0.5 pb-0.5 font-t3-medium text-2xs text-foreground-muted opacity-60">
|
||||
work log
|
||||
@@ -149,17 +248,21 @@ export function ThreadWorkLog(props: {
|
||||
) : null}
|
||||
|
||||
<View className="gap-px">
|
||||
{rows.map((row) => {
|
||||
{visibleRows.map((row) => {
|
||||
const expanded = props.expandedRows[row.id] ?? false;
|
||||
const canExpand = row.canExpand;
|
||||
const fullDetail = expanded ? row.getFullDetail() : null;
|
||||
const displayText = row.detail ? `${row.summary} ${row.detail}` : row.summary;
|
||||
const iconIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
const detail = compactActivityDetail(row.detail);
|
||||
const displayText = detail ? `${row.summary} ${detail}` : row.summary;
|
||||
const textIsDestructive = row.icon === "alert" || row.icon === "warning";
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
key={row.id}
|
||||
{...(isFreshRow(row.createdAt) ? { entering: FadeIn.duration(200) } : {})}
|
||||
className={cn(
|
||||
row.prominent &&
|
||||
"mb-2 overflow-hidden rounded-xl border border-neutral-300/60 bg-card dark:border-white/[0.1]",
|
||||
)}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole={canExpand ? "button" : undefined}
|
||||
@@ -181,30 +284,24 @@ export function ThreadWorkLog(props: {
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="rounded-md px-0.5 py-0"
|
||||
className="rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="min-h-8 flex-row items-center gap-1.5">
|
||||
<View className="h-[18px] w-5 shrink-0 items-center justify-center">
|
||||
<SymbolView
|
||||
name={workRowSymbolName(row.icon)}
|
||||
size={13}
|
||||
weight="medium"
|
||||
tintColor={iconIsDestructive ? "#e11d48" : props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<View className="min-h-9 flex-row items-center gap-1.5">
|
||||
<View className="h-5 w-5 shrink-0 items-center justify-center">
|
||||
<WorkRowIcon row={row} iconSubtleColor={props.iconSubtleColor} />
|
||||
</View>
|
||||
|
||||
<Text className="min-w-0 flex-1 text-xs text-foreground" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground",
|
||||
iconIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
textIsDestructive && "text-rose-600 dark:text-rose-400",
|
||||
)}
|
||||
>
|
||||
{row.summary}
|
||||
</Text>
|
||||
{row.detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {row.detail}</Text>
|
||||
{detail ? (
|
||||
<Text className="text-foreground-muted opacity-60"> {detail}</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
|
||||
@@ -248,28 +345,63 @@ export function ThreadWorkLog(props: {
|
||||
</View>
|
||||
</Pressable>
|
||||
|
||||
{fullDetail ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
className="max-h-60"
|
||||
contentContainerStyle={{ paddingRight: 8 }}
|
||||
>
|
||||
<Text
|
||||
selectable
|
||||
className="font-mono text-2xs leading-normal text-foreground-muted"
|
||||
>
|
||||
{fullDetail}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
{expanded && canExpand ? (
|
||||
<View className="ml-7 border-l border-neutral-300/60 pb-1.5 pl-3 pt-0.5 dark:border-white/[0.12]">
|
||||
<ThreadActivityInspector
|
||||
activity={row}
|
||||
currentThreadId={props.currentThreadId}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
workspaceRoot={props.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{row.prominent ? (
|
||||
<ThreadActivityThreadLink
|
||||
activity={row}
|
||||
environmentId={props.environmentId}
|
||||
iconColor={props.iconSubtleColor}
|
||||
/>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
{hasOverflow ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={
|
||||
props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `Show ${hiddenCount} previous ${overflowNoun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggleGroup();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-9 flex-row items-center gap-1.5 rounded-md px-0.5 py-0.5"
|
||||
>
|
||||
<View className="h-5 w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={13}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded
|
||||
? `Show fewer ${overflowNoun}`
|
||||
: `+${hiddenCount} previous ${overflowNoun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -283,48 +415,36 @@ export function ThreadWorkGroupToggle(props: {
|
||||
}) {
|
||||
const colorScheme = useColorScheme();
|
||||
const pressedBackground = colorScheme === "dark" ? "rgba(255,255,255,0.05)" : "rgba(0,0,0,0.035)";
|
||||
const noun = props.onlyToolActivities
|
||||
? props.hiddenCount === 1
|
||||
? "tool call"
|
||||
: "tool calls"
|
||||
: props.hiddenCount === 1
|
||||
? "log entry"
|
||||
: "log entries";
|
||||
const collapsedLabel = `Show ${props.hiddenCount} previous ${noun}`;
|
||||
const expandedLabel = props.onlyToolActivities
|
||||
? "Show fewer tool calls"
|
||||
: "Show fewer log entries";
|
||||
const noun = threadWorkLogOverflowNoun(props.onlyToolActivities, props.hiddenCount);
|
||||
|
||||
return (
|
||||
<View className="-mx-1 mb-1 px-1 py-0">
|
||||
<View className="-mx-1 mb-1 px-1">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.expanded ? expandedLabel : collapsedLabel}
|
||||
accessibilityLabel={
|
||||
props.expanded ? `Show fewer ${noun}` : `Show ${props.hiddenCount} previous ${noun}`
|
||||
}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
triggerDisclosureFeedback();
|
||||
props.onToggle();
|
||||
}}
|
||||
style={({ pressed }) => ({
|
||||
backgroundColor: pressed ? pressedBackground : "transparent",
|
||||
})}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0"
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5"
|
||||
>
|
||||
<View className="h-[18px] w-5 items-center justify-center">
|
||||
<SymbolView
|
||||
name={
|
||||
props.expanded
|
||||
? { ios: "chevron.up", android: "keyboard_arrow_up" }
|
||||
: { ios: "chevron.down", android: "keyboard_arrow_down" }
|
||||
}
|
||||
name={props.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={12}
|
||||
tintColor={props.iconSubtleColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-foreground opacity-80">
|
||||
{props.expanded ? expandedLabel : `+${props.hiddenCount} previous ${noun}`}
|
||||
{props.expanded ? `Show fewer ${noun}` : `+${props.hiddenCount} previous ${noun}`}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
|
||||
|
||||
describe("thread activity file navigation", () => {
|
||||
it("keeps inherited activity file links on the currently selected thread", () => {
|
||||
const sourceThreadId = ThreadId.make("source-thread");
|
||||
const currentThreadId = ThreadId.make("current-thread");
|
||||
|
||||
const params = buildThreadActivityFileParams({
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
currentThreadId,
|
||||
activitySourceThreadId: sourceThreadId,
|
||||
relativePath: "apps/mobile/src/index.ts",
|
||||
line: 12,
|
||||
});
|
||||
|
||||
expect(params).toEqual({
|
||||
environmentId: "environment",
|
||||
threadId: "current-thread",
|
||||
path: ["apps", "mobile", "src", "index.ts"],
|
||||
line: "12",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
interface ThreadActivityFileContext {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly currentThreadId: ThreadId;
|
||||
readonly activitySourceThreadId: ThreadId;
|
||||
readonly relativePath: string;
|
||||
readonly line?: number | null;
|
||||
}
|
||||
|
||||
export function buildThreadActivityFileParams(input: ThreadActivityFileContext) {
|
||||
// Activity provenance may come from a parent thread, but file routes stay scoped
|
||||
// to the thread whose workspace is currently selected.
|
||||
return {
|
||||
environmentId: String(input.environmentId),
|
||||
threadId: String(input.currentThreadId),
|
||||
path: input.relativePath.split("/").filter((segment) => segment.length > 0),
|
||||
...(Number.isFinite(input.line) && Number(input.line) > 0
|
||||
? { line: String(Math.floor(Number(input.line))) }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { waitForThreadShellReady } from "./threadForkNavigation";
|
||||
|
||||
describe("waitForThreadShellReady", () => {
|
||||
it("returns true when the forked thread shell arrives before the deadline", async () => {
|
||||
let elapsedMs = 0;
|
||||
|
||||
const ready = await waitForThreadShellReady({
|
||||
read: () => elapsedMs >= 80,
|
||||
timeoutMs: 120,
|
||||
pollIntervalMs: 40,
|
||||
now: () => elapsedMs,
|
||||
delay: async (durationMs) => {
|
||||
elapsedMs += durationMs;
|
||||
},
|
||||
});
|
||||
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false instead of navigating when the shell never arrives", async () => {
|
||||
let elapsedMs = 0;
|
||||
|
||||
const ready = await waitForThreadShellReady({
|
||||
read: () => false,
|
||||
timeoutMs: 80,
|
||||
pollIntervalMs: 40,
|
||||
now: () => elapsedMs,
|
||||
delay: async (durationMs) => {
|
||||
elapsedMs += durationMs;
|
||||
},
|
||||
});
|
||||
|
||||
expect(ready).toBe(false);
|
||||
expect(elapsedMs).toBe(80);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
const DEFAULT_TIMEOUT_MS = 2_000;
|
||||
const DEFAULT_POLL_INTERVAL_MS = 40;
|
||||
|
||||
export async function waitForThreadShellReady(input: {
|
||||
readonly read: () => boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly pollIntervalMs?: number;
|
||||
readonly now?: () => number;
|
||||
readonly delay?: (durationMs: number) => Promise<void>;
|
||||
}): Promise<boolean> {
|
||||
const now = input.now ?? Date.now;
|
||||
const delay =
|
||||
input.delay ??
|
||||
((durationMs: number) =>
|
||||
new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, durationMs);
|
||||
}));
|
||||
const deadline = now() + (input.timeoutMs ?? DEFAULT_TIMEOUT_MS);
|
||||
const pollIntervalMs = input.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
||||
|
||||
while (!input.read() && now() < deadline) {
|
||||
await delay(Math.min(pollIntervalMs, deadline - now()));
|
||||
}
|
||||
|
||||
return input.read();
|
||||
}
|
||||
@@ -7,12 +7,13 @@ import {
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
buildThreadListV2ListItems,
|
||||
@@ -29,27 +30,10 @@ const environmentId = EnvironmentId.make("environment-1");
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> & Pick<EnvironmentThreadShell, "id" | "title">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
return makeThreadShellFixture({
|
||||
environmentId,
|
||||
projectId: ProjectId.make("project-1"),
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-06-01T00:00:00.000Z",
|
||||
updatedAt: "2026-06-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
@@ -126,18 +110,16 @@ describe("resolveThreadListV2Enabled", () => {
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running session", () => {
|
||||
it("prioritizes approval over a running runtime", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
hasPendingApprovals: true,
|
||||
session: {
|
||||
threadId: ThreadId.make("t"),
|
||||
runtime: {
|
||||
status: "running",
|
||||
activeRunId: RunId.make("run-t"),
|
||||
providerName: "Codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
@@ -145,6 +127,26 @@ describe("resolveThreadListV2Status", () => {
|
||||
expect(resolveThreadListV2Status(thread)).toBe("approval");
|
||||
});
|
||||
|
||||
it("reports waiting when presentation parks runtime idle for background tasks", () => {
|
||||
expect(
|
||||
resolveThreadListV2Status(
|
||||
makeThread({
|
||||
id: ThreadId.make("t"),
|
||||
title: "t",
|
||||
pendingBackgroundTasks: [{ taskId: "bg-1", description: "Run Codex review" }],
|
||||
runtime: {
|
||||
status: "idle",
|
||||
activeRunId: null,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
providerName: "Codex",
|
||||
lastError: null,
|
||||
updatedAt: NOW,
|
||||
},
|
||||
}),
|
||||
),
|
||||
).toBe("waiting");
|
||||
});
|
||||
|
||||
it("resolves ready for quiescent threads", () => {
|
||||
expect(resolveThreadListV2Status(makeThread({ id: ThreadId.make("t"), title: "t" }))).toBe(
|
||||
"ready",
|
||||
@@ -263,6 +265,68 @@ describe("sortThreadsForListV2", () => {
|
||||
});
|
||||
|
||||
describe("buildThreadListV2Items", () => {
|
||||
it("excludes subagent child threads from top-level rows and counts", () => {
|
||||
const rootThreadId = ThreadId.make("root");
|
||||
const activeChildId = ThreadId.make("active-child");
|
||||
const forkId = ThreadId.make("fork");
|
||||
const settledChildId = ThreadId.make("settled-child");
|
||||
const snoozedChildId = ThreadId.make("snoozed-child");
|
||||
const layout = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: rootThreadId, title: "Root" }),
|
||||
makeThread({
|
||||
id: forkId,
|
||||
title: "Fork",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "fork",
|
||||
},
|
||||
}),
|
||||
makeThread({
|
||||
id: activeChildId,
|
||||
title: "Active child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
}),
|
||||
makeThread({
|
||||
id: settledChildId,
|
||||
title: "Settled child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
settledOverride: "settled",
|
||||
settledAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: snoozedChildId,
|
||||
title: "Snoozed child",
|
||||
lineage: {
|
||||
rootThreadId,
|
||||
parentThreadId: rootThreadId,
|
||||
relationshipToParent: "subagent",
|
||||
},
|
||||
snoozedUntil: "2026-06-03T09:00:00.000Z",
|
||||
snoozedAt: "2026-06-01T12:00:00.000Z",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
settledLimit: 0,
|
||||
});
|
||||
|
||||
expect(layout.items.map((item) => item.thread.id)).toEqual([forkId, rootThreadId]);
|
||||
expect(layout.hiddenSettledCount).toBe(0);
|
||||
expect(layout.snoozedCount).toBe(0);
|
||||
expect(layout.nextSnoozeWakeAt).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps a merged thread active when auto-settle on merge is off", () => {
|
||||
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
|
||||
const layout = buildThreadListV2Items({
|
||||
@@ -645,10 +709,11 @@ describe("buildThreadListV2Items", () => {
|
||||
});
|
||||
|
||||
it("scopes the flat list to one project", () => {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const otherProjectId = ProjectId.make("project-2");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("included"), title: "Included" }),
|
||||
makeThread({ id: ThreadId.make("included"), projectId, title: "Included" }),
|
||||
makeThread({
|
||||
id: ThreadId.make("excluded"),
|
||||
projectId: otherProjectId,
|
||||
@@ -656,7 +721,7 @@ describe("buildThreadListV2Items", () => {
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [{ environmentId, projectId: ProjectId.make("project-1") }],
|
||||
projectRefs: [{ environmentId, projectId }],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
});
|
||||
@@ -666,19 +731,21 @@ describe("buildThreadListV2Items", () => {
|
||||
|
||||
it("scopes the flat list to every environment member of a logical project", () => {
|
||||
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const { items } = buildThreadListV2Items({
|
||||
threads: [
|
||||
makeThread({ id: ThreadId.make("local"), title: "Local" }),
|
||||
makeThread({ id: ThreadId.make("local"), projectId, title: "Local" }),
|
||||
makeThread({
|
||||
environmentId: remoteEnvironmentId,
|
||||
id: ThreadId.make("remote"),
|
||||
projectId,
|
||||
title: "Remote",
|
||||
}),
|
||||
],
|
||||
environmentId: null,
|
||||
projectRefs: [
|
||||
{ environmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId: remoteEnvironmentId, projectId: ProjectId.make("project-1") },
|
||||
{ environmentId, projectId },
|
||||
{ environmentId: remoteEnvironmentId, projectId },
|
||||
],
|
||||
searchQuery: "",
|
||||
now: NOW,
|
||||
@@ -701,9 +768,9 @@ describe("buildThreadListV2Items settled paging", () => {
|
||||
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
// A turn adopted the message (same requestedAt): without it the
|
||||
// thread reads as a queued turn start, which never settles.
|
||||
latestTurn: {
|
||||
turnId: TurnId.make(`turn-${index}`),
|
||||
state: "completed",
|
||||
latestRun: {
|
||||
runId: RunId.make(`run-${index}`),
|
||||
status: "completed",
|
||||
requestedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
startedAt: `2026-06-01T0${index}:00:00.000Z`,
|
||||
completedAt: `2026-06-01T0${index}:10:00.000Z`,
|
||||
|
||||
@@ -20,11 +20,13 @@ export { snoozeWakeLabel };
|
||||
* Thread List v2 model, ported from the web sidebar v2
|
||||
* (apps/web/src/components/Sidebar.logic.ts + SidebarV2.tsx).
|
||||
*
|
||||
* Four visual states, three colors: color is reserved for "act now"
|
||||
* (approval), "in motion" (working), and "broken" (failed). Ready is the
|
||||
* unlabeled resting state.
|
||||
* Six visual states. Color distinguishes approval, input, active work, and
|
||||
* failures. Ready is the unlabeled resting state; waiting (runtime status "idle") is the agent
|
||||
* parked on open background tasks, grey like working rather than a false Done.
|
||||
* The orchestrator v2 presentation bridge parks runtime at idle when the
|
||||
* post-settlement background roster is nonempty.
|
||||
*/
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "ready";
|
||||
export type ThreadListV2Status = "approval" | "input" | "working" | "waiting" | "failed" | "ready";
|
||||
export type ThreadListV2SwipeAction = "archive" | "settle" | "unsettle" | "snooze" | "unsnooze";
|
||||
|
||||
export function resolveThreadListV2SnoozeMenuSelection(input: {
|
||||
@@ -85,7 +87,7 @@ export function resolveThreadListV2SwipeActions(input: {
|
||||
export function resolveThreadListV2SnoozeGateExpiryMs(
|
||||
thread: Pick<
|
||||
EnvironmentThreadShell,
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestUserMessageAt" | "latestTurn" | "session"
|
||||
"hasPendingApprovals" | "hasPendingUserInput" | "latestRun" | "latestUserMessageAt" | "runtime"
|
||||
>,
|
||||
options: { readonly now: string },
|
||||
): number | null {
|
||||
@@ -122,8 +124,29 @@ export function resolveThreadListV2Enabled(input: {
|
||||
return input.legacyPreference !== true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed-but-not-yet-seen, mirroring the web sidebar's
|
||||
* hasUnseenCompletion. The visited watermark is server state
|
||||
* (thread.lastVisitedAt), so the marker agrees across web and mobile.
|
||||
* Never-visited threads count as read — a fresh environment must not light
|
||||
* up its whole history — and pre-tracking servers (field absent) never
|
||||
* report unread.
|
||||
*/
|
||||
export function threadHasUnseenCompletion(
|
||||
thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
|
||||
): boolean {
|
||||
const completedAt = thread.latestRun?.completedAt;
|
||||
if (!completedAt) return false;
|
||||
const completedAtMs = Date.parse(completedAt);
|
||||
if (Number.isNaN(completedAtMs)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
|
||||
if (Number.isNaN(lastVisitedAtMs)) return true;
|
||||
return completedAtMs > lastVisitedAtMs;
|
||||
}
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
|
||||
): ThreadListV2Status {
|
||||
if (thread.hasPendingApprovals) {
|
||||
return "approval";
|
||||
@@ -131,10 +154,16 @@ export function resolveThreadListV2Status(
|
||||
if (thread.hasPendingUserInput) {
|
||||
return "input";
|
||||
}
|
||||
if (thread.session?.status === "running" || thread.session?.status === "starting") {
|
||||
if (
|
||||
thread.runtime !== null &&
|
||||
["preparing", "queued", "starting", "running", "waiting"].includes(thread.runtime.status)
|
||||
) {
|
||||
return "working";
|
||||
}
|
||||
if (thread.session?.status === "error") {
|
||||
if (thread.runtime?.status === "idle") {
|
||||
return "waiting";
|
||||
}
|
||||
if (thread.runtime?.status === "failed") {
|
||||
return "failed";
|
||||
}
|
||||
return "ready";
|
||||
@@ -361,6 +390,7 @@ export function buildThreadListV2Items(input: {
|
||||
const snoozed: EnvironmentThreadShell[] = [];
|
||||
let nextSnoozeWakeAt: string | null = null;
|
||||
for (const thread of input.threads) {
|
||||
if (thread.lineage.relationshipToParent === "subagent") continue;
|
||||
// Callers pass live (unarchived) shells; settled threads are among them
|
||||
// and partition into the tail via effectiveSettled.
|
||||
if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";
|
||||
import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
export function threadSortValue(thread: EnvironmentThreadShell): number {
|
||||
const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);
|
||||
@@ -31,14 +33,10 @@ export const THREAD_STATUS_NEUTRAL_ICON = {
|
||||
iconBackground: "rgba(142,142,147,0.22)",
|
||||
} as const;
|
||||
|
||||
function isLatestTurnSettled(
|
||||
latestTurn: OrchestrationLatestTurn | null,
|
||||
session: OrchestrationSession | null,
|
||||
): boolean {
|
||||
if (!latestTurn?.startedAt) return false;
|
||||
if (!latestTurn.completedAt) return false;
|
||||
if (!session) return true;
|
||||
return session.status !== "running";
|
||||
function isLatestRunSettled(thread: EnvironmentThreadShell): boolean {
|
||||
if (!thread.latestRun?.startedAt) return false;
|
||||
if (!thread.latestRun.completedAt) return false;
|
||||
return !threadRuntimeIsActive(thread.runtime);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -73,7 +71,9 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "running") {
|
||||
const runtimeStatus = thread.runtime?.status;
|
||||
|
||||
if (runtimeStatus === "running" || runtimeStatus === "waiting") {
|
||||
return {
|
||||
kind: "working",
|
||||
label: "Working",
|
||||
@@ -85,7 +85,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "starting") {
|
||||
if (runtimeStatus === "preparing" || runtimeStatus === "queued" || runtimeStatus === "starting") {
|
||||
return {
|
||||
kind: "connecting",
|
||||
label: "Connecting",
|
||||
@@ -97,7 +97,7 @@ export function resolveThreadStatus(
|
||||
};
|
||||
}
|
||||
|
||||
if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
|
||||
if (runtimeStatus === "failed" || thread.latestRun?.status === "failed") {
|
||||
return {
|
||||
kind: "error",
|
||||
label: "Error",
|
||||
@@ -111,7 +111,7 @@ export function resolveThreadStatus(
|
||||
|
||||
const hasPlanReadyPrompt =
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
isLatestRunSettled(thread) &&
|
||||
thread.hasActionableProposedPlan;
|
||||
if (hasPlanReadyPrompt) {
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
|
||||
buildCancelQueuedRunCommand,
|
||||
resolveThreadQueueRowControls,
|
||||
} from "./threadQueueControlPresentation";
|
||||
|
||||
describe("threadQueueControlPresentation", () => {
|
||||
it("preserves queue reorder and steer controls with removal", () => {
|
||||
const controls = resolveThreadQueueRowControls({
|
||||
busy: false,
|
||||
canPromoteToSteer: true,
|
||||
canReorder: true,
|
||||
index: 1,
|
||||
queuedCount: 3,
|
||||
text: "Please review the follow-up change.",
|
||||
});
|
||||
|
||||
expect(controls.displayText).toBe("Please review the follow-up change.");
|
||||
expect(controls.canMoveUp).toBe(true);
|
||||
expect(controls.canMoveDown).toBe(true);
|
||||
expect(controls.canSteer).toBe(true);
|
||||
expect(controls.canDismiss).toBe(true);
|
||||
expect(controls.dismissAccessibilityLabel).toBe(REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL);
|
||||
});
|
||||
|
||||
it("disables edge reorder controls and busy dismissal", () => {
|
||||
const first = resolveThreadQueueRowControls({
|
||||
busy: false,
|
||||
canPromoteToSteer: false,
|
||||
canReorder: true,
|
||||
index: 0,
|
||||
queuedCount: 2,
|
||||
text: "First",
|
||||
});
|
||||
const busy = resolveThreadQueueRowControls({
|
||||
busy: true,
|
||||
canPromoteToSteer: true,
|
||||
canReorder: true,
|
||||
index: 0,
|
||||
queuedCount: 1,
|
||||
text: "Queued message",
|
||||
});
|
||||
|
||||
expect(first.canMoveUp).toBe(false);
|
||||
expect(first.canMoveDown).toBe(true);
|
||||
expect(first.canSteer).toBe(false);
|
||||
expect(busy.canDismiss).toBe(false);
|
||||
expect(busy.canMoveUp).toBe(false);
|
||||
expect(busy.canSteer).toBe(false);
|
||||
});
|
||||
|
||||
it("builds cancelQueuedRun command arguments for removal", () => {
|
||||
expect(
|
||||
buildCancelQueuedRunCommand({
|
||||
environmentId: "environment:test" as never,
|
||||
runId: "run:queued" as never,
|
||||
threadId: "thread:test" as never,
|
||||
}),
|
||||
).toEqual({
|
||||
environmentId: "environment:test",
|
||||
input: {
|
||||
runId: "run:queued",
|
||||
threadId: "thread:test",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export const REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL = "Remove queued message";
|
||||
|
||||
export interface ThreadQueueRowControls {
|
||||
readonly canDismiss: boolean;
|
||||
readonly canMoveDown: boolean;
|
||||
readonly canMoveUp: boolean;
|
||||
readonly canSteer: boolean;
|
||||
readonly dismissAccessibilityLabel: string;
|
||||
readonly displayText: string;
|
||||
}
|
||||
|
||||
export function resolveThreadQueueRowControls(input: {
|
||||
readonly busy: boolean;
|
||||
readonly canPromoteToSteer: boolean;
|
||||
readonly canReorder: boolean;
|
||||
readonly index: number;
|
||||
readonly queuedCount: number;
|
||||
readonly text: string;
|
||||
}): ThreadQueueRowControls {
|
||||
const mutationEnabled = !input.busy;
|
||||
|
||||
return {
|
||||
canDismiss: !input.busy,
|
||||
canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
|
||||
canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
|
||||
canSteer: mutationEnabled && input.canPromoteToSteer,
|
||||
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
|
||||
displayText: input.text,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCancelQueuedRunCommand(input: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly runId: RunId;
|
||||
readonly threadId: ThreadId;
|
||||
}): {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly input: {
|
||||
readonly runId: RunId;
|
||||
readonly threadId: ThreadId;
|
||||
};
|
||||
} {
|
||||
return {
|
||||
environmentId: input.environmentId,
|
||||
input: {
|
||||
runId: input.runId,
|
||||
threadId: input.threadId,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import { resolveUserMessageIntentBadge } from "./userMessageIntentBadge";
|
||||
|
||||
describe("user message intent badge", () => {
|
||||
it("does not label ordinary turn-start messages", () => {
|
||||
expect(resolveUserMessageIntentBadge(undefined)).toBeNull();
|
||||
expect(resolveUserMessageIntentBadge("turn_start")).toBeNull();
|
||||
});
|
||||
|
||||
it("labels messages waiting behind the active turn", () => {
|
||||
expect(resolveUserMessageIntentBadge("queued_turn")).toEqual({
|
||||
label: "queued",
|
||||
accessibilityLabel: "Queued behind the active turn",
|
||||
tone: "queued",
|
||||
});
|
||||
});
|
||||
|
||||
it("labels messages that steer the active turn", () => {
|
||||
expect(resolveUserMessageIntentBadge("steer")).toEqual({
|
||||
label: "steer",
|
||||
accessibilityLabel: "Steered the active turn",
|
||||
tone: "steer",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the queued origin after promotion to steer", () => {
|
||||
expect(resolveUserMessageIntentBadge("promoted_queued_to_steer")).toEqual({
|
||||
label: "queued → steer",
|
||||
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
|
||||
tone: "steer",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { OrchestrationV2UserMessageInputIntent } from "@t3tools/contracts";
|
||||
|
||||
export interface UserMessageIntentBadgePresentation {
|
||||
readonly label: string;
|
||||
readonly accessibilityLabel: string;
|
||||
readonly tone: "queued" | "steer";
|
||||
}
|
||||
|
||||
export function resolveUserMessageIntentBadge(
|
||||
intent: OrchestrationV2UserMessageInputIntent | undefined,
|
||||
): UserMessageIntentBadgePresentation | null {
|
||||
switch (intent) {
|
||||
case "queued_turn":
|
||||
return {
|
||||
label: "queued",
|
||||
accessibilityLabel: "Queued behind the active turn",
|
||||
tone: "queued",
|
||||
};
|
||||
case "steer":
|
||||
return {
|
||||
label: "steer",
|
||||
accessibilityLabel: "Steered the active turn",
|
||||
tone: "steer",
|
||||
};
|
||||
case "promoted_queued_to_steer":
|
||||
return {
|
||||
label: "queued → steer",
|
||||
accessibilityLabel: "Originally queued, then promoted to steer the active turn",
|
||||
tone: "steer",
|
||||
};
|
||||
case "turn_start":
|
||||
case undefined:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
ModelSelection,
|
||||
@@ -187,3 +188,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)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -7,19 +7,10 @@ import {
|
||||
type ProviderInteractionMode,
|
||||
type RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
|
||||
import { toUploadChatImageAttachments, type DraftComposerImageAttachment } from "./composerImages";
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
const compact = trimmed.replace(/\s+/g, " ");
|
||||
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
|
||||
}
|
||||
|
||||
export interface ProjectThreadStartTurnSpec {
|
||||
readonly projectId: ProjectId;
|
||||
readonly projectCwd: string;
|
||||
@@ -46,10 +37,11 @@ export interface ProjectThreadStartTurnSpec {
|
||||
* offline outbox drain so both deliver identical commands.
|
||||
*/
|
||||
export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpec) {
|
||||
const title = deriveThreadTitleFromPrompt(spec.text);
|
||||
const title = deriveThreadTitleSeed({ text: spec.text, attachments: spec.attachments });
|
||||
const isWorktree = spec.workspaceMode === "worktree";
|
||||
return {
|
||||
commandId: CommandId.make(spec.commandId),
|
||||
creationSource: "mobile" as const,
|
||||
threadId: ThreadId.make(spec.threadId),
|
||||
message: {
|
||||
messageId: MessageId.make(spec.messageId),
|
||||
@@ -87,3 +79,13 @@ export function buildProjectThreadStartTurnInput(spec: ProjectThreadStartTurnSpe
|
||||
createdAt: spec.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveThreadTitleFromPrompt(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return "New thread";
|
||||
}
|
||||
|
||||
const compact = trimmed.replace(/\s+/g, " ");
|
||||
return compact.length <= 72 ? compact : `${compact.slice(0, 69).trimEnd()}...`;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ApprovalRequestId, EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { EnvironmentId, ProjectId, RuntimeRequestId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
export function scopedProjectKey(environmentId: EnvironmentId, projectId: ProjectId): string {
|
||||
return `${environmentId}:${projectId}`;
|
||||
@@ -10,7 +10,7 @@ export function scopedThreadKey(environmentId: EnvironmentId, threadId: ThreadId
|
||||
|
||||
export function scopedRequestKey(
|
||||
environmentId: EnvironmentId,
|
||||
requestId: ApprovalRequestId,
|
||||
requestId: RuntimeRequestId,
|
||||
): string {
|
||||
return `${environmentId}:${requestId}`;
|
||||
}
|
||||
@@ -1,27 +1,419 @@
|
||||
import {
|
||||
MessageId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
buildThreadFeed,
|
||||
deriveThreadFeedPresentation,
|
||||
isPendingUserInputOptionSelected,
|
||||
setPendingUserInputCustomAnswer,
|
||||
togglePendingUserInputOptionSelection,
|
||||
threadFeedRunIsUnsettled,
|
||||
type ThreadFeedActivity,
|
||||
type ThreadFeedEntry,
|
||||
togglePendingUserInputOptionSelection,
|
||||
setPendingUserInputCustomAnswer,
|
||||
isPendingUserInputOptionSelected,
|
||||
buildPendingUserInputAnswers,
|
||||
} from "./threadActivity";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const sourceThreadId = ThreadId.make("thread-source");
|
||||
const runId = RunId.make("run-1");
|
||||
|
||||
function base(id: string, updatedAt: string, ordinal: number) {
|
||||
const timestamp = DateTime.makeUnsafe(updatedAt);
|
||||
return {
|
||||
id: TurnItemId.make(id),
|
||||
threadId,
|
||||
runId,
|
||||
nodeId: null,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt: timestamp,
|
||||
completedAt: timestamp,
|
||||
updatedAt: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
function projected(
|
||||
item: OrchestrationV2TurnItem,
|
||||
position: number,
|
||||
visibility: OrchestrationV2ProjectedTurnItem["visibility"] = "local",
|
||||
): OrchestrationV2ProjectedTurnItem {
|
||||
return {
|
||||
position,
|
||||
visibility,
|
||||
sourceThreadId: visibility === "local" ? threadId : sourceThreadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
};
|
||||
}
|
||||
|
||||
function userMessage(updatedAt = "2026-06-20T00:00:01.000Z") {
|
||||
return {
|
||||
...base("item-user", updatedAt, 0),
|
||||
type: "user_message" as const,
|
||||
messageId: MessageId.make("message-user"),
|
||||
createdBy: "user" as const,
|
||||
creationSource: "mobile" as const,
|
||||
inputIntent: "turn_start" as const,
|
||||
text: "Run checks",
|
||||
attachments: [],
|
||||
};
|
||||
}
|
||||
|
||||
function command(updatedAt = "2026-06-20T00:00:02.000Z") {
|
||||
return {
|
||||
...base("item-command", updatedAt, 1),
|
||||
type: "command_execution" as const,
|
||||
input: "vp check",
|
||||
output: "ok",
|
||||
exitCode: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function assistantMessage(updatedAt = "2026-06-20T00:00:03.000Z") {
|
||||
return {
|
||||
...base("item-assistant", updatedAt, 2),
|
||||
type: "assistant_message" as const,
|
||||
messageId: MessageId.make("message-assistant"),
|
||||
text: "Done",
|
||||
streaming: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("hides synthetic workspace preparation activity", () => {
|
||||
const workspacePreparation = projected(
|
||||
{
|
||||
...command(),
|
||||
title: "Workspace ready",
|
||||
input: "Preparing workspace",
|
||||
output: "Workspace preparation completed.",
|
||||
},
|
||||
0,
|
||||
);
|
||||
|
||||
expect(buildThreadFeed([workspacePreparation])).toEqual([]);
|
||||
});
|
||||
|
||||
it("does not treat a queued-only run as live feed activity", () => {
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "queued",
|
||||
startedAt: null,
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
threadFeedRunIsUnsettled({
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("adds queued input only after dispatch creates its turn item", () => {
|
||||
const dispatchedRunId = RunId.make("run-dispatched-queued");
|
||||
const dispatchedMessageId = MessageId.make("message-dispatched-queued");
|
||||
expect(buildThreadFeed([])).toEqual([]);
|
||||
|
||||
const promotedEntries = buildThreadFeed([
|
||||
projected(
|
||||
{
|
||||
...userMessage(),
|
||||
id: TurnItemId.make("item-dispatched-queued"),
|
||||
runId: dispatchedRunId,
|
||||
messageId: dispatchedMessageId,
|
||||
inputIntent: "turn_start",
|
||||
},
|
||||
0,
|
||||
),
|
||||
]);
|
||||
expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
|
||||
expect(
|
||||
promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
|
||||
).toBe("turn_start");
|
||||
});
|
||||
|
||||
it("hides the interruption request and keeps the terminal result", () => {
|
||||
const request = projected(
|
||||
{
|
||||
...base("item-interrupt-request", "2026-06-20T00:00:02.000Z", 1),
|
||||
type: "run_interrupt_request",
|
||||
message: "Interrupt requested",
|
||||
},
|
||||
0,
|
||||
);
|
||||
const result = projected(
|
||||
{
|
||||
...base("item-interrupt-result", "2026-06-20T00:00:03.000Z", 2),
|
||||
type: "run_interrupt_result",
|
||||
message: "Run interrupted before provider start",
|
||||
},
|
||||
1,
|
||||
);
|
||||
|
||||
const activities = buildThreadFeed([request, result]).flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities : [],
|
||||
);
|
||||
|
||||
expect(activities).toHaveLength(1);
|
||||
expect(activities[0]?.summary).toBe("Run interrupted");
|
||||
expect(activities[0]?.detail).toBe("Run interrupted before provider start");
|
||||
});
|
||||
|
||||
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
|
||||
const rows = [
|
||||
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
|
||||
projected(command("2026-06-20T00:00:01.000Z"), 1),
|
||||
projected(assistantMessage("2026-06-20T00:00:02.000Z"), 2),
|
||||
];
|
||||
|
||||
const feed = buildThreadFeed(rows);
|
||||
expect(feed.map((entry) => entry.type)).toEqual(["message", "activity-group", "message"]);
|
||||
expect(feed.map((entry) => entry.id)).toEqual([
|
||||
"message-user",
|
||||
"local:thread-1:item-command",
|
||||
"message-assistant",
|
||||
]);
|
||||
const activity = feed.find((entry) => entry.type === "activity-group")?.activities[0];
|
||||
expect(activity?.projectedItem).toBe(rows[1]);
|
||||
expect(activity?.getFullDetail()).toContain('"input": "vp check"');
|
||||
});
|
||||
|
||||
it("retains inherited and synthetic rows with their original projected identity", () => {
|
||||
const inherited = projected(command(), 0, "inherited");
|
||||
const { providerThreadId: _providerThreadId, ...forkBase } = base(
|
||||
"item-fork",
|
||||
"2026-06-20T00:00:03.000Z",
|
||||
2,
|
||||
);
|
||||
const synthetic = projected(
|
||||
{
|
||||
...forkBase,
|
||||
type: "fork",
|
||||
source: { type: "run", threadId: sourceThreadId, runId },
|
||||
targetThreadId: threadId,
|
||||
},
|
||||
1,
|
||||
"synthetic",
|
||||
);
|
||||
|
||||
const feed = buildThreadFeed([inherited, synthetic]);
|
||||
const activities = feed.flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities : [],
|
||||
);
|
||||
expect(activities.map((activity) => activity.projectedItem)).toEqual([inherited, synthetic]);
|
||||
expect(activities.map((activity) => activity.projectedItem.visibility)).toEqual([
|
||||
"inherited",
|
||||
"synthetic",
|
||||
]);
|
||||
expect(activities.at(-1)?.prominent).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps orchestration relationship cards visible when a completed run is folded", () => {
|
||||
const { providerThreadId: _providerThreadId, ...forkBase } = base(
|
||||
"item-fork",
|
||||
"2026-06-20T00:00:02.500Z",
|
||||
2,
|
||||
);
|
||||
const feed = buildThreadFeed([
|
||||
projected(userMessage(), 0),
|
||||
projected(command(), 1),
|
||||
projected(
|
||||
{
|
||||
...forkBase,
|
||||
type: "fork",
|
||||
source: { type: "run", threadId, runId },
|
||||
targetThreadId: sourceThreadId,
|
||||
},
|
||||
2,
|
||||
),
|
||||
projected(assistantMessage(), 3),
|
||||
]);
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "completed",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
},
|
||||
new Set(),
|
||||
);
|
||||
|
||||
expect(
|
||||
collapsed.some(
|
||||
(entry) =>
|
||||
entry.type === "activity-group" &&
|
||||
entry.activities.some((activity) => activity.projectedItem.item.type === "fork"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
collapsed.some(
|
||||
(entry) =>
|
||||
entry.type === "activity-group" &&
|
||||
entry.activities.some(
|
||||
(activity) => activity.projectedItem.item.type === "command_execution",
|
||||
),
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("folds settled V2 run work while keeping the terminal assistant message visible", () => {
|
||||
const feed = buildThreadFeed([
|
||||
projected(userMessage(), 0),
|
||||
projected(command(), 1),
|
||||
projected(assistantMessage(), 2),
|
||||
]);
|
||||
const latestRun = {
|
||||
runId,
|
||||
status: "completed" as const,
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: "2026-06-20T00:00:03.000Z",
|
||||
};
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, latestRun, new Set());
|
||||
expect(collapsed.map((entry) => entry.type)).toEqual(["message", "run-fold", "message"]);
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId]));
|
||||
expect(expanded.map((entry) => entry.type)).toEqual([
|
||||
"message",
|
||||
"run-fold",
|
||||
"activity-group",
|
||||
"message",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps an active run expanded and marks failed tools as failures", () => {
|
||||
const failedCommand: OrchestrationV2TurnItem = {
|
||||
...command(),
|
||||
status: "failed",
|
||||
completedAt: DateTime.makeUnsafe("2026-06-20T00:00:02.000Z"),
|
||||
};
|
||||
const feed = buildThreadFeed([projected(userMessage(), 0), projected(failedCommand, 1)]);
|
||||
const presented = deriveThreadFeedPresentation(
|
||||
feed,
|
||||
{
|
||||
runId,
|
||||
status: "running",
|
||||
startedAt: "2026-06-20T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
},
|
||||
new Set(),
|
||||
);
|
||||
|
||||
expect(presented.some((entry) => entry.type === "run-fold")).toBe(false);
|
||||
expect(presented.find((entry) => entry.type === "activity-group")?.activities[0]?.status).toBe(
|
||||
"failure",
|
||||
);
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
const startedAt = "2026-04-01T00:00:01.000Z";
|
||||
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
|
||||
|
||||
expect(presented).toEqual([
|
||||
{
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: startedAt,
|
||||
},
|
||||
]);
|
||||
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
runId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
canExpand: false,
|
||||
getFullDetail: () => null,
|
||||
getCopyText: () => id,
|
||||
icon: "command",
|
||||
logo: null,
|
||||
toolLike: true,
|
||||
prominent: false,
|
||||
status,
|
||||
projectedItem: projected(command(createdAt), 0),
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
runId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
|
||||
expect(collapsed[1]).toMatchObject({
|
||||
type: "work-toggle",
|
||||
groupId: "work-group-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"activity-1",
|
||||
"activity-2",
|
||||
"activity-3",
|
||||
"work-toggle:work-group-1",
|
||||
]);
|
||||
expect(expanded.at(-1)).toMatchObject({
|
||||
type: "work-toggle",
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("pretty prints T3 MCP dynamic tool activities and attaches the product logo", () => {
|
||||
const toolItem: OrchestrationV2TurnItem = {
|
||||
...base("item-t3-tool", "2026-06-20T00:00:04.000Z", 3),
|
||||
type: "dynamic_tool",
|
||||
toolName: "mcp__t3-code__t3_thread_read",
|
||||
input: { threadId: "thread-child" },
|
||||
output: { messages: [] },
|
||||
};
|
||||
|
||||
const feed = buildThreadFeed([projected(toolItem, 0)]);
|
||||
const activity = feed[0]?.type === "activity-group" ? feed[0].activities[0] : null;
|
||||
|
||||
expect(activity?.summary).toBe("Read a T3 thread");
|
||||
expect(activity?.logo).toBe("t3-code");
|
||||
expect(activity?.getCopyText().split("\n")[0]).toBe("Read a T3 thread");
|
||||
});
|
||||
});
|
||||
|
||||
const singleSelectQuestion = {
|
||||
id: "runtime",
|
||||
header: "Runtime",
|
||||
@@ -112,554 +504,3 @@ describe("pending user input answers", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
function makeActivity(
|
||||
input: Partial<OrchestrationThreadActivity> &
|
||||
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
tone: "info",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<OrchestrationThread> & Pick<OrchestrationThread, "id" | "projectId" | "title">,
|
||||
): OrchestrationThread {
|
||||
return {
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
archivedAt: null,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildThreadFeed", () => {
|
||||
it("keeps historic work entries attributed to their turns", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Runtime warning thread",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("activity-old"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-old"),
|
||||
payload: {
|
||||
message: "Old warning",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("activity-latest"),
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
turnId: TurnId.make("turn-latest"),
|
||||
payload: {
|
||||
message: "Latest warning",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(feed).toMatchObject([
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-old",
|
||||
activities: [{ id: "activity-old", turnId: "turn-old" }],
|
||||
},
|
||||
{
|
||||
type: "activity-group",
|
||||
turnId: "turn-latest",
|
||||
activities: [{ id: "activity-latest", turnId: "turn-latest" }],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("collapses matching tool lifecycle rows like desktop", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Collapsed tools",
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-updated"),
|
||||
kind: "tool.updated",
|
||||
tone: "tool",
|
||||
summary: "Run tests",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run tests completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
payload: {
|
||||
title: "Run tests",
|
||||
itemType: "command_execution",
|
||||
detail: "/bin/zsh -lc 'bun run test'",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const group = feed[0];
|
||||
|
||||
expect(group).toMatchObject({
|
||||
type: "activity-group",
|
||||
});
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(1);
|
||||
expect(group.activities[0]).toMatchObject({
|
||||
id: "tool-completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId: "turn-1",
|
||||
summary: "Run tests",
|
||||
detail: "bun run test",
|
||||
canExpand: true,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status: "success",
|
||||
});
|
||||
expect(group.activities[0]?.getFullDetail()).toBe("/bin/zsh -lc 'bun run test'");
|
||||
expect(group.activities[0]?.getCopyText()).toBe(
|
||||
"Run tests\nbun run test\n/bin/zsh -lc 'bun run test'",
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps MCP inputs available to expanded mobile work rows", () => {
|
||||
const turnId = TurnId.make("turn-mcp");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-mcp"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Expandable MCP call",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("mcp-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Call repository tool",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Call repository tool",
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "repository.search",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
server: "repository",
|
||||
tool: "search",
|
||||
arguments: { query: "work log" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const group = buildThreadFeed(thread)[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities[0]?.icon).toBe("wrench");
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"query": "work log"');
|
||||
expect(group.activities[0]?.getFullDetail()).toContain("repository.search");
|
||||
});
|
||||
|
||||
it("defers large tool output expansion until a work row is opened or copied", () => {
|
||||
let serializedToolOutputs = 0;
|
||||
const activities = Array.from({ length: 5_000 }, (_, index) =>
|
||||
makeActivity({
|
||||
id: EventId.make(`large-tool-${index}`),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: `Tool ${index}`,
|
||||
createdAt: new Date(Date.UTC(2026, 3, 1, 0, 0, index)).toISOString(),
|
||||
payload: {
|
||||
title: `Tool ${index}`,
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
data: {
|
||||
item: {
|
||||
toJSON: () => {
|
||||
serializedToolOutputs += 1;
|
||||
return { output: "x".repeat(32_768) };
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-large-tools"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Large tools",
|
||||
activities,
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(serializedToolOutputs).toBe(0);
|
||||
|
||||
const group = feed[0];
|
||||
expect(group).toMatchObject({ type: "activity-group" });
|
||||
if (!group || group.type !== "activity-group") {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(group.activities).toHaveLength(5_000);
|
||||
expect(group.activities[0]?.getFullDetail()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
expect(group.activities[0]?.getCopyText()).toContain('"output"');
|
||||
expect(serializedToolOutputs).toBe(1);
|
||||
});
|
||||
|
||||
it("folds settled turn work while leaving the terminal answer visible", () => {
|
||||
const turnId = TurnId.make("turn-1");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-3"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Folded work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "completed",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: "2026-04-01T00:00:18.000Z",
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "I am checking.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
updatedAt: "2026-04-01T00:00:03.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:18.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-completed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Read files",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Read files",
|
||||
itemType: "file_read",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["turn-fold:turn-1", "assistant-final"]);
|
||||
expect(collapsed[0]).toMatchObject({
|
||||
type: "turn-fold",
|
||||
label: "Worked for 17s",
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set([turnId]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-commentary",
|
||||
"tool-completed",
|
||||
"assistant-final",
|
||||
]);
|
||||
});
|
||||
|
||||
it("measures a steer-superseded turn from its user boundary through trailing work", () => {
|
||||
const firstTurnId = TurnId.make("turn-1");
|
||||
const secondTurnId = TurnId.make("turn-2");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-steered"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Steered work",
|
||||
latestTurn: {
|
||||
turnId: secondTurnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:14.000Z",
|
||||
startedAt: "2026-04-01T00:00:14.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("assistant-next"),
|
||||
},
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("user-1"),
|
||||
role: "user",
|
||||
text: "Do it once more.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-commentary"),
|
||||
role: "assistant",
|
||||
text: "Kicking off call 1.",
|
||||
turnId: firstTurnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:09.000Z",
|
||||
updatedAt: "2026-04-01T00:00:09.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("user-2"),
|
||||
role: "user",
|
||||
text: "Actually do 15.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T00:00:14.000Z",
|
||||
updatedAt: "2026-04-01T00:00:14.000Z",
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-next"),
|
||||
role: "assistant",
|
||||
text: "One down - adjusting.",
|
||||
turnId: secondTurnId,
|
||||
streaming: true,
|
||||
createdAt: "2026-04-01T00:00:17.000Z",
|
||||
updatedAt: "2026-04-01T00:00:17.000Z",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("work-1"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Ran command",
|
||||
createdAt: "2026-04-01T00:00:12.000Z",
|
||||
turnId: firstTurnId,
|
||||
payload: {
|
||||
title: "Ran command",
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const collapsed = deriveThreadFeedPresentation(feed, thread.latestTurn, new Set());
|
||||
expect(collapsed.find((entry) => entry.type === "turn-fold")).toMatchObject({
|
||||
turnId: firstTurnId,
|
||||
label: "Worked for 12s",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps an active turn expanded and classifies error-shaped tool output", () => {
|
||||
const turnId = TurnId.make("turn-running");
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-4"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Running work",
|
||||
latestTurn: {
|
||||
turnId,
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T00:00:00.000Z",
|
||||
startedAt: "2026-04-01T00:00:01.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
activities: [
|
||||
makeActivity({
|
||||
id: EventId.make("tool-failed"),
|
||||
kind: "tool.completed",
|
||||
tone: "tool",
|
||||
summary: "Run command",
|
||||
createdAt: "2026-04-01T00:00:05.000Z",
|
||||
turnId,
|
||||
payload: {
|
||||
title: "Run command",
|
||||
itemType: "command_execution",
|
||||
detail: "zsh: command not found: nope",
|
||||
status: "completed",
|
||||
},
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
expect(deriveThreadFeedPresentation(feed, thread.latestTurn, new Set())).toEqual(feed);
|
||||
expect(feed[0]).toMatchObject({
|
||||
type: "activity-group",
|
||||
activities: [{ status: "failure" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("appends active work as a normal timeline row", () => {
|
||||
const startedAt = "2026-04-01T00:00:01.000Z";
|
||||
const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);
|
||||
|
||||
expect(presented).toEqual([
|
||||
{
|
||||
type: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: startedAt,
|
||||
},
|
||||
]);
|
||||
expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]);
|
||||
});
|
||||
|
||||
it("models work-log overflow as list rows", () => {
|
||||
const activity = (
|
||||
id: string,
|
||||
createdAt: string,
|
||||
status: ThreadFeedActivity["status"] = "success",
|
||||
): ThreadFeedActivity => ({
|
||||
id,
|
||||
createdAt,
|
||||
turnId: null,
|
||||
summary: `Tool ${id}`,
|
||||
detail: null,
|
||||
canExpand: false,
|
||||
getFullDetail: () => null,
|
||||
getCopyText: () => id,
|
||||
icon: "command",
|
||||
toolLike: true,
|
||||
status,
|
||||
});
|
||||
const feed: ThreadFeedEntry[] = [
|
||||
{
|
||||
type: "activity-group",
|
||||
id: "work-group-1",
|
||||
createdAt: "2026-04-01T00:00:01.000Z",
|
||||
turnId: null,
|
||||
activities: [
|
||||
activity("activity-1", "2026-04-01T00:00:01.000Z"),
|
||||
activity("activity-neutral", "2026-04-01T00:00:02.000Z", "neutral"),
|
||||
activity("activity-2", "2026-04-01T00:00:03.000Z"),
|
||||
activity("activity-3", "2026-04-01T00:00:04.000Z"),
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const collapsed = deriveThreadFeedPresentation(feed, null, new Set());
|
||||
expect(collapsed.map((entry) => entry.id)).toEqual(["activity-3", "work-toggle:work-group-1"]);
|
||||
expect(collapsed[1]).toMatchObject({
|
||||
type: "work-toggle",
|
||||
groupId: "work-group-1",
|
||||
hiddenCount: 2,
|
||||
expanded: false,
|
||||
});
|
||||
|
||||
const expanded = deriveThreadFeedPresentation(feed, null, new Set(), new Set(["work-group-1"]));
|
||||
expect(expanded.map((entry) => entry.id)).toEqual([
|
||||
"activity-1",
|
||||
"activity-2",
|
||||
"activity-3",
|
||||
"work-toggle:work-group-1",
|
||||
]);
|
||||
expect(expanded.at(-1)).toMatchObject({
|
||||
type: "work-toggle",
|
||||
expanded: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("quiet timeline: nested agents", () => {
|
||||
it("keeps a nested agent's terminal row but hides its background work", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-nested"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Nested agents",
|
||||
activities: [
|
||||
// A subagent's own shell: internal, covered by the owner's liveness.
|
||||
makeActivity({
|
||||
id: EventId.make("shell-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
|
||||
}),
|
||||
// A nested AGENT's completion: mobile has no Agents sheet, so this
|
||||
// terminal row is the only signal it ever finished.
|
||||
makeActivity({
|
||||
id: EventId.make("nested-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const ids = feed.flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
|
||||
);
|
||||
expect(ids).toContain("nested-done");
|
||||
expect(ids).not.toContain("shell-done");
|
||||
});
|
||||
});
|
||||
+407
-1186
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,257 @@
|
||||
import { EMPTY_V2_ITEM_SUPPORT } from "@t3tools/client-runtime/state/item-support";
|
||||
import {
|
||||
CheckpointId,
|
||||
CheckpointScopeId,
|
||||
NodeId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
RunId,
|
||||
ThreadId,
|
||||
TurnItemId,
|
||||
type OrchestrationV2ProjectedTurnItem,
|
||||
type OrchestrationV2TurnItem,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { buildThreadFeed, type ThreadFeedActivity } from "./threadActivity";
|
||||
import { buildThreadActivityInspector } from "./threadActivityInspector";
|
||||
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const sourceThreadId = ThreadId.make("thread-source");
|
||||
const runId = RunId.make("run-1");
|
||||
const nodeId = NodeId.make("node-1");
|
||||
const startedAt = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
|
||||
const completedAt = DateTime.makeUnsafe("2026-06-20T00:00:02.000Z");
|
||||
|
||||
function itemBase(id: string) {
|
||||
return {
|
||||
id: TurnItemId.make(id),
|
||||
threadId,
|
||||
runId,
|
||||
nodeId,
|
||||
providerThreadId: null,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: 0,
|
||||
status: "completed" as const,
|
||||
title: null,
|
||||
startedAt,
|
||||
completedAt,
|
||||
updatedAt: completedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function activityFor(item: OrchestrationV2TurnItem): ThreadFeedActivity {
|
||||
const row: OrchestrationV2ProjectedTurnItem = {
|
||||
position: 0,
|
||||
visibility: "inherited",
|
||||
sourceThreadId,
|
||||
sourceItemId: item.id,
|
||||
item,
|
||||
};
|
||||
const group = buildThreadFeed([row])[0];
|
||||
if (group?.type !== "activity-group" || !group.activities[0]) {
|
||||
throw new Error("Expected an activity group");
|
||||
}
|
||||
return group.activities[0];
|
||||
}
|
||||
|
||||
describe("buildThreadActivityInspector", () => {
|
||||
it("presents command lifecycle, execution support, output, and exit state", () => {
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("command"),
|
||||
type: "command_execution",
|
||||
input: "vp check",
|
||||
output: "all checks passed",
|
||||
exitCode: 0,
|
||||
};
|
||||
const support = {
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
run: { status: "completed" } as never,
|
||||
attempts: [
|
||||
{
|
||||
id: "attempt-1",
|
||||
attemptOrdinal: 1,
|
||||
status: "superseded",
|
||||
reason: "initial",
|
||||
},
|
||||
{
|
||||
id: "attempt-2",
|
||||
attemptOrdinal: 2,
|
||||
status: "completed",
|
||||
reason: "steering_restart",
|
||||
},
|
||||
] as never,
|
||||
node: { kind: "tool_call", status: "completed" } as never,
|
||||
providerSession: {
|
||||
status: "ready",
|
||||
model: "gpt-5.4",
|
||||
cwd: "/workspace/project",
|
||||
} as never,
|
||||
};
|
||||
|
||||
const model = buildThreadActivityInspector(activityFor(item), support, sourceThreadId);
|
||||
expect(model.fields).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ label: "Duration", value: "2.0s" },
|
||||
{ label: "Run", value: "completed" },
|
||||
{ label: "Working directory", value: "/workspace/project" },
|
||||
{ label: "Visibility", value: "inherited" },
|
||||
]),
|
||||
);
|
||||
expect(model.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Command", value: "vp check" }),
|
||||
expect.objectContaining({ label: "Output", value: "all checks passed" }),
|
||||
expect.objectContaining({ label: "Exit", value: "Process exited with code 0" }),
|
||||
expect.objectContaining({ label: "Attempt history" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("exposes file and web result provenance plus dynamic structured data", () => {
|
||||
const fileSearch: OrchestrationV2TurnItem = {
|
||||
...itemBase("file-search"),
|
||||
type: "file_search",
|
||||
pattern: "resolveSession",
|
||||
results: [{ fileName: "src/session.ts", line: 42, preview: "function resolveSession()" }],
|
||||
};
|
||||
const fileModel = buildThreadActivityInspector(
|
||||
activityFor(fileSearch),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(fileModel.fileLinks).toEqual([
|
||||
{
|
||||
label: "src/session.ts — function resolveSession()",
|
||||
path: "src/session.ts",
|
||||
line: 42,
|
||||
},
|
||||
]);
|
||||
|
||||
const webSearch: OrchestrationV2TurnItem = {
|
||||
...itemBase("web-search"),
|
||||
type: "web_search",
|
||||
patterns: ["Effect Schema docs"],
|
||||
results: [
|
||||
{ title: "Schema", url: "https://effect.website/docs/schema", snippet: "Typed schemas" },
|
||||
],
|
||||
};
|
||||
const webModel = buildThreadActivityInspector(
|
||||
activityFor(webSearch),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(webModel.webLinks).toEqual([
|
||||
{ label: "Schema", url: "https://effect.website/docs/schema" },
|
||||
]);
|
||||
expect(webModel.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Schema", value: "Typed schemas" }),
|
||||
]),
|
||||
);
|
||||
|
||||
const dynamicTool: OrchestrationV2TurnItem = {
|
||||
...itemBase("dynamic"),
|
||||
type: "dynamic_tool",
|
||||
toolName: "custom",
|
||||
input: { nested: { value: 1 } },
|
||||
output: { ok: true },
|
||||
};
|
||||
const dynamicModel = buildThreadActivityInspector(
|
||||
activityFor(dynamicTool),
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(dynamicModel.blocks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ label: "Input", value: expect.stringContaining('"nested"') }),
|
||||
expect.objectContaining({ label: "Output", value: expect.stringContaining('"ok"') }),
|
||||
]),
|
||||
);
|
||||
expect(dynamicModel.structuredDetails).toContain('"type": "dynamic_tool"');
|
||||
});
|
||||
|
||||
it("enables rollback only for the matching ready checkpoint", () => {
|
||||
const checkpointId = CheckpointId.make("checkpoint-1");
|
||||
const scopeId = CheckpointScopeId.make("scope-1");
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("checkpoint"),
|
||||
type: "checkpoint",
|
||||
checkpointId,
|
||||
scopeId,
|
||||
files: [{ path: "src/main.ts", kind: "modified", additions: 2, deletions: 1 }],
|
||||
};
|
||||
const checkpoint = { id: checkpointId, scopeId, status: "ready" } as never;
|
||||
const model = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
checkpoint,
|
||||
},
|
||||
sourceThreadId,
|
||||
);
|
||||
|
||||
expect(model.canRollback).toBe(true);
|
||||
expect(model.rollbackTarget).toEqual({
|
||||
threadId: sourceThreadId,
|
||||
checkpointId,
|
||||
scopeId,
|
||||
});
|
||||
|
||||
const inheritedModel = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
checkpoint,
|
||||
},
|
||||
ThreadId.make("child-thread"),
|
||||
);
|
||||
expect(inheritedModel.canRollback).toBe(false);
|
||||
expect(inheritedModel.rollbackTarget).toBeNull();
|
||||
});
|
||||
|
||||
it("prefers live subagent progress from supporting state", () => {
|
||||
const item: OrchestrationV2TurnItem = {
|
||||
...itemBase("subagent"),
|
||||
type: "subagent",
|
||||
subagentId: nodeId,
|
||||
origin: "provider_native",
|
||||
driver: ProviderDriverKind.make("claude"),
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
childThreadId: null,
|
||||
prompt: "Audit the reducer",
|
||||
progress: "Starting",
|
||||
result: null,
|
||||
};
|
||||
const model = buildThreadActivityInspector(
|
||||
activityFor(item),
|
||||
{
|
||||
...EMPTY_V2_ITEM_SUPPORT,
|
||||
item,
|
||||
subagent: {
|
||||
origin: "provider_native",
|
||||
status: "running",
|
||||
progress: "Reading projection tests",
|
||||
result: null,
|
||||
} as never,
|
||||
},
|
||||
sourceThreadId,
|
||||
);
|
||||
|
||||
expect(model.fields).toContainEqual({
|
||||
label: "Delegated task",
|
||||
value: "provider native · running",
|
||||
});
|
||||
expect(model.blocks).toContainEqual({
|
||||
label: "Progress",
|
||||
value: "Reading projection tests",
|
||||
monospaced: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
import type { V2ItemSupport } from "@t3tools/client-runtime/state/item-support";
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
import type { ThreadFeedActivity } from "./threadActivity";
|
||||
|
||||
export interface ThreadActivityInspectorField {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface ThreadActivityInspectorBlock {
|
||||
readonly label: string;
|
||||
readonly value: string;
|
||||
readonly monospaced: boolean;
|
||||
}
|
||||
|
||||
export interface ThreadActivityFileLink {
|
||||
readonly label: string;
|
||||
readonly path: string;
|
||||
readonly line?: number;
|
||||
}
|
||||
|
||||
export interface ThreadActivityWebLink {
|
||||
readonly label: string;
|
||||
readonly url: string;
|
||||
}
|
||||
|
||||
export interface ThreadActivityInspectorModel {
|
||||
readonly fields: ReadonlyArray<ThreadActivityInspectorField>;
|
||||
readonly blocks: ReadonlyArray<ThreadActivityInspectorBlock>;
|
||||
readonly fileLinks: ReadonlyArray<ThreadActivityFileLink>;
|
||||
readonly webLinks: ReadonlyArray<ThreadActivityWebLink>;
|
||||
readonly canRollback: boolean;
|
||||
readonly rollbackTarget: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly checkpointId: string;
|
||||
readonly scopeId: string;
|
||||
} | null;
|
||||
readonly structuredDetails: string;
|
||||
}
|
||||
|
||||
function formatStructured(value: unknown): string {
|
||||
if (typeof value === "string") return value;
|
||||
try {
|
||||
return JSON.stringify(value, null, 2) ?? String(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function durationLabel(
|
||||
startedAt: DateTime.Utc | null,
|
||||
completedAt: DateTime.Utc | null,
|
||||
): string | null {
|
||||
if (startedAt === null) return null;
|
||||
const start = DateTime.toEpochMillis(startedAt);
|
||||
const end = completedAt === null ? Date.now() : DateTime.toEpochMillis(completedAt);
|
||||
return formatDuration(Math.max(0, end - start));
|
||||
}
|
||||
|
||||
function addBlock(
|
||||
blocks: ThreadActivityInspectorBlock[],
|
||||
label: string,
|
||||
value: unknown,
|
||||
monospaced = true,
|
||||
): void {
|
||||
if (value === undefined || value === null || value === "") return;
|
||||
blocks.push({ label, value: formatStructured(value), monospaced });
|
||||
}
|
||||
|
||||
export function buildThreadActivityInspector(
|
||||
activity: ThreadFeedActivity,
|
||||
support: V2ItemSupport,
|
||||
currentThreadId: ThreadId,
|
||||
): ThreadActivityInspectorModel {
|
||||
const row = activity.projectedItem;
|
||||
const item = row.item;
|
||||
const fields: ThreadActivityInspectorField[] = [
|
||||
{ label: "Item", value: item.type.replaceAll("_", " ") },
|
||||
{ label: "Status", value: item.status.replaceAll("_", " ") },
|
||||
];
|
||||
const duration = durationLabel(item.startedAt, item.completedAt);
|
||||
if (duration) fields.push({ label: "Duration", value: duration });
|
||||
if (row.visibility !== "local") fields.push({ label: "Visibility", value: row.visibility });
|
||||
if (support.run) fields.push({ label: "Run", value: support.run.status });
|
||||
|
||||
const latestAttempt = support.attempts.at(-1);
|
||||
if (latestAttempt) {
|
||||
fields.push({
|
||||
label: "Attempt",
|
||||
value: `${latestAttempt.attemptOrdinal} · ${latestAttempt.status} · ${latestAttempt.reason.replaceAll("_", " ")}`,
|
||||
});
|
||||
}
|
||||
if (support.node) {
|
||||
fields.push({
|
||||
label: "Node",
|
||||
value: `${support.node.kind.replaceAll("_", " ")} · ${support.node.status}`,
|
||||
});
|
||||
}
|
||||
if (support.providerThread) {
|
||||
fields.push({
|
||||
label: "Provider thread",
|
||||
value: `${support.providerThread.providerInstanceId} · ${support.providerThread.status}`,
|
||||
});
|
||||
}
|
||||
if (support.providerTurn) {
|
||||
fields.push({ label: "Provider turn", value: support.providerTurn.status });
|
||||
}
|
||||
if (support.providerSession) {
|
||||
fields.push({
|
||||
label: "Session",
|
||||
value: `${support.providerSession.status} · ${support.providerSession.model ?? "default model"}`,
|
||||
});
|
||||
fields.push({ label: "Working directory", value: support.providerSession.cwd });
|
||||
}
|
||||
if (support.runtimeRequest) {
|
||||
fields.push({
|
||||
label: "Request",
|
||||
value: `${support.runtimeRequest.status} · ${support.runtimeRequest.responseCapability.type.replaceAll("_", " ")}`,
|
||||
});
|
||||
}
|
||||
|
||||
const blocks: ThreadActivityInspectorBlock[] = [];
|
||||
const fileLinks: ThreadActivityFileLink[] = [];
|
||||
const webLinks: ThreadActivityWebLink[] = [];
|
||||
|
||||
if (support.attempts.length > 1) {
|
||||
addBlock(
|
||||
blocks,
|
||||
"Attempt history",
|
||||
support.attempts
|
||||
.map(
|
||||
(attempt) =>
|
||||
`Attempt ${attempt.attemptOrdinal} · ${attempt.status} · ${attempt.reason.replaceAll("_", " ")}`,
|
||||
)
|
||||
.join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
switch (item.type) {
|
||||
case "reasoning":
|
||||
addBlock(blocks, "Reasoning", item.text, false);
|
||||
break;
|
||||
case "command_execution":
|
||||
addBlock(blocks, "Command", item.input);
|
||||
addBlock(blocks, "Output", item.output);
|
||||
if (item.exitCode !== undefined) {
|
||||
addBlock(blocks, "Exit", `Process exited with code ${item.exitCode}`);
|
||||
}
|
||||
break;
|
||||
case "file_change":
|
||||
fileLinks.push({ label: item.fileName, path: item.fileName });
|
||||
if (item.additions !== undefined || item.deletions !== undefined) {
|
||||
fields.push({
|
||||
label: "Changes",
|
||||
value: `+${item.additions ?? 0} −${item.deletions ?? 0}`,
|
||||
});
|
||||
}
|
||||
addBlock(blocks, "Patch", item.diffStr);
|
||||
addBlock(blocks, "Before", item.oldStr);
|
||||
addBlock(blocks, "After", item.newStr);
|
||||
break;
|
||||
case "file_search":
|
||||
addBlock(blocks, "Query", item.pattern);
|
||||
for (const result of item.results ?? []) {
|
||||
fileLinks.push({
|
||||
label: result.preview ? `${result.fileName} — ${result.preview}` : result.fileName,
|
||||
path: result.fileName,
|
||||
...(result.line === undefined ? {} : { line: result.line }),
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "web_search":
|
||||
addBlock(blocks, "Queries", item.patterns?.join("\n"));
|
||||
for (const result of item.results ?? []) {
|
||||
if (result.url) {
|
||||
webLinks.push({
|
||||
label: result.title ?? result.url,
|
||||
url: result.url,
|
||||
});
|
||||
}
|
||||
if (result.snippet)
|
||||
addBlock(blocks, result.title ?? "Search result", result.snippet, false);
|
||||
}
|
||||
break;
|
||||
case "dynamic_tool":
|
||||
addBlock(blocks, "Input", item.input);
|
||||
addBlock(blocks, "Output", item.output);
|
||||
break;
|
||||
case "approval_request":
|
||||
addBlock(blocks, "Prompt", item.prompt, false);
|
||||
break;
|
||||
case "user_input_request":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Questions",
|
||||
item.questions.map((question) => question.question).join("\n"),
|
||||
false,
|
||||
);
|
||||
break;
|
||||
case "checkpoint":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Files",
|
||||
item.files
|
||||
.map((file) => `${file.path} +${file.additions} −${file.deletions} ${file.kind}`)
|
||||
.join("\n"),
|
||||
);
|
||||
break;
|
||||
case "subagent":
|
||||
addBlock(blocks, "Prompt", item.prompt, false);
|
||||
addBlock(blocks, "Progress", support.subagent?.progress ?? item.progress, false);
|
||||
addBlock(blocks, "Result", support.subagent?.result ?? item.result, false);
|
||||
if (support.subagent) {
|
||||
fields.push({
|
||||
label: "Delegated task",
|
||||
value: `${support.subagent.origin.replaceAll("_", " ")} · ${support.subagent.status}`,
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "handoff":
|
||||
addBlock(blocks, "Summary", item.summary, false);
|
||||
fields.push({
|
||||
label: "Handoff",
|
||||
value: `${item.strategy.replaceAll("_", " ")} · ${support.contextHandoff?.status ?? item.status}`,
|
||||
});
|
||||
if (support.contextTransfer) {
|
||||
fields.push({
|
||||
label: "Transfer",
|
||||
value: `${support.contextTransfer.type.replaceAll("_", " ")} · ${support.contextTransfer.status}`,
|
||||
});
|
||||
if (support.contextTransfer.resolution) {
|
||||
fields.push({
|
||||
label: "Context",
|
||||
value: support.contextTransfer.resolution.strategy.replaceAll("_", " "),
|
||||
});
|
||||
}
|
||||
}
|
||||
break;
|
||||
case "error":
|
||||
addBlock(blocks, "Error", item.failure.message, false);
|
||||
if (item.failure.code) fields.push({ label: "Code", value: item.failure.code });
|
||||
if (item.failure.retryable !== null) {
|
||||
fields.push({ label: "Retryable", value: item.failure.retryable ? "yes" : "no" });
|
||||
}
|
||||
break;
|
||||
case "proposed_plan":
|
||||
addBlock(blocks, "Plan", item.markdown, false);
|
||||
break;
|
||||
case "todo_list":
|
||||
addBlock(
|
||||
blocks,
|
||||
"Tasks",
|
||||
item.steps
|
||||
.map((step) => `${step.status === "completed" ? "✓" : "○"} ${step.text}`)
|
||||
.join("\n"),
|
||||
false,
|
||||
);
|
||||
addBlock(blocks, "Explanation", item.explanation, false);
|
||||
break;
|
||||
case "compaction":
|
||||
addBlock(blocks, "Summary", item.summary, false);
|
||||
if (item.beforeTokenCount !== undefined || item.afterTokenCount !== undefined) {
|
||||
fields.push({
|
||||
label: "Context tokens",
|
||||
value: `${item.beforeTokenCount ?? "?"} → ${item.afterTokenCount ?? "?"}`,
|
||||
});
|
||||
}
|
||||
break;
|
||||
case "run_interrupt_request":
|
||||
case "run_interrupt_result":
|
||||
addBlock(blocks, "Message", item.message, false);
|
||||
break;
|
||||
case "fork":
|
||||
case "thread_created":
|
||||
case "user_message":
|
||||
case "assistant_message":
|
||||
break;
|
||||
}
|
||||
|
||||
const checkpoint =
|
||||
item.type === "checkpoint" && row.sourceThreadId === currentThreadId
|
||||
? support.checkpoint
|
||||
: null;
|
||||
return {
|
||||
fields,
|
||||
blocks,
|
||||
fileLinks,
|
||||
webLinks,
|
||||
canRollback: checkpoint?.status === "ready",
|
||||
rollbackTarget:
|
||||
checkpoint?.status === "ready"
|
||||
? {
|
||||
threadId: row.sourceThreadId,
|
||||
checkpointId: checkpoint.id,
|
||||
scopeId: checkpoint.scopeId,
|
||||
}
|
||||
: null,
|
||||
structuredDetails: formatStructured({
|
||||
visibility: row.visibility,
|
||||
sourceThreadId: row.sourceThreadId,
|
||||
sourceItemId: row.sourceItemId,
|
||||
item,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,11 +1,5 @@
|
||||
import type { VcsRefTarget } from "@t3tools/client-runtime/state/vcs";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
OrchestrationThread,
|
||||
ThreadId,
|
||||
VcsListRefsResult,
|
||||
VcsRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentId, ThreadId, VcsListRefsResult, VcsRef } from "@t3tools/contracts";
|
||||
import {
|
||||
createThreadSearchResultsAtomFamily,
|
||||
makeThreadSearchKey,
|
||||
@@ -21,7 +15,6 @@ import { appAtomRegistry } from "./atom-registry";
|
||||
import { orchestrationEnvironment } from "./orchestration";
|
||||
import { projectEnvironment } from "./projects";
|
||||
import { useEnvironmentQuery } from "./query";
|
||||
import { useEnvironmentThread } from "./threads";
|
||||
import { vcsEnvironment } from "./vcs";
|
||||
import {
|
||||
buildCheckpointDiffTargets,
|
||||
@@ -50,13 +43,6 @@ const threadSearchResultsAtom = createThreadSearchResultsAtomFamily({
|
||||
labelPrefix: "mobile:thread-search",
|
||||
});
|
||||
|
||||
export interface ThreadDetailView {
|
||||
readonly data: OrchestrationThread | null;
|
||||
readonly error: string | null;
|
||||
readonly isPending: boolean;
|
||||
readonly isDeleted: boolean;
|
||||
}
|
||||
|
||||
export interface ComposerPathSearchTarget {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
@@ -103,19 +89,6 @@ export function useThreadSearch(
|
||||
};
|
||||
}
|
||||
|
||||
export function useThreadDetail(
|
||||
environmentId: EnvironmentId | null,
|
||||
threadId: ThreadId | null,
|
||||
): ThreadDetailView {
|
||||
const state = useEnvironmentThread(environmentId, threadId);
|
||||
return {
|
||||
data: Option.getOrNull(state.data),
|
||||
error: Option.getOrNull(state.error),
|
||||
isPending: state.status === "synchronizing",
|
||||
isDeleted: state.status === "deleted",
|
||||
};
|
||||
}
|
||||
|
||||
export function useBranches(input: {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly cwd: string | null;
|
||||
|
||||
@@ -38,8 +38,9 @@ export function useEnvironmentThread(
|
||||
? environmentThreads.stateAtom(environmentId, threadId)
|
||||
: EMPTY_THREAD_STATE_ATOM,
|
||||
);
|
||||
return Option.getOrElse(
|
||||
const state = Option.getOrElse(
|
||||
AsyncResult.value(result),
|
||||
() => EMPTY_ENVIRONMENT_THREAD_STATE,
|
||||
) as EnvironmentThreadState;
|
||||
return state;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
|
||||
import { deriveThreadTitleFromPrompt } from "../lib/projectThreadStartTurn";
|
||||
import {
|
||||
flattenQueuedThreadMessages,
|
||||
type QueuedThreadCreation,
|
||||
@@ -26,7 +26,7 @@ export function usePendingNewTasks(): ReadonlyArray<PendingNewTask> {
|
||||
tasks.push({
|
||||
message,
|
||||
creation: message.creation,
|
||||
title: deriveThreadTitleFromPrompt(message.text),
|
||||
title: deriveThreadTitleSeed({ text: message.text, attachments: message.attachments }),
|
||||
});
|
||||
}
|
||||
tasks.sort((left, right) => right.message.createdAt.localeCompare(left.message.createdAt));
|
||||
|
||||
@@ -1,26 +1,23 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
|
||||
import { type ProviderApprovalDecision, type RuntimeRequestId } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
derivePendingThreadRequests,
|
||||
type ThreadUserInputQuestion,
|
||||
} from "@t3tools/client-runtime/state/thread-requests";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { threadEnvironment } from "../state/threads";
|
||||
import { scopedRequestKey } from "../lib/scopedEntities";
|
||||
import {
|
||||
buildPendingUserInputAnswers,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
setPendingUserInputCustomAnswer,
|
||||
sortThreadActivities,
|
||||
togglePendingUserInputOptionSelection,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../lib/threadActivity";
|
||||
import { appAtomRegistry } from "./atom-registry";
|
||||
import { useSelectedThreadDetail } from "./use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "./use-thread-detail";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
import { useAtomCommand } from "./use-atom-command";
|
||||
|
||||
@@ -30,7 +27,7 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
|
||||
|
||||
function setUserInputDraftOption(
|
||||
requestKey: string,
|
||||
question: UserInputQuestion,
|
||||
question: ThreadUserInputQuestion,
|
||||
label: string,
|
||||
): void {
|
||||
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
|
||||
@@ -75,27 +72,21 @@ export function useSelectedThreadRequests() {
|
||||
"thread user input response",
|
||||
);
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThread = useSelectedThreadDetail();
|
||||
const selectedThread = useSelectedThreadProjection();
|
||||
const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
|
||||
null,
|
||||
);
|
||||
const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
|
||||
const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
|
||||
|
||||
// Sort once; both derivations expect the same lifecycle ordering.
|
||||
const sortedActivities = useMemo(
|
||||
() => (selectedThread ? sortThreadActivities(selectedThread.activities) : []),
|
||||
const pendingRequests = useMemo(
|
||||
() =>
|
||||
selectedThread === null
|
||||
? { approvals: [], userInputs: [] }
|
||||
: derivePendingThreadRequests(selectedThread.projection),
|
||||
[selectedThread],
|
||||
);
|
||||
const activePendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingApprovals = pendingRequests.approvals;
|
||||
const activePendingApproval = activePendingApprovals[0] ?? null;
|
||||
const activePendingUserInputs = useMemo(
|
||||
() => derivePendingUserInputs(sortedActivities),
|
||||
[sortedActivities],
|
||||
);
|
||||
const activePendingUserInputs = pendingRequests.userInputs;
|
||||
const activePendingUserInput = activePendingUserInputs[0] ?? null;
|
||||
const activePendingUserInputDrafts =
|
||||
activePendingUserInput && selectedThreadShell
|
||||
@@ -108,7 +99,7 @@ export function useSelectedThreadRequests() {
|
||||
: null;
|
||||
|
||||
const onSelectUserInputOption = useCallback(
|
||||
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
|
||||
(requestId: RuntimeRequestId, question: ThreadUserInputQuestion, label: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -120,7 +111,7 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onChangeUserInputCustomAnswer = useCallback(
|
||||
(requestId: ApprovalRequestId, questionId: string, customAnswer: string) => {
|
||||
(requestId: RuntimeRequestId, questionId: string, customAnswer: string) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
@@ -132,10 +123,16 @@ export function useSelectedThreadRequests() {
|
||||
);
|
||||
|
||||
const onRespondToApproval = useCallback(
|
||||
async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {
|
||||
async (requestId: RuntimeRequestId, decision: ProviderApprovalDecision) => {
|
||||
if (!selectedThreadShell) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
activePendingApprovals.find((approval) => approval.requestId === requestId)
|
||||
?.responseCapability !== "live"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setRespondingApprovalId(requestId);
|
||||
const result = await respondToApproval({
|
||||
@@ -149,11 +146,16 @@ export function useSelectedThreadRequests() {
|
||||
setRespondingApprovalId((current) => (current === requestId ? null : current));
|
||||
return result;
|
||||
},
|
||||
[respondToApproval, selectedThreadShell],
|
||||
[activePendingApprovals, respondToApproval, selectedThreadShell],
|
||||
);
|
||||
|
||||
const onSubmitUserInput = useCallback(async () => {
|
||||
if (!selectedThreadShell || !activePendingUserInput || !activePendingUserInputAnswers) {
|
||||
if (
|
||||
!selectedThreadShell ||
|
||||
!activePendingUserInput ||
|
||||
activePendingUserInput.responseCapability !== "live" ||
|
||||
!activePendingUserInputAnswers
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import { useMemo } from "react";
|
||||
|
||||
import { useSelectedThreadDetail } from "./use-thread-detail";
|
||||
import { useSelectedThreadProjection } from "./use-thread-detail";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
import { resolvePreferredThreadWorktreePath } from "../features/terminal/terminalLaunchContext";
|
||||
|
||||
export function useSelectedThreadWorktree() {
|
||||
const { selectedThread, selectedThreadProject } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const selectedThreadDetail = useSelectedThreadProjection();
|
||||
const detailWorktreePath = selectedThreadDetail?.projection.thread.worktreePath ?? null;
|
||||
|
||||
const selectedThreadWorktreePath = useMemo(
|
||||
() =>
|
||||
resolvePreferredThreadWorktreePath({
|
||||
threadShellWorktreePath: selectedThread?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
|
||||
threadDetailWorktreePath: detailWorktreePath,
|
||||
}),
|
||||
[selectedThread?.worktreePath, selectedThreadDetail?.worktreePath],
|
||||
[detailWorktreePath, selectedThread?.worktreePath],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
deriveThreadActivityRun,
|
||||
deriveThreadRuntime,
|
||||
threadRuntimeHasInterruptibleRun,
|
||||
} from "@t3tools/client-runtime/state/thread-execution";
|
||||
import { useCallback, useEffect, useMemo } from "react";
|
||||
|
||||
import {
|
||||
@@ -37,7 +43,10 @@ import {
|
||||
useComposerDraft,
|
||||
} from "./use-composer-drafts";
|
||||
import { setPendingConnectionError } from "../state/use-remote-environment-registry";
|
||||
import { useSelectedThreadDetail } from "../state/use-thread-detail";
|
||||
import {
|
||||
useSelectedThreadProjection,
|
||||
useSelectedThreadVisibleTurnItems,
|
||||
} from "../state/use-thread-detail";
|
||||
import { useThreadSelection } from "../state/use-thread-selection";
|
||||
import { enqueueThreadOutboxMessage } from "./thread-outbox";
|
||||
import { useThreadOutboxMessages } from "./use-thread-outbox";
|
||||
@@ -75,7 +84,8 @@ export function useThreadDraftForThread(input: {
|
||||
|
||||
export function useThreadComposerState() {
|
||||
const { selectedThread: selectedThreadShell } = useThreadSelection();
|
||||
const selectedThreadDetail = useSelectedThreadDetail();
|
||||
const selectedThreadProjection = useSelectedThreadProjection();
|
||||
const selectedThreadVisibleTurnItems = useSelectedThreadVisibleTurnItems();
|
||||
const composerDrafts = useAtomValue(composerDraftsAtom);
|
||||
const queuedMessagesByThreadKey = useThreadOutboxMessages();
|
||||
|
||||
@@ -91,43 +101,59 @@ export function useThreadComposerState() {
|
||||
[queuedMessagesByThreadKey, selectedThreadKey],
|
||||
);
|
||||
const selectedThreadFeed = useMemo(
|
||||
() => (selectedThreadDetail ? buildThreadFeed(selectedThreadDetail) : []),
|
||||
[selectedThreadDetail],
|
||||
() => buildThreadFeed(selectedThreadVisibleTurnItems),
|
||||
[selectedThreadVisibleTurnItems],
|
||||
);
|
||||
|
||||
const selectedDraft = selectedThreadKey ? composerDrafts[selectedThreadKey] : null;
|
||||
const draftMessage = selectedDraft?.text ?? "";
|
||||
const draftAttachments = selectedDraft?.attachments ?? [];
|
||||
const selectedThreadQueueCount = selectedThreadQueuedMessages.length;
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const selectedThread = selectedThreadShell;
|
||||
const modelSelection = selectedDraft?.modelSelection ?? selectedThread?.modelSelection ?? null;
|
||||
const runtimeMode = selectedDraft?.runtimeMode ?? selectedThread?.runtimeMode ?? null;
|
||||
const interactionMode = selectedDraft?.interactionMode ?? selectedThread?.interactionMode ?? null;
|
||||
const selectedThreadRuntime = useMemo(
|
||||
() =>
|
||||
selectedThreadProjection
|
||||
? deriveThreadRuntime(selectedThreadProjection.projection)
|
||||
: (selectedThreadShell?.runtime ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.runtime],
|
||||
);
|
||||
const selectedThreadActivityRun = useMemo(
|
||||
() =>
|
||||
selectedThreadProjection
|
||||
? deriveThreadActivityRun(selectedThreadProjection.projection)
|
||||
: (selectedThreadShell?.latestRun ?? null),
|
||||
[selectedThreadProjection, selectedThreadShell?.latestRun],
|
||||
);
|
||||
|
||||
const selectedThreadSessionActivity = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread?.session) {
|
||||
if (!selectedThreadRuntime) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
orchestrationStatus: selectedThread.session.status,
|
||||
activeTurnId: selectedThread.session.activeTurnId ?? undefined,
|
||||
orchestrationStatus: selectedThreadRuntime.status,
|
||||
activeRunId: selectedThreadRuntime.activeRunId ?? undefined,
|
||||
};
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
}, [selectedThreadRuntime]);
|
||||
|
||||
const activeWorkStartedAt = useMemo(() => {
|
||||
const selectedThread = selectedThreadDetail ?? selectedThreadShell;
|
||||
if (!selectedThread) {
|
||||
if (!selectedThreadShell) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return deriveActiveWorkStartedAt(
|
||||
selectedThread.latestTurn,
|
||||
selectedThreadActivityRun,
|
||||
selectedThreadSessionActivity,
|
||||
null,
|
||||
);
|
||||
}, [selectedThreadDetail, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
}, [selectedThreadActivityRun, selectedThreadSessionActivity, selectedThreadShell]);
|
||||
|
||||
const activeThreadBusy = threadRuntimeIsActive(selectedThreadRuntime);
|
||||
const interruptibleRunId = threadRuntimeHasInterruptibleRun(selectedThreadRuntime)
|
||||
? (selectedThreadRuntime?.activeRunId ?? null)
|
||||
: null;
|
||||
|
||||
const onSendMessage = useCallback(async () => {
|
||||
if (!selectedThreadShell) {
|
||||
@@ -136,7 +162,7 @@ export function useThreadComposerState() {
|
||||
|
||||
const threadKey = scopedThreadKey(selectedThreadShell.environmentId, selectedThreadShell.id);
|
||||
const draft = getComposerDraftSnapshot(threadKey);
|
||||
const thread = selectedThreadDetail ?? selectedThreadShell;
|
||||
const thread = selectedThreadShell;
|
||||
const text = draft.text.trim();
|
||||
const attachments = draft.attachments;
|
||||
if (text.length === 0 && attachments.length === 0) {
|
||||
@@ -175,7 +201,7 @@ export function useThreadComposerState() {
|
||||
);
|
||||
});
|
||||
return messageId;
|
||||
}, [selectedThreadDetail, selectedThreadShell]);
|
||||
}, [selectedThreadShell]);
|
||||
|
||||
const onChangeDraftMessage = useCallback(
|
||||
(value: string) => {
|
||||
@@ -297,6 +323,7 @@ export function useThreadComposerState() {
|
||||
|
||||
return {
|
||||
selectedThreadFeed,
|
||||
selectedThreadActivityRun,
|
||||
selectedThreadQueueCount,
|
||||
activeWorkStartedAt,
|
||||
draftMessage,
|
||||
@@ -304,6 +331,8 @@ export function useThreadComposerState() {
|
||||
modelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
activeThreadBusy,
|
||||
interruptibleRunId,
|
||||
onChangeDraftMessage,
|
||||
onPickDraftImages,
|
||||
onPasteIntoDraft,
|
||||
|
||||
@@ -1,9 +1,18 @@
|
||||
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import * as Option from "effect/Option";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentThread } from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentId, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { useEnvironmentThread } from "./threads";
|
||||
import { environmentThreadDetails, useEnvironmentThread } from "./threads";
|
||||
import { useThreadSelection } from "./use-thread-selection";
|
||||
|
||||
const EMPTY_THREAD_PROJECTION_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(
|
||||
Atom.withLabel("mobile-thread-projection:empty"),
|
||||
);
|
||||
const EMPTY_VISIBLE_TURN_ITEMS_ATOM = Atom.make<
|
||||
OrchestrationV2ThreadProjection["visibleTurnItems"]
|
||||
>(Object.freeze([])).pipe(Atom.withLabel("mobile-thread-visible-turn-items:empty"));
|
||||
|
||||
export interface ThreadDetailTarget {
|
||||
readonly environmentId: EnvironmentId | null;
|
||||
readonly threadId: ThreadId | null;
|
||||
@@ -21,6 +30,42 @@ export function useSelectedThreadDetailState() {
|
||||
});
|
||||
}
|
||||
|
||||
export function useSelectedThreadDetail() {
|
||||
return Option.getOrNull(useSelectedThreadDetailState().data);
|
||||
export function useThreadProjection(target: ThreadDetailTarget): EnvironmentThread | null {
|
||||
return useAtomValue(
|
||||
target.environmentId === null || target.threadId === null
|
||||
? EMPTY_THREAD_PROJECTION_ATOM
|
||||
: environmentThreadDetails.threadAtom({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function useSelectedThreadProjection(): EnvironmentThread | null {
|
||||
const { selectedThread } = useThreadSelection();
|
||||
return useThreadProjection({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
export function useThreadVisibleTurnItems(
|
||||
target: ThreadDetailTarget,
|
||||
): OrchestrationV2ThreadProjection["visibleTurnItems"] {
|
||||
return useAtomValue(
|
||||
target.environmentId === null || target.threadId === null
|
||||
? EMPTY_VISIBLE_TURN_ITEMS_ATOM
|
||||
: environmentThreadDetails.visibleTurnItemsAtom({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.threadId,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function useSelectedThreadVisibleTurnItems(): OrchestrationV2ThreadProjection["visibleTurnItems"] {
|
||||
const { selectedThread } = useThreadSelection();
|
||||
return useThreadVisibleTurnItems({
|
||||
environmentId: selectedThread?.environmentId ?? null,
|
||||
threadId: selectedThread?.id ?? null,
|
||||
});
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
import {
|
||||
threadRuntimeIsActive,
|
||||
type EnvironmentProject,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";
|
||||
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -221,6 +223,7 @@ export function useThreadOutboxDrain(): void {
|
||||
environmentId: queuedMessage.environmentId,
|
||||
input: {
|
||||
commandId: queuedMessage.commandId,
|
||||
creationSource: "mobile",
|
||||
threadId: queuedMessage.threadId,
|
||||
message: {
|
||||
messageId: queuedMessage.messageId,
|
||||
@@ -229,9 +232,14 @@ export function useThreadOutboxDrain(): void {
|
||||
attachments: toUploadChatImageAttachments(queuedMessage.attachments),
|
||||
},
|
||||
modelSelection: settings.modelSelection,
|
||||
titleSeed: deriveThreadTitleSeed({
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
}),
|
||||
runtimeMode: settings.runtimeMode,
|
||||
interactionMode: settings.interactionMode,
|
||||
createdAt: queuedMessage.createdAt,
|
||||
dispatchMode: "start",
|
||||
},
|
||||
});
|
||||
return completeDelivery(deliveryResult);
|
||||
@@ -314,7 +322,7 @@ export function useThreadOutboxDrain(): void {
|
||||
threadExists: thread !== undefined,
|
||||
shellStatus,
|
||||
environmentConnected: environment?.connectionState === "connected",
|
||||
threadBusy: thread?.session?.status === "running" || thread?.session?.status === "starting",
|
||||
threadBusy: threadRuntimeIsActive(thread?.runtime),
|
||||
});
|
||||
if (deliveryAction === "wait") {
|
||||
continue;
|
||||
|
||||
@@ -2,12 +2,20 @@ import { useRoute, type RouteProp } from "@react-navigation/native";
|
||||
import { useMemo, useRef } from "react";
|
||||
import {
|
||||
EnvironmentId,
|
||||
type OrchestrationThread,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadProjection,
|
||||
type OrchestrationV2ThreadShell,
|
||||
type ScopedProjectRef,
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
deriveLatestThreadRun,
|
||||
deriveThreadRuntime,
|
||||
} from "@t3tools/client-runtime/state/thread-execution";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import { useProject, useThreadShell } from "../state/entities";
|
||||
@@ -29,9 +37,11 @@ function firstRouteParam(value: string | string[] | undefined): string | null {
|
||||
return value ?? null;
|
||||
}
|
||||
|
||||
function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["updatedAt"] | null {
|
||||
for (let index = thread.messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = thread.messages[index];
|
||||
function latestUserMessageAt(
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): OrchestrationV2ThreadShell["latestUserMessageAt"] {
|
||||
for (let index = projection.messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = projection.messages[index];
|
||||
if (message?.role === "user") {
|
||||
return message.createdAt;
|
||||
}
|
||||
@@ -40,21 +50,47 @@ function latestUserMessageAt(thread: OrchestrationThread): OrchestrationThread["
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds an optimistic thread shell from the detail projection for the window
|
||||
* where the shell list has not materialized the thread yet (e.g. a thread that
|
||||
* was just created from this device).
|
||||
*/
|
||||
function threadDetailToShell(
|
||||
environmentId: EnvironmentId,
|
||||
thread: OrchestrationThread,
|
||||
projection: OrchestrationV2ThreadProjection,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
environmentId,
|
||||
const thread = projection.thread;
|
||||
const latestRun = deriveLatestThreadRun(projection);
|
||||
const runtime = deriveThreadRuntime(projection);
|
||||
const pendingRequest =
|
||||
projection.runtimeRequests.find((request) => request.status === "pending") ?? null;
|
||||
return presentThreadShell(environmentId, {
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
providerInstanceId: thread.providerInstanceId,
|
||||
modelSelection: thread.modelSelection,
|
||||
runtimeMode: thread.runtimeMode,
|
||||
interactionMode: thread.interactionMode,
|
||||
branch: thread.branch,
|
||||
worktreePath: thread.worktreePath,
|
||||
latestTurn: thread.latestTurn,
|
||||
activeProviderThreadId: thread.activeProviderThreadId,
|
||||
lineage: thread.lineage,
|
||||
forkedFrom: thread.forkedFrom,
|
||||
createdBy: thread.createdBy,
|
||||
creationSource: thread.creationSource,
|
||||
latestRunId: latestRun?.runId ?? null,
|
||||
activeRunId: runtime?.activeRunId ?? null,
|
||||
status: runtime?.status ?? "idle",
|
||||
pendingRuntimeRequest:
|
||||
pendingRequest === null
|
||||
? null
|
||||
: { id: pendingRequest.id, kind: pendingRequest.kind, createdAt: pendingRequest.createdAt },
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: latestUserMessageAt(projection),
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: projection.turnItems.length,
|
||||
visibleItemCount: projection.visibleTurnItems.length,
|
||||
createdAt: thread.createdAt,
|
||||
updatedAt: thread.updatedAt,
|
||||
archivedAt: thread.archivedAt,
|
||||
@@ -62,12 +98,8 @@ function threadDetailToShell(
|
||||
settledAt: thread.settledAt,
|
||||
snoozedUntil: thread.snoozedUntil ?? null,
|
||||
snoozedAt: thread.snoozedAt ?? null,
|
||||
session: thread.session,
|
||||
latestUserMessageAt: latestUserMessageAt(thread),
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
};
|
||||
deletedAt: thread.deletedAt,
|
||||
});
|
||||
}
|
||||
|
||||
function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefined) {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
|
||||
import {
|
||||
EMPTY_V2_ITEM_SUPPORT,
|
||||
resolveV2ItemSupport,
|
||||
v2ItemSupportEqual,
|
||||
type V2ItemSupport,
|
||||
} from "@t3tools/client-runtime/state/item-support";
|
||||
import type { EnvironmentId, ThreadId, TurnItemId } from "@t3tools/contracts";
|
||||
import { Atom } from "effect/unstable/reactivity";
|
||||
|
||||
import { environmentThreadDetails } from "./threads";
|
||||
|
||||
interface ItemSupportTarget {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly itemId: TurnItemId;
|
||||
}
|
||||
|
||||
function supportKey(target: ItemSupportTarget): string {
|
||||
return JSON.stringify(target);
|
||||
}
|
||||
|
||||
function parseSupportKey(key: string): ItemSupportTarget {
|
||||
return JSON.parse(key) as ItemSupportTarget;
|
||||
}
|
||||
|
||||
const itemSupportAtomFamily = Atom.family((key: string) => {
|
||||
const target = parseSupportKey(key);
|
||||
const ref = scopeThreadRef(target.environmentId, target.threadId);
|
||||
let previous = EMPTY_V2_ITEM_SUPPORT;
|
||||
return Atom.make((get): V2ItemSupport => {
|
||||
const scoped = get(environmentThreadDetails.threadAtom(ref));
|
||||
if (scoped === null) return EMPTY_V2_ITEM_SUPPORT;
|
||||
const next = resolveV2ItemSupport(scoped.projection, target.itemId);
|
||||
if (v2ItemSupportEqual(previous, next)) return previous;
|
||||
previous = next;
|
||||
return next;
|
||||
}).pipe(Atom.withLabel(`mobile-v2-item-support:${key}`));
|
||||
});
|
||||
|
||||
export function useV2ItemSupport(target: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly sourceThreadId: ThreadId;
|
||||
readonly sourceItemId: TurnItemId;
|
||||
}): V2ItemSupport {
|
||||
return useAtomValue(
|
||||
itemSupportAtomFamily(
|
||||
supportKey({
|
||||
environmentId: target.environmentId,
|
||||
threadId: target.sourceThreadId,
|
||||
itemId: target.sourceItemId,
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import {
|
||||
presentThreadShell,
|
||||
type EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
ThreadId,
|
||||
type OrchestrationV2ThreadShell,
|
||||
} from "@t3tools/contracts";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
|
||||
const DEFAULT_TIMESTAMP = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
export function makeRawThreadShell(
|
||||
input: Partial<OrchestrationV2ThreadShell> = {},
|
||||
): OrchestrationV2ThreadShell {
|
||||
const id = input.id ?? ThreadId.make("thread-test");
|
||||
const providerInstanceId = input.providerInstanceId ?? ProviderInstanceId.make("codex");
|
||||
const now = DateTime.makeUnsafe(DEFAULT_TIMESTAMP);
|
||||
return {
|
||||
id,
|
||||
projectId: ProjectId.make("project-test"),
|
||||
title: "Thread",
|
||||
providerInstanceId,
|
||||
modelSelection: { instanceId: providerInstanceId, model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
activeProviderThreadId: null,
|
||||
lineage: { rootThreadId: id, parentThreadId: null, relationshipToParent: null },
|
||||
forkedFrom: null,
|
||||
createdBy: "user",
|
||||
creationSource: "mobile",
|
||||
latestRunId: null,
|
||||
activeRunId: null,
|
||||
status: "idle",
|
||||
pendingRuntimeRequest: null,
|
||||
latestVisibleMessage: null,
|
||||
latestUserMessageAt: null,
|
||||
hasActionableProposedPlan: false,
|
||||
itemCount: 0,
|
||||
visibleItemCount: 0,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
export function makeThreadShellFixture(
|
||||
overrides: Partial<EnvironmentThreadShell> = {},
|
||||
): EnvironmentThreadShell {
|
||||
const environmentId = overrides.environmentId ?? EnvironmentId.make("environment-test");
|
||||
const raw = makeRawThreadShell({
|
||||
id: overrides.id,
|
||||
projectId: overrides.projectId,
|
||||
title: overrides.title,
|
||||
providerInstanceId: overrides.providerInstanceId,
|
||||
modelSelection: overrides.modelSelection,
|
||||
runtimeMode: overrides.runtimeMode,
|
||||
interactionMode: overrides.interactionMode,
|
||||
branch: overrides.branch,
|
||||
worktreePath: overrides.worktreePath,
|
||||
});
|
||||
return { ...presentThreadShell(environmentId, raw), ...overrides };
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
# Server
|
||||
|
||||
Node.js WebSocket server for the T3 Code app.
|
||||
@@ -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>;
|
||||
@@ -1,578 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CodexSettings,
|
||||
ProviderDriverKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as ManagedRuntime from "effect/ManagedRuntime";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schedule from "effect/Schedule";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as CheckpointStore from "../src/checkpointing/CheckpointStore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
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,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
RuntimeReceiptBus,
|
||||
type OrchestrationRuntimeReceipt,
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import * as WorkspaceEntries from "../src/workspace/WorkspaceEntries.ts";
|
||||
import * as WorkspacePaths from "../src/workspace/WorkspacePaths.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
import * as AgentAwarenessRelay from "../src/relay/AgentAwarenessRelay.ts";
|
||||
|
||||
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return NodeChildProcess.execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
|
||||
runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const { join } = yield* Path.Path;
|
||||
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
|
||||
runGit(cwd, ["add", "."]);
|
||||
runGit(cwd, ["commit", "-m", "Initial"]);
|
||||
});
|
||||
|
||||
export function gitRefExists(cwd: string, ref: string): boolean {
|
||||
try {
|
||||
runGit(cwd, ["show-ref", "--verify", "--quiet", ref]);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
|
||||
return runGit(cwd, ["show", `${ref}:${filePath}`]);
|
||||
}
|
||||
|
||||
class WaitForTimeoutError extends Schema.TaggedErrorClass<WaitForTimeoutError>()(
|
||||
"WaitForTimeoutError",
|
||||
{
|
||||
description: Schema.String,
|
||||
},
|
||||
) {}
|
||||
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<A, never>;
|
||||
function waitFor<A, B extends A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => value is B,
|
||||
description: string,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<B, never>;
|
||||
function waitFor<A, E>(
|
||||
read: Effect.Effect<A, E>,
|
||||
predicate: (value: A) => boolean,
|
||||
description: string,
|
||||
timeoutMs = 40_000,
|
||||
): Effect.Effect<A, never> {
|
||||
const RETRY_SIGNAL = "wait_for_retry";
|
||||
const retryIntervalMs = 10;
|
||||
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
|
||||
const retrySchedule = Schedule.spaced(`${retryIntervalMs} millis`);
|
||||
|
||||
return read.pipe(
|
||||
Effect.filterOrFail(predicate, () => RETRY_SIGNAL),
|
||||
Effect.retry({
|
||||
schedule: retrySchedule,
|
||||
times: maxRetries,
|
||||
while: (error) => error === RETRY_SIGNAL,
|
||||
}),
|
||||
Effect.mapError((error) =>
|
||||
error === RETRY_SIGNAL ? new WaitForTimeoutError({ description }) : error,
|
||||
),
|
||||
Effect.orDie,
|
||||
);
|
||||
}
|
||||
|
||||
class OrchestrationHarnessRuntimeError extends Schema.TaggedErrorClass<OrchestrationHarnessRuntimeError>()(
|
||||
"OrchestrationHarnessRuntimeError",
|
||||
{
|
||||
operation: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {}
|
||||
|
||||
const tryRuntimePromise = <A>(operation: string, run: () => Promise<A>) =>
|
||||
Effect.tryPromise({
|
||||
try: run,
|
||||
catch: (cause) => new OrchestrationHarnessRuntimeError({ operation, cause }),
|
||||
});
|
||||
|
||||
export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
readonly checkpointStore: CheckpointStore.CheckpointStore["Service"];
|
||||
readonly checkpointRepository: ProjectionCheckpointRepository["Service"];
|
||||
readonly pendingApprovalRepository: ProjectionPendingApprovalRepository["Service"];
|
||||
readonly waitForThread: (
|
||||
threadId: string,
|
||||
predicate: (thread: OrchestrationThread) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<OrchestrationThread, never>;
|
||||
readonly waitForDomainEvent: (
|
||||
predicate: (event: OrchestrationEvent) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
|
||||
readonly waitForPendingApproval: (
|
||||
requestId: string,
|
||||
predicate: (row: {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
}) => boolean,
|
||||
timeoutMs?: number,
|
||||
) => Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
readonly waitForReceipt: {
|
||||
(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
};
|
||||
readonly drainProviderRuntime: Effect.Effect<void>;
|
||||
readonly drainCheckpointReactor: Effect.Effect<void>;
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
: yield* makeTestProviderAdapterHarness({
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(
|
||||
ProviderAdapterRegistry,
|
||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
||||
)
|
||||
: null;
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
});
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
);
|
||||
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
|
||||
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
|
||||
yield* initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexSettings = yield* decodeCodexSettings({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
return makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: codexAdapter,
|
||||
});
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
);
|
||||
const providerRegistryLayer = makeProviderRegistryLayer();
|
||||
|
||||
const checkpointStoreLayer = CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
projectionSnapshotQueryLayer,
|
||||
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusTest,
|
||||
).pipe(
|
||||
Layer.provideMerge(ThreadBackgroundLiveness.layer),
|
||||
Layer.provideMerge(ThreadPlanProgress.layer),
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.succeed({ branch: input.newBranch }),
|
||||
});
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitWorkflowLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
refreshStatus: () => Effect.die("refreshStatus should not be called in this test"),
|
||||
streamStatus: () => Stream.empty,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntries.layer.pipe(
|
||||
Layer.provide(WorkspacePaths.layer),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePaths.layer),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(AgentAwarenessRelay.AgentAwarenessRelay, {
|
||||
publishThread: () => Effect.void,
|
||||
start: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(orchestrationReactorLayer),
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(RepositoryIdentityResolver.layer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
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);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore.CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const runtimeReceiptBus = yield* tryRuntimePromise("load RuntimeReceiptBus service", () =>
|
||||
runtime.runPromise(Effect.service(RuntimeReceiptBus)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
|
||||
yield* Stream.runForEach(runtimeReceiptBus.streamEventsForTest, (receipt) =>
|
||||
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkIn(scope));
|
||||
yield* Effect.sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
|
||||
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
function waitForReceipt(
|
||||
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
|
||||
timeoutMs?: number,
|
||||
) {
|
||||
const readMatchingReceipt = Ref.get(receiptHistory).pipe(
|
||||
Effect.map((history) => history.find(predicate)),
|
||||
);
|
||||
|
||||
return waitFor(
|
||||
readMatchingReceipt,
|
||||
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
|
||||
"runtime receipt",
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown;
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
waitForReceipt,
|
||||
drainProviderRuntime: providerRuntimeIngestion.drain,
|
||||
drainCheckpointReactor: checkpointReactor.drain,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -1,568 +0,0 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
RuntimeSessionId,
|
||||
ProviderSession,
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../src/provider/Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterShape,
|
||||
ProviderThreadSnapshot,
|
||||
ProviderThreadTurnSnapshot,
|
||||
} from "../src/provider/Services/ProviderAdapter.ts";
|
||||
|
||||
export interface TestTurnResponse {
|
||||
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
// Temporary alias while fixtures migrate to the new name.
|
||||
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
readonly queuedResponses: Array<TestTurnResponse>;
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (
|
||||
value === "completed" ||
|
||||
value === "failed" ||
|
||||
value === "interrupted" ||
|
||||
value === "cancelled"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "completed";
|
||||
}
|
||||
|
||||
function mapRequestType(
|
||||
requestKind: unknown,
|
||||
): "command_execution_approval" | "file_change_approval" | "unknown" {
|
||||
if (requestKind === "command") {
|
||||
return "command_execution_approval";
|
||||
}
|
||||
if (requestKind === "file-change") {
|
||||
return "file_change_approval";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
|
||||
if (toolKind === "command") {
|
||||
return "command_execution";
|
||||
}
|
||||
if (toolKind === "file-change") {
|
||||
return "file_change";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
|
||||
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
|
||||
switch (type) {
|
||||
case "turn.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.started",
|
||||
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "turn.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.completed",
|
||||
payload: isRecord(rawEvent.payload)
|
||||
? rawEvent.payload
|
||||
: {
|
||||
state: normalizeTurnState(rawEvent.status),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.delta":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.started",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
status: "completed",
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.requested":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.resolved":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
default:
|
||||
return rawEvent as ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
|
||||
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: ProviderDriverKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return "2026-01-01T00:00:00.000Z";
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderDriverKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
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>>();
|
||||
const approvalResponsesBySession = new Map<
|
||||
ThreadId,
|
||||
Array<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
const nextEventId = (threadId: ThreadId) => {
|
||||
eventCount += 1;
|
||||
return EventId.make(`test-provider:${provider}:${threadId}:${eventCount}`);
|
||||
};
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== provider) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const threadId = input.threadId;
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
...(input.providerInstanceId !== undefined
|
||||
? { providerInstanceId: input.providerInstanceId }
|
||||
: {}),
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
queuedResponses: queuedResponsesForNextSession.splice(0),
|
||||
rollbackCalls: [],
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(provider, input.threadId);
|
||||
}
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for thread ${input.threadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
const assistantDeltas: string[] = [];
|
||||
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: nextEventId(input.threadId),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = normalizeFixtureEvent(rawEvent);
|
||||
const runtimeType = (runtimeEvent as { type: string }).type;
|
||||
if (runtimeType === "content.delta") {
|
||||
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
|
||||
if (typeof payload?.delta === "string") {
|
||||
assistantDeltas.push(payload.delta);
|
||||
}
|
||||
} else if (runtimeType === "message.delta") {
|
||||
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
|
||||
if (typeof legacyDelta === "string") {
|
||||
assistantDeltas.push(legacyDelta);
|
||||
}
|
||||
}
|
||||
if (runtimeEvent.type === "turn.completed") {
|
||||
deferredTurnCompletedEvents.push(runtimeEvent);
|
||||
continue;
|
||||
}
|
||||
|
||||
yield* emit(runtimeEvent);
|
||||
}
|
||||
|
||||
if (response.mutateWorkspace && state.session.cwd) {
|
||||
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
|
||||
}
|
||||
|
||||
const userItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input }],
|
||||
} as const;
|
||||
const assistantText = assistantDeltas.join("");
|
||||
const nextItems: Array<unknown> =
|
||||
assistantText.length > 0
|
||||
? [userItem, { type: "agentMessage", text: assistantText }]
|
||||
: [userItem];
|
||||
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: nextItems,
|
||||
};
|
||||
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: nextEventId(input.threadId),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
yield* emit(completedEvent);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = interruptCallsBySession.get(threadId) ?? [];
|
||||
existing.push(turnId);
|
||||
interruptCallsBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(threadId) ?? [];
|
||||
existing.push({
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers,
|
||||
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.sync(() => {
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.sync(() => {
|
||||
state.rollbackCalls.push(numTurns);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
};
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.sync(() => {
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(threadId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
|
||||
const queueTurnResponseForNextSession = (
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, never> =>
|
||||
Effect.sync(() => {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
const getStartCount = (): number => sessionCount;
|
||||
|
||||
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
|
||||
const calls = interruptCallsBySession.get(threadId);
|
||||
if (!calls) {
|
||||
return [];
|
||||
}
|
||||
return [...calls];
|
||||
};
|
||||
|
||||
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
|
||||
Array.from(sessions.values(), (state) => state.session.threadId);
|
||||
|
||||
const getApprovalResponses = (
|
||||
threadId: ThreadId,
|
||||
): ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(threadId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
return [...responses];
|
||||
};
|
||||
|
||||
return {
|
||||
adapter,
|
||||
provider,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getStartCount,
|
||||
getRollbackCalls,
|
||||
getInterruptCalls,
|
||||
listActiveSessionIds,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -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,162 +0,0 @@
|
||||
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.make(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
export const codexTurnTextFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Ran command",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
type: "turn.started",
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
@@ -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 };
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,386 +0,0 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
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";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
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";
|
||||
import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";
|
||||
|
||||
import {
|
||||
makeTestProviderAdapterHarness,
|
||||
type TestProviderAdapterHarness,
|
||||
type TestTurnResponse,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import {
|
||||
codexTurnApprovalFixture,
|
||||
codexTurnToolFixture,
|
||||
codexTurnTextFixture,
|
||||
} from "./fixtures/providerRuntime.ts";
|
||||
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
|
||||
const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
const cwd = yield* fs.makeTempDirectory();
|
||||
yield* fs.writeFileString(pathService.join(cwd, "README.md"), "v1\n");
|
||||
return cwd;
|
||||
}).pipe(Effect.provide(NodeServices.layer));
|
||||
|
||||
interface IntegrationFixture {
|
||||
readonly cwd: string;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
interface RecordedAnalyticsEvent {
|
||||
readonly event: string;
|
||||
readonly properties: Readonly<Record<string, unknown>> | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 collectEventsDuring = <A, E, R>(
|
||||
stream: Stream.Stream<ProviderRuntimeEvent>,
|
||||
count: number,
|
||||
action: Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
yield* Stream.runForEach(stream, (event) => Queue.offer(queue, event).pipe(Effect.asVoid)).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* action;
|
||||
|
||||
return yield* Effect.forEach(
|
||||
Array.from({ length: count }, () => undefined),
|
||||
() => Queue.take(queue),
|
||||
{ discard: false },
|
||||
);
|
||||
});
|
||||
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
threadId: input.threadId,
|
||||
input: input.userText,
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "hello",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnTextFixture.map((event) => event.type),
|
||||
);
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.providerInstanceId),
|
||||
codexTurnTextFixture.map(() => codexInstanceId),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "make a small change",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnToolFixture.map((event) => event.type),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
firstTurnEvents.map((event) => event.type),
|
||||
codexTurnToolFixture.map((event) => event.type),
|
||||
);
|
||||
|
||||
const secondTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
secondTurnEvents.map((event) => event.type),
|
||||
codexTurnApprovalFixture.map((event) => event.type),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v2\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
writeFileString(join(cwd, "README.md"), "v3\n").pipe(Effect.asVoid, Effect.ignore),
|
||||
},
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
threadId: session.threadId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
|
||||
assert.deepEqual(rollbackCalls, [1]);
|
||||
|
||||
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
|
||||
assert.equal(readme, "v3\n");
|
||||
}).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)),
|
||||
);
|
||||
@@ -16,13 +16,19 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node --watch src/bin.ts",
|
||||
"build:bundle": "vp pack && vp pack src/service-launcher.ts --out-dir dist --no-clean",
|
||||
"record:codex-replay": "bun scripts/record-codex-app-server-replay-fixture.ts",
|
||||
"record:claude-replay": "bun scripts/record-claude-agent-sdk-replay-fixture.ts",
|
||||
"record:cursor-replay": "node --env-file-if-exists=../../.env --experimental-strip-types scripts/record-cursor-agent-sdk-replay-fixture.ts",
|
||||
"build:bundle": "vp pack",
|
||||
"start": "node dist/bin.mjs",
|
||||
"typecheck": "tsgo --noEmit",
|
||||
"test": "vp test run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.205",
|
||||
"@connectrpc/connect": "1.7.0",
|
||||
"@connectrpc/connect-node": "1.7.0",
|
||||
"@cursor/sdk": "1.0.22",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#!/usr/bin/env node
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -11,19 +12,44 @@ import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
|
||||
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitPostSettleMonitorFlow = process.env.T3_ACP_EMIT_POST_SETTLE_MONITOR_FLOW === "1";
|
||||
const emitInTurnTaskOutputThenLateDuplicate =
|
||||
process.env.T3_ACP_EMIT_IN_TURN_TASKOUTPUT_THEN_LATE_DUPLICATE === "1";
|
||||
const injectedReportTriggerPath = process.env.T3_ACP_INJECTED_REPORT_TRIGGER_PATH;
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const emitElicitation = process.env.T3_ACP_EMIT_ELICITATION === "1";
|
||||
const emitUrlElicitation = process.env.T3_ACP_EMIT_URL_ELICITATION === "1";
|
||||
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
|
||||
const emitXAiPromptCompleteThenHang = process.env.T3_ACP_EMIT_XAI_PROMPT_COMPLETE_THEN_HANG === "1";
|
||||
const emitForeignSessionUpdates = process.env.T3_ACP_EMIT_FOREIGN_SESSION_UPDATES === "1";
|
||||
const hangPromptForever = process.env.T3_ACP_HANG_PROMPT_FOREVER === "1";
|
||||
const hangAfterPermission = process.env.T3_ACP_HANG_AFTER_PERMISSION === "1";
|
||||
const hangFirstPromptForever = process.env.T3_ACP_HANG_FIRST_PROMPT_FOREVER === "1";
|
||||
const emitLateUpdateAfterCancel = process.env.T3_ACP_EMIT_LATE_UPDATE_AFTER_CANCEL === "1";
|
||||
const emitTaskBackgroundedAfterCancel =
|
||||
process.env.T3_ACP_EMIT_TASK_BACKGROUNDED_AFTER_CANCEL === "1";
|
||||
const residualCallbackResponseLogPath = process.env.T3_ACP_RESIDUAL_CALLBACK_RESPONSE_LOG_PATH;
|
||||
const residualCallbackTriggerPath = process.env.T3_ACP_RESIDUAL_CALLBACK_TRIGGER_PATH;
|
||||
const exitAfterResidualCallbacks = process.env.T3_ACP_EXIT_AFTER_RESIDUAL_CALLBACKS === "1";
|
||||
const emitRunningCommandThenHang = process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG === "1";
|
||||
const emitRunningCommandThenHangOnFirstPrompt =
|
||||
process.env.T3_ACP_EMIT_RUNNING_COMMAND_THEN_HANG_FIRST_PROMPT === "1";
|
||||
const emitEmptySuccessfulBash = process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH === "1";
|
||||
const emitEmptySuccessfulBashThenHang =
|
||||
process.env.T3_ACP_EMIT_EMPTY_SUCCESSFUL_BASH_THEN_HANG === "1";
|
||||
const exitOnCancel = process.env.T3_ACP_EXIT_ON_CANCEL === "1";
|
||||
const runningCommandIgnoresTerm = process.env.T3_ACP_RUNNING_COMMAND_IGNORE_TERM === "1";
|
||||
const runningCommandPidPath = process.env.T3_ACP_RUNNING_COMMAND_PID_PATH;
|
||||
const runningCommandSeparateSession = process.env.T3_ACP_RUNNING_COMMAND_SEPARATE_SESSION === "1";
|
||||
const exitAfterRunningCommandLaunch = process.env.T3_ACP_EXIT_AFTER_RUNNING_COMMAND_LAUNCH === "1";
|
||||
const omitXAiPromptCompleteStopReason =
|
||||
process.env.T3_ACP_OMIT_XAI_PROMPT_COMPLETE_STOP_REASON === "1";
|
||||
const failLoadSession = process.env.T3_ACP_FAIL_LOAD_SESSION === "1";
|
||||
@@ -40,6 +66,9 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
|
||||
const supportsSessionLifecycle = process.env.T3_ACP_SESSION_LIFECYCLE === "1";
|
||||
const advertisedAuthMethodId = process.env.T3_ACP_AUTH_METHOD_ID?.trim();
|
||||
const requiresAuthentication = process.env.T3_ACP_REQUIRE_AUTH === "1";
|
||||
const permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
@@ -53,6 +82,7 @@ let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
let authenticated = !requiresAuthentication;
|
||||
let promptCount = 0;
|
||||
let overlappingFirstPromptId: string | undefined;
|
||||
const cancelledSessions = new Set<string>();
|
||||
@@ -79,6 +109,11 @@ function writeJsonRpcNotification(method: string, params: unknown): void {
|
||||
process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", method, params })}\n`);
|
||||
}
|
||||
|
||||
function logResidualCallbackResponse(kind: string): void {
|
||||
if (!residualCallbackResponseLogPath) return;
|
||||
NodeFS.appendFileSync(residualCallbackResponseLogPath, `${kind}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
@@ -224,35 +259,6 @@ function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
];
|
||||
}
|
||||
|
||||
function modelConfigOptionsFor(modelId: string): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
const previousModelId = currentModelId;
|
||||
try {
|
||||
currentModelId = modelId;
|
||||
return configOptions().filter(
|
||||
(option) => option.category !== "mode" && option.category !== "model",
|
||||
);
|
||||
} finally {
|
||||
currentModelId = previousModelId;
|
||||
}
|
||||
}
|
||||
|
||||
function availableModels(): ReadonlyArray<{
|
||||
readonly value: string;
|
||||
readonly name: string;
|
||||
readonly configOptions: ReadonlyArray<AcpSchema.SessionConfigOption>;
|
||||
}> {
|
||||
return [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
].map((model) => ({
|
||||
value: model.value,
|
||||
name: model.name,
|
||||
configOptions: modelConfigOptionsFor(model.value),
|
||||
}));
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
@@ -302,19 +308,60 @@ const program = Effect.gen(function* () {
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
agentCapabilities: {
|
||||
loadSession: true,
|
||||
...(supportsSessionLifecycle
|
||||
? {
|
||||
sessionCapabilities: {
|
||||
list: {},
|
||||
fork: {},
|
||||
resume: {},
|
||||
close: {},
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
...(advertisedAuthMethodId
|
||||
? {
|
||||
authMethods: [
|
||||
{
|
||||
id: advertisedAuthMethodId,
|
||||
name: "Mock agent authentication",
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
yield* agent.handleAuthenticate((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (advertisedAuthMethodId && request.methodId !== advertisedAuthMethodId) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
`Unknown mock authentication method: ${request.methodId}`,
|
||||
);
|
||||
}
|
||||
authenticated = true;
|
||||
return {};
|
||||
}),
|
||||
);
|
||||
|
||||
const requireAuthentication = Effect.fn("acpMockAgent.requireAuthentication")(function* () {
|
||||
if (!authenticated) {
|
||||
return yield* AcpError.AcpRequestError.authRequired();
|
||||
}
|
||||
});
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
Effect.gen(function* () {
|
||||
yield* requireAuthentication();
|
||||
return {
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -380,6 +427,52 @@ const program = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleListSessions((request) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireAuthentication();
|
||||
return {
|
||||
sessions: [
|
||||
{
|
||||
sessionId,
|
||||
cwd: request.cwd ?? process.cwd(),
|
||||
title: "Mock session",
|
||||
updatedAt: "1970-01-01T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleForkSession((request) =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireAuthentication();
|
||||
return {
|
||||
sessionId: `${request.sessionId}-fork`,
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleResumeSession(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireAuthentication();
|
||||
return {
|
||||
modes: modeState(),
|
||||
models: modelState(),
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCloseSession(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* requireAuthentication();
|
||||
return {};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionModel((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
|
||||
@@ -437,6 +530,9 @@ const program = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const cancelledSessionId = String(sessionId ?? "mock-session-1");
|
||||
cancelledSessions.add(cancelledSessionId);
|
||||
if (exitOnCancel) {
|
||||
return yield* Effect.sync(() => process.exit(0));
|
||||
}
|
||||
if (emitLateUpdateAfterCancel) {
|
||||
yield* Effect.sleep("50 millis");
|
||||
yield* Effect.sync(() => {
|
||||
@@ -449,14 +545,119 @@ const program = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
}
|
||||
if (emitTaskBackgroundedAfterCancel) {
|
||||
// Grok cancel-as-detach: the foreground command is re-run as a
|
||||
// background task that later completes on its own.
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("_x.ai/task_backgrounded", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "task_backgrounded",
|
||||
tool_call_id: "task-bg-1",
|
||||
task_id: "task-bg-1",
|
||||
command: "sleep 30",
|
||||
},
|
||||
});
|
||||
});
|
||||
yield* Effect.sleep("1200 millis")
|
||||
.pipe(
|
||||
Effect.andThen(
|
||||
Effect.sync(() => {
|
||||
writeJsonRpcNotification("_x.ai/task_completed", {
|
||||
sessionId: cancelledSessionId,
|
||||
update: {
|
||||
sessionUpdate: "task_completed",
|
||||
task_snapshot: { task_id: "task-bg-1", command: "sleep 30" },
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
)
|
||||
.pipe(Effect.forkDetach);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
beginAcpMockPrompt(cancelledSessions, requestedSessionId);
|
||||
promptCount += 1;
|
||||
|
||||
if (residualCallbackTriggerPath !== undefined) {
|
||||
yield* Effect.gen(function* () {
|
||||
while (!(yield* Effect.sync(() => NodeFS.existsSync(residualCallbackTriggerPath)))) {
|
||||
yield* Effect.sleep("20 millis");
|
||||
}
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "residual assistant callback" },
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "residual-tool-call",
|
||||
title: "Residual tool callback",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{ content: "Residual plan callback", priority: "high", status: "pending" },
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
yield* agent.client
|
||||
.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId: "residual-permission",
|
||||
title: "Residual permission callback",
|
||||
},
|
||||
options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }],
|
||||
})
|
||||
.pipe(
|
||||
Effect.exit,
|
||||
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("permission"))),
|
||||
Effect.ignore,
|
||||
Effect.forkDetach,
|
||||
);
|
||||
yield* agent.client
|
||||
.elicit({
|
||||
sessionId: requestedSessionId,
|
||||
message: "Residual elicitation callback",
|
||||
mode: "form",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
approved: { type: "boolean", title: "Approved" },
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.exit,
|
||||
Effect.tap(() => Effect.sync(() => logResidualCallbackResponse("elicitation"))),
|
||||
Effect.ignore,
|
||||
Effect.forkDetach,
|
||||
);
|
||||
if (exitAfterResidualCallbacks) {
|
||||
yield* Effect.sleep("100 millis");
|
||||
return yield* Effect.sync(() => process.exit(0));
|
||||
}
|
||||
}).pipe(Effect.forkDetach);
|
||||
}
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
@@ -518,10 +719,126 @@ const program = Effect.gen(function* () {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (hangPromptForever || (hangFirstPromptForever && promptCount === 1)) {
|
||||
if (
|
||||
hangPromptForever ||
|
||||
(hangFirstPromptForever && promptCount === 1) ||
|
||||
(emitEmptySuccessfulBashThenHang && promptCount === 2)
|
||||
) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
if (
|
||||
emitRunningCommandThenHang ||
|
||||
(emitRunningCommandThenHangOnFirstPrompt && promptCount === 1)
|
||||
) {
|
||||
const toolCallId = "tool-call-running-1";
|
||||
if (runningCommandPidPath !== undefined) {
|
||||
const command = runningCommandIgnoresTerm
|
||||
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"'
|
||||
: 'sleep 120 & child=$!; printf "%s %s\\n" "$$" "$child" > "$1"; wait "$child"';
|
||||
if (runningCommandSeparateSession) {
|
||||
const launcher = [
|
||||
'const { spawn } = require("node:child_process");',
|
||||
"const child = spawn(process.argv[1], process.argv.slice(2), { stdio: 'ignore' });",
|
||||
"child.once('exit', (code, signal) => process.exitCode = code ?? (signal ? 1 : 0));",
|
||||
].join(" ");
|
||||
const detachedCommand = runningCommandIgnoresTerm
|
||||
? 'trap "" TERM; bash -c \'trap "" TERM; while :; do sleep 1; done\' & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"'
|
||||
: 'sleep 120 & child=$!; printf "%s %s %s\\n" "$PPID" "$$" "$child" > "$1"; wait "$child"';
|
||||
// Nested bash publishes "$PPID $$ $child" once it starts. Do not
|
||||
// write the launcher PID alone here: that races with bash and can
|
||||
// clobber the triple that interrupt tests wait for.
|
||||
const detachedLauncher = NodeChildProcess.spawn(
|
||||
process.execPath,
|
||||
["-e", launcher, "bash", "-c", detachedCommand, "bash", runningCommandPidPath],
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
detachedLauncher.unref();
|
||||
} else {
|
||||
NodeChildProcess.spawn("bash", ["-c", command, "bash", runningCommandPidPath], {
|
||||
stdio: "ignore",
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["sleep", "120"],
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "in_progress",
|
||||
rawInput: {
|
||||
command: ["sleep", "120"],
|
||||
},
|
||||
// Grok-like mid-stream Bash re-report: exit_code 0 while still running.
|
||||
rawOutput: { type: "Bash", exit_code: 0 },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-call-output-1",
|
||||
title: "get_command_or_subagent_output",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: { task_id: "task-running-1" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-call-output-1",
|
||||
status: "in_progress",
|
||||
rawOutput: { task_id: "task-running-1", status: "running" },
|
||||
},
|
||||
});
|
||||
if (exitAfterRunningCommandLaunch) {
|
||||
yield* Effect.sleep("100 millis");
|
||||
return yield* Effect.sync(() => process.exit(0));
|
||||
}
|
||||
// Stay open until session/cancel so interrupt tests can observe a running tool.
|
||||
while (!cancelledSessions.has(requestedSessionId)) {
|
||||
yield* Effect.sleep("25 millis");
|
||||
}
|
||||
cancelledSessions.delete(requestedSessionId);
|
||||
return { stopReason: "cancelled" };
|
||||
}
|
||||
|
||||
if (emitEmptySuccessfulBash || (emitEmptySuccessfulBashThenHang && promptCount === 1)) {
|
||||
const update = {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-call-empty-success-1",
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawInput: { command: "true" },
|
||||
rawOutput: { type: "Bash", exit_code: 0 },
|
||||
},
|
||||
} as const;
|
||||
yield* agent.client.sessionUpdate(update);
|
||||
yield* Effect.sleep("25 millis");
|
||||
yield* agent.client.sessionUpdate(update);
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitXAiPromptCompleteThenHang) {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
@@ -630,6 +947,32 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitElicitation) {
|
||||
yield* agent.client.elicit({
|
||||
sessionId: requestedSessionId,
|
||||
message: "Approve this request?",
|
||||
mode: "form",
|
||||
requestedSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
approved: { type: "boolean", title: "Approved" },
|
||||
},
|
||||
},
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitUrlElicitation) {
|
||||
yield* agent.client.elicit({
|
||||
sessionId: requestedSessionId,
|
||||
message: "Open authentication page",
|
||||
mode: "url",
|
||||
url: "https://example.com/auth",
|
||||
elicitationId: "url-elicitation-1",
|
||||
});
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
@@ -688,6 +1031,10 @@ const program = Effect.gen(function* () {
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
if (hangAfterPermission) {
|
||||
return yield* Effect.never;
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
@@ -754,6 +1101,159 @@ const program = Effect.gen(function* () {
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
// In-turn monitor + TaskOutput hydrate, then a late post-finalize
|
||||
// duplicate terminal TaskOutput for the same task. Exercises the
|
||||
// already-handled short-circuit: must not pin hasPendingBackgroundWork.
|
||||
if (emitInTurnTaskOutputThenLateDuplicate) {
|
||||
const monitorToolCallId = "tool-call-monitor-1";
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: monitorToolCallId,
|
||||
title: "Monitor: mock background task",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: monitorToolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-call-fetch-1",
|
||||
title: "get_command_or_subagent_output",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: { task_id: "task-monitor-1" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-call-fetch-1",
|
||||
status: "completed",
|
||||
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
|
||||
},
|
||||
});
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Monitor listing ready in-turn." },
|
||||
},
|
||||
});
|
||||
// After deferred finalize (~2s) clears activeTurn, re-emit a terminal
|
||||
// TaskOutput for the same task so bufferPostSettleWake sees
|
||||
// alreadyHandledToolUpdate with a non-empty wake path.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep("2500 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-call-fetch-1",
|
||||
title: "get_command_or_subagent_output",
|
||||
kind: "other",
|
||||
status: "completed",
|
||||
rawOutput: { output: "MONITOR_LISTING_TOKEN_LATE" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}).pipe(Effect.forkDetach);
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitPostSettleMonitorFlow) {
|
||||
const monitorToolCallId = "tool-call-monitor-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: monitorToolCallId,
|
||||
title: "Monitor: mock background task",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: monitorToolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
// After the prompt settles, replay the CLI-injected monitor-event
|
||||
// turn: end notice, TaskOutput hydration, then (once the trigger
|
||||
// file exists) the report chunk. Detached fiber on the real clock;
|
||||
// it outlives the prompt handler.
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Effect.sleep("150 millis");
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: {
|
||||
type: "text",
|
||||
text: 'Monitor "task-monitor-1" ended: [monitor ended: exit 0]',
|
||||
},
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId: "tool-call-fetch-1",
|
||||
title: "get_command_or_subagent_output",
|
||||
kind: "other",
|
||||
status: "pending",
|
||||
rawInput: { task_id: "task-monitor-1" },
|
||||
},
|
||||
});
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId: "tool-call-fetch-1",
|
||||
status: "completed",
|
||||
rawOutput: { output: "MONITOR_LISTING_TOKEN" },
|
||||
},
|
||||
});
|
||||
});
|
||||
if (injectedReportTriggerPath === undefined) return;
|
||||
while (!(yield* Effect.sync(() => NodeFS.existsSync(injectedReportTriggerPath)))) {
|
||||
yield* Effect.sleep("20 millis");
|
||||
}
|
||||
yield* Effect.sync(() => {
|
||||
writeJsonRpcNotification("session/update", {
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "Monitor finished. MONITOR_REPORT_TOKEN" },
|
||||
},
|
||||
});
|
||||
});
|
||||
}).pipe(Effect.forkDetach);
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
@@ -878,12 +1378,6 @@ const program = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method === "cursor/list_available_models") {
|
||||
return Effect.succeed({
|
||||
models: availableModels(),
|
||||
});
|
||||
}
|
||||
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as NodeURL from "node:url";
|
||||
|
||||
import { expect, it } from "vite-plus/test";
|
||||
|
||||
import { acpReplayAgentArgs } from "../src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts";
|
||||
|
||||
const replayAgentPath = NodeURL.fileURLToPath(new URL("./acp-replay-agent.ts", import.meta.url));
|
||||
|
||||
async function runRuntimeExit(status: "success" | "error" | "cancelled") {
|
||||
const scratch = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-acp-replay-agent-"));
|
||||
const statusPath = NodePath.join(scratch, "status.json");
|
||||
const transcript = {
|
||||
scenario: `${status}-runtime-exit`,
|
||||
entries: [{ type: "runtime_exit", status }],
|
||||
};
|
||||
const args = acpReplayAgentArgs(replayAgentPath);
|
||||
const child = NodeChildProcess.spawn(process.execPath, args, {
|
||||
env: {
|
||||
...process.env,
|
||||
T3_ACP_REPLAY_STATUS_PATH: statusPath,
|
||||
T3_ACP_REPLAY_TRANSCRIPT: Buffer.from(JSON.stringify(transcript), "utf8").toString("base64"),
|
||||
T3_ACP_REPLAY_WORKSPACE: scratch,
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
let stderr = "";
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
stderr += chunk;
|
||||
});
|
||||
child.stdin.end();
|
||||
|
||||
try {
|
||||
const code = await new Promise<number | null>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", resolve);
|
||||
});
|
||||
return {
|
||||
code,
|
||||
status: JSON.parse(NodeFS.readFileSync(statusPath, "utf8")) as unknown,
|
||||
stderr,
|
||||
transcript,
|
||||
args,
|
||||
};
|
||||
} finally {
|
||||
NodeFS.rmSync(scratch, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
it("accepts a recorded cancelled runtime exit", async () => {
|
||||
const result = await runRuntimeExit("cancelled");
|
||||
expect(result.code, result.stderr).toBe(0);
|
||||
expect(result.args).toEqual(["--experimental-strip-types", replayAgentPath]);
|
||||
expect(result.status).toEqual({
|
||||
scenario: result.transcript.scenario,
|
||||
cursor: 1,
|
||||
total: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("still rejects a recorded error runtime exit", async () => {
|
||||
const result = await runRuntimeExit("error");
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.status).toMatchObject({
|
||||
scenario: result.transcript.scenario,
|
||||
cursor: 0,
|
||||
total: 1,
|
||||
failure: {
|
||||
detail: "Recorded runtime exit was error",
|
||||
cursor: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
#!/usr/bin/env node
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeReadline from "node:readline";
|
||||
|
||||
interface ReplayEntry {
|
||||
readonly type: "emit_inbound" | "expect_outbound" | "runtime_exit";
|
||||
readonly label?: string;
|
||||
readonly frame?: unknown;
|
||||
readonly status?: "success" | "error" | "cancelled";
|
||||
readonly error?: unknown;
|
||||
}
|
||||
|
||||
interface ReplayTranscript {
|
||||
readonly scenario: string;
|
||||
readonly entries: ReadonlyArray<ReplayEntry>;
|
||||
}
|
||||
|
||||
interface LogicalFrame {
|
||||
readonly kind: "notification" | "request" | "response";
|
||||
readonly method: string;
|
||||
readonly params?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: unknown;
|
||||
}
|
||||
|
||||
interface JsonRpcMessage {
|
||||
readonly jsonrpc?: string;
|
||||
readonly id?: string | number | null;
|
||||
readonly method?: string;
|
||||
readonly params?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: unknown;
|
||||
readonly headers?: ReadonlyArray<unknown>;
|
||||
}
|
||||
|
||||
const encodedTranscript = process.env.T3_ACP_REPLAY_TRANSCRIPT;
|
||||
const statusPath = process.env.T3_ACP_REPLAY_STATUS_PATH;
|
||||
const replayWorkspace = process.env.T3_ACP_REPLAY_WORKSPACE ?? process.cwd();
|
||||
|
||||
if (encodedTranscript === undefined || statusPath === undefined) {
|
||||
process.stderr.write("ACP replay requires transcript and status environment variables.\n");
|
||||
process.exit(2);
|
||||
}
|
||||
|
||||
const replayStatusPath = statusPath;
|
||||
const transcript = JSON.parse(
|
||||
Buffer.from(encodedTranscript, "base64").toString("utf8"),
|
||||
) as ReplayTranscript;
|
||||
let cursor = 0;
|
||||
let stopped = false;
|
||||
let nextAgentRequestId = 1;
|
||||
const pendingClientRequestIds = new Map<string, string | number>();
|
||||
const pendingAgentRequestMethods = new Map<string, string>();
|
||||
|
||||
function writeStatus(failure?: unknown): void {
|
||||
NodeFS.writeFileSync(
|
||||
replayStatusPath,
|
||||
JSON.stringify({
|
||||
scenario: transcript.scenario,
|
||||
cursor,
|
||||
total: transcript.entries.length,
|
||||
...(failure === undefined ? {} : { failure }),
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
}
|
||||
|
||||
function stableStringify(value: unknown): string {
|
||||
if (Array.isArray(value)) {
|
||||
return `[${value.map(stableStringify).join(",")}]`;
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
const record = value as Record<string, unknown>;
|
||||
return `{${Object.keys(record)
|
||||
.toSorted()
|
||||
.map((key) => `${JSON.stringify(key)}:${stableStringify(record[key])}`)
|
||||
.join(",")}}`;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
function expandExpectedString(value: string): string {
|
||||
return value.replaceAll("<workspace>", replayWorkspace);
|
||||
}
|
||||
|
||||
function matchesExpected(expected: unknown, actual: unknown): boolean {
|
||||
if (expected === "<any>") return true;
|
||||
if (typeof expected === "string" && typeof actual === "string") {
|
||||
const expanded = expandExpectedString(expected);
|
||||
if (!expanded.includes("<any>")) return expanded === actual;
|
||||
const parts = expanded.split("<any>");
|
||||
let offset = 0;
|
||||
for (const part of parts) {
|
||||
const index = actual.indexOf(part, offset);
|
||||
if (index === -1) return false;
|
||||
offset = index + part.length;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (Array.isArray(expected)) {
|
||||
return (
|
||||
Array.isArray(actual) &&
|
||||
expected.length === actual.length &&
|
||||
expected.every((entry, index) => matchesExpected(entry, actual[index]))
|
||||
);
|
||||
}
|
||||
if (typeof expected === "object" && expected !== null) {
|
||||
if (typeof actual !== "object" || actual === null || Array.isArray(actual)) return false;
|
||||
const expectedRecord = expected as Record<string, unknown>;
|
||||
const actualRecord = actual as Record<string, unknown>;
|
||||
const expectedKeys = Object.keys(expectedRecord).toSorted();
|
||||
const actualKeys = Object.keys(actualRecord).toSorted();
|
||||
return (
|
||||
stableStringify(expectedKeys) === stableStringify(actualKeys) &&
|
||||
expectedKeys.every((key) => matchesExpected(expectedRecord[key], actualRecord[key]))
|
||||
);
|
||||
}
|
||||
return Object.is(expected, actual);
|
||||
}
|
||||
|
||||
function stopWithFailure(detail: string, actual?: unknown): void {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
const entry = transcript.entries[cursor];
|
||||
const failure = {
|
||||
detail,
|
||||
cursor,
|
||||
expected: entry,
|
||||
...(actual === undefined ? {} : { actual }),
|
||||
};
|
||||
writeStatus(failure);
|
||||
process.stderr.write(`ACP replay mismatch: ${JSON.stringify(failure)}\n`);
|
||||
process.exitCode = 1;
|
||||
process.stdin.pause();
|
||||
}
|
||||
|
||||
function advance(): void {
|
||||
cursor += 1;
|
||||
writeStatus();
|
||||
}
|
||||
|
||||
function send(message: JsonRpcMessage): void {
|
||||
process.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
function pendingClientRequestId(method: string): string | number | undefined {
|
||||
return pendingClientRequestIds.get(method);
|
||||
}
|
||||
|
||||
function logicalIncoming(message: JsonRpcMessage): LogicalFrame | undefined {
|
||||
if (typeof message.method === "string") {
|
||||
return {
|
||||
kind:
|
||||
message.id === undefined || message.id === null || message.id === ""
|
||||
? "notification"
|
||||
: "request",
|
||||
method: message.method,
|
||||
...(message.params === undefined ? {} : { params: message.params }),
|
||||
};
|
||||
}
|
||||
if (message.id === undefined || message.id === null) return undefined;
|
||||
const method = pendingAgentRequestMethods.get(String(message.id));
|
||||
if (method === undefined) return undefined;
|
||||
return {
|
||||
kind: "response",
|
||||
method,
|
||||
...(message.result === undefined ? {} : { result: message.result }),
|
||||
...(message.error === undefined ? {} : { error: message.error }),
|
||||
};
|
||||
}
|
||||
|
||||
function emitInbound(frame: LogicalFrame): void {
|
||||
switch (frame.kind) {
|
||||
case "notification":
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
method: frame.method,
|
||||
...(frame.params === undefined ? {} : { params: frame.params }),
|
||||
});
|
||||
return;
|
||||
case "request": {
|
||||
const id = nextAgentRequestId;
|
||||
nextAgentRequestId += 1;
|
||||
pendingAgentRequestMethods.set(String(id), frame.method);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
method: frame.method,
|
||||
...(frame.params === undefined ? {} : { params: frame.params }),
|
||||
headers: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "response": {
|
||||
const id = pendingClientRequestId(frame.method);
|
||||
if (id === undefined) {
|
||||
stopWithFailure(`No pending client request for ${frame.method}`, frame);
|
||||
return;
|
||||
}
|
||||
pendingClientRequestIds.delete(frame.method);
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id,
|
||||
...(frame.result === undefined ? {} : { result: frame.result }),
|
||||
...(frame.error === undefined ? {} : { error: frame.error }),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function flushInbound(): void {
|
||||
while (!stopped) {
|
||||
const entry = transcript.entries[cursor];
|
||||
if (entry === undefined || entry.type === "expect_outbound") return;
|
||||
if (entry.type === "runtime_exit") {
|
||||
if (entry.status !== "success" && entry.status !== "cancelled") {
|
||||
stopWithFailure(`Recorded runtime exit was ${entry.status ?? "unknown"}`, entry.error);
|
||||
return;
|
||||
}
|
||||
advance();
|
||||
continue;
|
||||
}
|
||||
const frame = entry.frame as LogicalFrame;
|
||||
if (
|
||||
typeof frame !== "object" ||
|
||||
frame === null ||
|
||||
!["notification", "request", "response"].includes(frame.kind) ||
|
||||
typeof frame.method !== "string"
|
||||
) {
|
||||
stopWithFailure("Invalid emit_inbound logical ACP frame", entry.frame);
|
||||
return;
|
||||
}
|
||||
emitInbound(frame);
|
||||
if (stopped) return;
|
||||
advance();
|
||||
}
|
||||
}
|
||||
|
||||
function handleMessage(message: JsonRpcMessage): void {
|
||||
if (stopped) return;
|
||||
const actual = logicalIncoming(message);
|
||||
if (actual === undefined) {
|
||||
stopWithFailure("Could not identify outbound ACP frame", message);
|
||||
return;
|
||||
}
|
||||
const entry = transcript.entries[cursor];
|
||||
if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
|
||||
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
|
||||
send({
|
||||
jsonrpc: "2.0",
|
||||
id: message.id,
|
||||
error: { code: -32603, message: "ACP replay frame mismatch" },
|
||||
});
|
||||
}
|
||||
stopWithFailure("Unexpected outbound ACP frame", actual);
|
||||
return;
|
||||
}
|
||||
if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
|
||||
pendingClientRequestIds.set(actual.method, message.id);
|
||||
} else if (actual.kind === "response" && message.id !== undefined && message.id !== null) {
|
||||
pendingAgentRequestMethods.delete(String(message.id));
|
||||
}
|
||||
advance();
|
||||
flushInbound();
|
||||
}
|
||||
|
||||
writeStatus();
|
||||
flushInbound();
|
||||
|
||||
const input = NodeReadline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
input.on("line", (line) => {
|
||||
if (stopped || line.trim().length === 0) return;
|
||||
try {
|
||||
handleMessage(JSON.parse(line) as JsonRpcMessage);
|
||||
} catch (cause) {
|
||||
stopWithFailure("Failed to decode outbound ACP JSON-RPC", String(cause));
|
||||
}
|
||||
});
|
||||
|
||||
input.on("close", () => {
|
||||
if (!stopped && cursor !== transcript.entries.length) {
|
||||
stopWithFailure("ACP replay input closed before transcript completion");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
#define _GNU_SOURCE
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static const char *pid_path;
|
||||
|
||||
static void *spawn_child(void *unused) {
|
||||
(void)unused;
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
execlp("sleep", "sleep", "120", NULL);
|
||||
_exit(127);
|
||||
}
|
||||
if (child < 0) return NULL;
|
||||
FILE *file = fopen(pid_path, "w");
|
||||
if (file != NULL) {
|
||||
fprintf(file, "%ld %d\n", syscall(SYS_gettid), child);
|
||||
fclose(file);
|
||||
}
|
||||
waitpid(child, NULL, 0);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2) return 2;
|
||||
pid_path = argv[1];
|
||||
pthread_t worker;
|
||||
if (pthread_create(&worker, NULL, spawn_child, NULL) != 0) return 3;
|
||||
if (pthread_join(worker, NULL) != 0) return 4;
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { beginAcpMockPrompt } from "./acpMockCancellationState.ts";
|
||||
|
||||
it("does not carry an idle cancellation into the next prompt", () => {
|
||||
const cancelledSessions = new Set(["session:cancelled-while-idle", "session:other"]);
|
||||
|
||||
beginAcpMockPrompt(cancelledSessions, "session:cancelled-while-idle");
|
||||
|
||||
assert.isFalse(cancelledSessions.has("session:cancelled-while-idle"));
|
||||
assert.isTrue(cancelledSessions.has("session:other"));
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export function beginAcpMockPrompt(cancelledSessions: Set<string>, sessionId: string): void {
|
||||
cancelledSessions.delete(sessionId);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { validateClaudeReplayRecordingSelection } from "./claudeReplayRecordingConfig.ts";
|
||||
|
||||
it("rejects a query mode that is incompatible with the selected scenario", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
validateClaudeReplayRecordingSelection({
|
||||
scenario: "simple",
|
||||
configuredQueryMode: "streaming",
|
||||
selectedQueryMode: "fork_session_siblings",
|
||||
configuredPromptCount: 1,
|
||||
selectedPromptCount: 1,
|
||||
}),
|
||||
"Select a scenario configured for the requested query mode",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects prompt overrides that do not preserve the scenario shape", () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
validateClaudeReplayRecordingSelection({
|
||||
scenario: "thread_fork_native_siblings",
|
||||
configuredQueryMode: "fork_session_siblings",
|
||||
selectedQueryMode: "fork_session_siblings",
|
||||
configuredPromptCount: 3,
|
||||
selectedPromptCount: 1,
|
||||
}),
|
||||
"requires exactly 3 prompt(s)",
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts the configured scenario mode and prompt shape", () => {
|
||||
assert.doesNotThrow(() =>
|
||||
validateClaudeReplayRecordingSelection({
|
||||
scenario: "thread_fork_native_siblings",
|
||||
configuredQueryMode: "fork_session_siblings",
|
||||
selectedQueryMode: "fork_session_siblings",
|
||||
configuredPromptCount: 3,
|
||||
selectedPromptCount: 3,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
export type ClaudeRecordingQueryMode =
|
||||
| "streaming"
|
||||
| "restart"
|
||||
| "resume_at_cursor"
|
||||
| "fork_session"
|
||||
| "fork_session_prior_turn"
|
||||
| "fork_session_continue"
|
||||
| "fork_session_siblings"
|
||||
| "fork_session_merge_back"
|
||||
| "fork_session_merge_back_siblings"
|
||||
| "active_steering"
|
||||
| "interrupt"
|
||||
| "interrupt_restart";
|
||||
|
||||
export function validateClaudeReplayRecordingSelection(input: {
|
||||
readonly scenario: string;
|
||||
readonly configuredQueryMode: ClaudeRecordingQueryMode;
|
||||
readonly selectedQueryMode: ClaudeRecordingQueryMode;
|
||||
readonly configuredPromptCount: number;
|
||||
readonly selectedPromptCount: number;
|
||||
}): void {
|
||||
if (input.selectedQueryMode !== input.configuredQueryMode) {
|
||||
throw new Error(
|
||||
`Claude replay fixture '${input.scenario}' uses query mode '${input.configuredQueryMode}', not '${input.selectedQueryMode}'. Select a scenario configured for the requested query mode.`,
|
||||
);
|
||||
}
|
||||
if (input.selectedPromptCount !== input.configuredPromptCount) {
|
||||
throw new Error(
|
||||
`Claude replay fixture '${input.scenario}' requires exactly ${input.configuredPromptCount} prompt(s) for query mode '${input.configuredQueryMode}', but received ${input.selectedPromptCount}.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts";
|
||||
|
||||
it("preserves monotonic request ids across native Codex forks", () => {
|
||||
const records = [
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "initialize",
|
||||
frame: { id: 1, method: "initialize" },
|
||||
},
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "thread/fork",
|
||||
frame: { id: 4, method: "thread/fork" },
|
||||
},
|
||||
{
|
||||
type: "expect_outbound",
|
||||
label: "turn/start",
|
||||
frame: { id: 5, method: "turn/start" },
|
||||
},
|
||||
];
|
||||
|
||||
const output = codexReplayRecordingOutputRecords(records);
|
||||
|
||||
assert.deepEqual(output, records);
|
||||
assert.deepEqual(
|
||||
output.map((record) => record.label),
|
||||
["initialize", "thread/fork", "turn/start"],
|
||||
);
|
||||
assert.deepEqual(
|
||||
output.map((record) => (record.frame as { readonly id: number }).id),
|
||||
[1, 4, 5],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* Codex supports multiple provider threads in one app-server session, so native
|
||||
* fork recording keeps the request ids emitted by that single client.
|
||||
*/
|
||||
export function codexReplayRecordingOutputRecords(
|
||||
records: ReadonlyArray<Record<string, unknown>>,
|
||||
): ReadonlyArray<Record<string, unknown>> {
|
||||
return [...records];
|
||||
}
|
||||
@@ -1,442 +0,0 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off
|
||||
import * as NodeChildProcess from "node:child_process";
|
||||
import * as NodeProcess from "node:process";
|
||||
import * as NodeReadline from "node:readline";
|
||||
import * as NodeTimers from "node:timers";
|
||||
import { resolveSpawnCommand } from "@t3tools/shared/shell";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
type JsonRpcId = number | string;
|
||||
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string;
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: JsonValue;
|
||||
result?: JsonValue;
|
||||
error?: JsonValue;
|
||||
headers?: JsonValue;
|
||||
};
|
||||
|
||||
type SelectLeafOption = {
|
||||
value: string;
|
||||
label?: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type SelectGroupOption = {
|
||||
label?: string;
|
||||
name?: string;
|
||||
options: SelectLeafOption[];
|
||||
};
|
||||
|
||||
type SessionConfigOption = {
|
||||
id: string;
|
||||
name?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
options?: Array<SelectLeafOption | SelectGroupOption>;
|
||||
};
|
||||
|
||||
type SessionNewResult = {
|
||||
sessionId: string;
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type SetConfigResult = {
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
method: string;
|
||||
resolve: (value: JsonValue | undefined) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const targetCwd = NodeProcess.argv[2] ?? NodeProcess.cwd();
|
||||
const targetModel = NodeProcess.argv[3] ?? "gpt-5.4";
|
||||
const promptText = NodeProcess.argv[4] ?? "helo";
|
||||
const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";
|
||||
const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";
|
||||
const targetFast = NodeProcess.env.CURSOR_FAST ?? "";
|
||||
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "cursor-agent";
|
||||
const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
|
||||
const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
|
||||
|
||||
function logSection(title: string, value: unknown) {
|
||||
NodeProcess.stdout.write(`\n=== ${title} ===\n`);
|
||||
NodeProcess.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function asString(value: JsonValue | undefined): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
|
||||
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (const entry of option.options) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("value" in entry && typeof entry.value === "string") {
|
||||
values.push(entry.value);
|
||||
continue;
|
||||
}
|
||||
if ("options" in entry && Array.isArray(entry.options)) {
|
||||
for (const nested of entry.options) {
|
||||
if (nested && typeof nested === "object" && typeof nested.value === "string") {
|
||||
values.push(nested.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function findConfigOption(
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
return configOptions.find(predicate);
|
||||
}
|
||||
|
||||
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
|
||||
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
|
||||
return haystack.includes(keyword.toLowerCase());
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test.
|
||||
NodeTimers.setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
class JsonRpcChild {
|
||||
readonly child: NodeChildProcess.ChildProcessWithoutNullStreams;
|
||||
readonly pending = new Map<JsonRpcId, PendingRequest>();
|
||||
nextId = 1;
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));
|
||||
this.child = NodeChildProcess.spawn(spawnCommand.command, spawnCommand.args, {
|
||||
cwd,
|
||||
shell: spawnCommand.shell,
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: NodeProcess.env,
|
||||
});
|
||||
|
||||
this.child.on("exit", (code, signal) => {
|
||||
this.closed = true;
|
||||
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
this.child.on("error", (error) => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
const stdout = NodeReadline.createInterface({ input: this.child.stdout });
|
||||
stdout.on("line", (line) => {
|
||||
void this.handleStdoutLine(line);
|
||||
});
|
||||
|
||||
const stderr = NodeReadline.createInterface({ input: this.child.stderr });
|
||||
stderr.on("line", (line) => {
|
||||
NodeProcess.stdout.write(`[stderr] ${line}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
write(message: JsonRpcMessage) {
|
||||
if (this.closed) {
|
||||
fail("ACP process is already closed.");
|
||||
}
|
||||
const payload = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
headers: [],
|
||||
...message,
|
||||
});
|
||||
NodeProcess.stdout.write(`>>> ${payload}\n`);
|
||||
this.child.stdin.write(`${payload}\n`);
|
||||
}
|
||||
|
||||
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
|
||||
const id = this.nextId++;
|
||||
|
||||
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
|
||||
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout.
|
||||
const timeout = NodeTimers.setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
method,
|
||||
resolve: (value) => {
|
||||
NodeTimers.clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
NodeTimers.clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.write({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
});
|
||||
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
notify(method: string, params: JsonValue) {
|
||||
this.write({
|
||||
method,
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
respond(id: JsonRpcId, result: JsonValue) {
|
||||
this.write({
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
respondError(id: JsonRpcId, code: number, message: string) {
|
||||
this.write({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async handleStdoutLine(line: string) {
|
||||
if (line.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
NodeProcess.stdout.write(`<<< ${line}\n`);
|
||||
|
||||
let message: JsonRpcMessage;
|
||||
try {
|
||||
message = JSON.parse(line) as JsonRpcMessage;
|
||||
} catch (error) {
|
||||
NodeProcess.stdout.write(`[parse-error] ${(error as Error).message}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && !message.method) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (typeof message.error !== "undefined") {
|
||||
pending.reject(
|
||||
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
|
||||
this.respond(message.id, {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && message.id !== "") {
|
||||
this.respondError(
|
||||
message.id,
|
||||
-32601,
|
||||
`Unhandled server request: ${message.method ?? "unknown"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.child.kill("SIGTERM");
|
||||
await sleep(250);
|
||||
if (!this.closed) {
|
||||
this.child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setSelectOptionIfAdvertised(
|
||||
rpc: JsonRpcChild,
|
||||
sessionId: string,
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
value: string,
|
||||
label: string,
|
||||
) {
|
||||
if (value.length === 0) {
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const option = findConfigOption(configOptions, predicate);
|
||||
const values = flattenSelectValues(option);
|
||||
if (!option || !values.includes(value)) {
|
||||
logSection(`SKIP_${label}`, {
|
||||
requestedValue: value,
|
||||
availableValues: values,
|
||||
});
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const response = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: option.id,
|
||||
value,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
|
||||
logSection(`SET_${label}_RESPONSE`, response);
|
||||
return response?.configOptions ?? configOptions;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
|
||||
|
||||
try {
|
||||
const initializeResponse = await rpc.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: {
|
||||
name: "cursor-acp-model-mismatch-probe",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
logSection("INITIALIZE_RESPONSE", initializeResponse);
|
||||
|
||||
const authenticateResponse = await rpc.request("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
|
||||
|
||||
const sessionResponse = (await rpc.request("session/new", {
|
||||
cwd: targetCwd,
|
||||
mcpServers: [],
|
||||
})) as SessionNewResult;
|
||||
logSection("SESSION_NEW_RESPONSE", sessionResponse);
|
||||
|
||||
const sessionId = asString(sessionResponse.sessionId);
|
||||
if (!sessionId) {
|
||||
fail("session/new did not return a sessionId.");
|
||||
}
|
||||
|
||||
let configOptions = sessionResponse.configOptions ?? [];
|
||||
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
|
||||
const advertisedModels = flattenSelectValues(modelConfig);
|
||||
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
|
||||
|
||||
if (!modelConfig || modelConfig.type !== "select") {
|
||||
fail("Cursor ACP did not expose a select-type model config option.");
|
||||
}
|
||||
|
||||
if (!advertisedModels.includes(targetModel)) {
|
||||
fail(
|
||||
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const setModelResponse = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfig.id,
|
||||
value: targetModel,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
logSection("SET_MODEL_RESPONSE", setModelResponse);
|
||||
|
||||
configOptions = setModelResponse?.configOptions ?? configOptions;
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "thought_level",
|
||||
targetReasoning,
|
||||
"REASONING",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
|
||||
targetContext,
|
||||
"CONTEXT",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
|
||||
targetFast,
|
||||
"FAST",
|
||||
);
|
||||
|
||||
const promptResponse = await rpc.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: promptText,
|
||||
},
|
||||
],
|
||||
});
|
||||
logSection("PROMPT_RESPONSE", promptResponse);
|
||||
|
||||
await sleep(promptWaitMs);
|
||||
rpc.notify("session/cancel", { sessionId });
|
||||
} finally {
|
||||
await rpc.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
NodeProcess.stderr.write(
|
||||
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
cursorReplayPromptsForWorkspace,
|
||||
cursorReplayTranscriptCwd,
|
||||
shouldSeedCursorReplayWorkspace,
|
||||
} from "./cursorReplayRecordingWorkspace.ts";
|
||||
|
||||
it("points the read-only prompt at the unique recording workspace", () => {
|
||||
assert.deepEqual(
|
||||
cursorReplayPromptsForWorkspace({
|
||||
scenario: "tool_call_read_only",
|
||||
configuredPrompts: ["stale global path"],
|
||||
packageJsonPath: "/tmp/t3-cursor-owned-abc123/package.json",
|
||||
tsconfigPath: "/tmp/t3-cursor-owned-abc123/tsconfig.json",
|
||||
}),
|
||||
[
|
||||
"Read /tmp/t3-cursor-owned-abc123/package.json and /tmp/t3-cursor-owned-abc123/tsconfig.json, then answer exactly: read only tool fixture complete",
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("never seeds files into an externally supplied workspace", () => {
|
||||
assert.isFalse(
|
||||
shouldSeedCursorReplayWorkspace({
|
||||
scenario: "tool_call_read_only",
|
||||
owned: false,
|
||||
}),
|
||||
);
|
||||
assert.isTrue(
|
||||
shouldSeedCursorReplayWorkspace({
|
||||
scenario: "tool_call_read_only",
|
||||
owned: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("canonicalizes read-only tool paths to the stable fixture workspace", () => {
|
||||
assert.equal(
|
||||
cursorReplayTranscriptCwd("tool_call_read_only"),
|
||||
"/tmp/claude-replay-tool_call_read_only",
|
||||
);
|
||||
assert.equal(cursorReplayTranscriptCwd("simple"), undefined);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { TOOL_CALL_READ_ONLY_WORKSPACE_ROOT } from "../src/orchestration-v2/testkit/fixtures/shared.ts";
|
||||
|
||||
const SEEDED_CURSOR_REPLAY_SCENARIOS = new Set(["subagent", "tool_call_read_only", "todo_list"]);
|
||||
|
||||
export function cursorReplayPromptsForWorkspace(input: {
|
||||
readonly scenario: string;
|
||||
readonly configuredPrompts: ReadonlyArray<string>;
|
||||
readonly packageJsonPath: string;
|
||||
readonly tsconfigPath: string;
|
||||
}): ReadonlyArray<string> {
|
||||
if (input.scenario !== "tool_call_read_only") {
|
||||
return input.configuredPrompts;
|
||||
}
|
||||
|
||||
return [
|
||||
`Read ${input.packageJsonPath} and ${input.tsconfigPath}, then answer exactly: read only tool fixture complete`,
|
||||
];
|
||||
}
|
||||
|
||||
export function shouldSeedCursorReplayWorkspace(input: {
|
||||
readonly scenario: string;
|
||||
readonly owned: boolean;
|
||||
}): boolean {
|
||||
return input.owned && SEEDED_CURSOR_REPLAY_SCENARIOS.has(input.scenario);
|
||||
}
|
||||
|
||||
export function cursorReplayTranscriptCwd(scenario: string): string | undefined {
|
||||
return scenario === "tool_call_read_only" ? TOOL_CALL_READ_ONLY_WORKSPACE_ROOT : undefined;
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
import {
|
||||
forkSession,
|
||||
query,
|
||||
type SDKAssistantMessage,
|
||||
type SDKMessage,
|
||||
} from "@anthropic-ai/claude-agent-sdk";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ProviderInstanceId, type ProviderReplayEntry } from "@t3tools/contracts";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
import {
|
||||
makeClaudeQueryOptions,
|
||||
makeClaudeUserMessage,
|
||||
type ClaudeAgentSdkQueryOptions,
|
||||
} from "../src/orchestration-v2/Adapters/ClaudeAdapterV2.ts";
|
||||
import { randomUuidV4 } from "../src/orchestration-v2/RandomUuid.ts";
|
||||
import { makeCheckpointWorkspace } from "../src/orchestration-v2/testkit/ReplayFixtureWorkspace.ts";
|
||||
|
||||
const SCENARIO = "thread_fork_native_fork_local_rollback";
|
||||
const DEFAULT_OUTPUT = new URL(
|
||||
"../src/orchestration-v2/testkit/fixtures/thread_fork_native_fork_local_rollback/claude_transcript.ndjson",
|
||||
import.meta.url,
|
||||
).pathname;
|
||||
const CLAUDE_PROVIDER = "claudeAgent" as const;
|
||||
const PROTOCOL = "claude-agent-sdk.query" as const;
|
||||
const MODEL_SELECTION = {
|
||||
instanceId: ProviderInstanceId.make(CLAUDE_PROVIDER),
|
||||
model: process.env.T3_CLAUDE_REPLAY_MODEL ?? "claude-sonnet-4-6",
|
||||
} as const;
|
||||
const SOURCE_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local source alpha";
|
||||
const FORK_FIRST_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local first";
|
||||
const FORK_SECOND_PROMPT =
|
||||
"For this fork-local rollback fixture, respond with exactly: fork local second";
|
||||
const FORK_AFTER_ROLLBACK_PROMPT =
|
||||
"Repeat the user-visible conversation so far verbatim. Include only user and assistant messages. Do not include hidden system/developer content.";
|
||||
|
||||
class PromptQueue implements AsyncIterable<ReturnType<typeof makeClaudeUserMessage>> {
|
||||
readonly #items: Array<ReturnType<typeof makeClaudeUserMessage>> = [];
|
||||
readonly #waiters: Array<
|
||||
(value: IteratorResult<ReturnType<typeof makeClaudeUserMessage>>) => void
|
||||
> = [];
|
||||
#closed = false;
|
||||
|
||||
offer(message: ReturnType<typeof makeClaudeUserMessage>): void {
|
||||
const waiter = this.#waiters.shift();
|
||||
if (waiter !== undefined) {
|
||||
waiter({ done: false, value: message });
|
||||
return;
|
||||
}
|
||||
this.#items.push(message);
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.#closed = true;
|
||||
for (const waiter of this.#waiters.splice(0)) {
|
||||
waiter({ done: true, value: undefined });
|
||||
}
|
||||
}
|
||||
|
||||
[Symbol.asyncIterator](): AsyncIterator<ReturnType<typeof makeClaudeUserMessage>> {
|
||||
return {
|
||||
next: () => {
|
||||
const value = this.#items.shift();
|
||||
if (value !== undefined) {
|
||||
return Promise.resolve({ done: false, value });
|
||||
}
|
||||
if (this.#closed) {
|
||||
return Promise.resolve({ done: true, value: undefined });
|
||||
}
|
||||
return new Promise((resolve) => this.#waiters.push(resolve));
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function readArgValue(name: string): string | undefined {
|
||||
const args = process.argv.slice(2);
|
||||
const index = args.indexOf(name);
|
||||
return index >= 0 ? args[index + 1] : undefined;
|
||||
}
|
||||
|
||||
function dirname(filePath: string): string {
|
||||
const normalized = filePath.replace(/\/+$/u, "");
|
||||
const lastSlash = normalized.lastIndexOf("/");
|
||||
if (lastSlash < 0) {
|
||||
return ".";
|
||||
}
|
||||
return lastSlash === 0 ? "/" : normalized.slice(0, lastSlash);
|
||||
}
|
||||
|
||||
function sanitizeValue(
|
||||
value: unknown,
|
||||
pathFragments: ReadonlyArray<readonly [string, string]>,
|
||||
): unknown {
|
||||
if (typeof value === "string") {
|
||||
return pathFragments.reduce(
|
||||
(sanitized, [actual, replacement]) =>
|
||||
actual.length === 0 ? sanitized : sanitized.split(actual).join(replacement),
|
||||
value,
|
||||
);
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
return value.map((entry) => sanitizeValue(entry, pathFragments));
|
||||
}
|
||||
if (typeof value === "object" && value !== null) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, entry]) => [key, sanitizeValue(entry, pathFragments)]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function stableOptions(options: ClaudeAgentSdkQueryOptions): ClaudeAgentSdkQueryOptions {
|
||||
const stable = {
|
||||
model: options.model,
|
||||
tools: options.tools,
|
||||
permissionMode: options.permissionMode,
|
||||
...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
|
||||
...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
|
||||
...(options.settings === undefined ? {} : { settings: options.settings }),
|
||||
...(options.allowDangerouslySkipPermissions === true
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
: {}),
|
||||
...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
|
||||
...(options.forkSession === true ? { forkSession: true } : {}),
|
||||
};
|
||||
return options.resume === undefined
|
||||
? { ...stable, sessionId: options.sessionId }
|
||||
: { ...stable, resume: options.resume };
|
||||
}
|
||||
|
||||
function queryOptions(input: {
|
||||
readonly cwd: string;
|
||||
readonly nativeThreadId: string;
|
||||
readonly resume: boolean;
|
||||
readonly resumeSessionAt?: string;
|
||||
}): ClaudeAgentSdkQueryOptions {
|
||||
return {
|
||||
...makeClaudeQueryOptions({
|
||||
modelSelection: MODEL_SELECTION,
|
||||
cwd: input.cwd,
|
||||
nativeThreadId: input.nativeThreadId,
|
||||
resume: input.resume,
|
||||
tools: { type: "preset", preset: "claude_code" },
|
||||
permissionMode: "bypassPermissions",
|
||||
allowDangerouslySkipPermissions: true,
|
||||
}),
|
||||
...(input.resumeSessionAt === undefined ? {} : { resumeSessionAt: input.resumeSessionAt }),
|
||||
};
|
||||
}
|
||||
|
||||
async function recordTurn(input: {
|
||||
readonly entries: Array<ProviderReplayEntry>;
|
||||
readonly iterator: AsyncIterator<SDKMessage>;
|
||||
readonly promptQueue: PromptQueue;
|
||||
readonly prompt: string;
|
||||
readonly label: string;
|
||||
readonly pathFragments: ReadonlyArray<readonly [string, string]>;
|
||||
}): Promise<SDKAssistantMessage["uuid"]> {
|
||||
const message = makeClaudeUserMessage({ text: input.prompt });
|
||||
input.entries.push({
|
||||
type: "expect_outbound",
|
||||
label: input.label,
|
||||
frame: { type: "prompt.offer", message },
|
||||
});
|
||||
input.promptQueue.offer(message);
|
||||
|
||||
let assistantMessageUuid: SDKAssistantMessage["uuid"] | null = null;
|
||||
while (true) {
|
||||
const next = await input.iterator.next();
|
||||
if (next.done === true) {
|
||||
throw new Error(`Claude query ended before ${input.label} completed.`);
|
||||
}
|
||||
const frame = sanitizeValue(next.value, input.pathFragments);
|
||||
input.entries.push({
|
||||
type: "emit_inbound",
|
||||
label: next.value.type,
|
||||
frame,
|
||||
});
|
||||
if (next.value.type === "assistant") {
|
||||
assistantMessageUuid = next.value.uuid;
|
||||
}
|
||||
if (next.value.type === "result") {
|
||||
if (assistantMessageUuid === null) {
|
||||
throw new Error(`Claude query completed ${input.label} without assistant UUID.`);
|
||||
}
|
||||
return assistantMessageUuid;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function encodeTranscript(input: {
|
||||
readonly entries: ReadonlyArray<ProviderReplayEntry>;
|
||||
readonly metadata: Record<string, unknown>;
|
||||
}): string {
|
||||
return [
|
||||
JSON.stringify({
|
||||
type: "transcript_start",
|
||||
provider: CLAUDE_PROVIDER,
|
||||
protocol: PROTOCOL,
|
||||
version: "0.2.111",
|
||||
scenario: SCENARIO,
|
||||
metadata: input.metadata,
|
||||
}),
|
||||
...input.entries.map((entry) => JSON.stringify(entry)),
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
const outputPath = readArgValue("--out") ?? DEFAULT_OUTPUT;
|
||||
const cwd =
|
||||
process.env.T3_CLAUDE_REPLAY_CWD ??
|
||||
(await makeCheckpointWorkspace(`claude-agent-sdk-record-${SCENARIO}`));
|
||||
const cwdRealPath = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
return yield* fs.realPath(cwd);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
const pathFragments = [
|
||||
[cwd, `/tmp/claude-replay-${SCENARIO}`],
|
||||
[cwdRealPath, `/tmp/claude-replay-${SCENARIO}`],
|
||||
[process.env.HOME ?? "", "/home/replay-user"],
|
||||
] as const;
|
||||
const sessionId =
|
||||
process.env.T3_CLAUDE_REPLAY_SESSION_ID ?? (await Effect.runPromise(randomUuidV4));
|
||||
const entries: Array<ProviderReplayEntry> = [];
|
||||
const metadata: Record<string, unknown> = {
|
||||
prompts: [SOURCE_PROMPT, FORK_FIRST_PROMPT, FORK_SECOND_PROMPT, FORK_AFTER_ROLLBACK_PROMPT],
|
||||
model: MODEL_SELECTION.model,
|
||||
nativeSessionId: sessionId,
|
||||
queryMode: "fork_session_resume_at_fork_cursor",
|
||||
tools: "claude_code",
|
||||
permissionMode: "bypassPermissions",
|
||||
generatedBy: "probeClaudeForkLocalRollbackReplay",
|
||||
};
|
||||
|
||||
const sourceQueue = new PromptQueue();
|
||||
const sourceOptions = queryOptions({ cwd, nativeThreadId: sessionId, resume: false });
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:source",
|
||||
frame: { type: "query.open", options: stableOptions(sourceOptions) },
|
||||
});
|
||||
const sourceRuntime = query({ prompt: sourceQueue, options: sourceOptions });
|
||||
try {
|
||||
const sourceCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: sourceRuntime[Symbol.asyncIterator](),
|
||||
promptQueue: sourceQueue,
|
||||
prompt: SOURCE_PROMPT,
|
||||
label: "prompt.offer:source",
|
||||
pathFragments,
|
||||
});
|
||||
sourceQueue.close();
|
||||
sourceRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "session.fork",
|
||||
frame: {
|
||||
type: "session.fork",
|
||||
sessionId,
|
||||
options: {
|
||||
dir: `/tmp/claude-replay-${SCENARIO}`,
|
||||
upToMessageId: sourceCursor,
|
||||
},
|
||||
},
|
||||
});
|
||||
const forked = await forkSession(sessionId, { dir: cwd, upToMessageId: sourceCursor });
|
||||
metadata.sourceAssistantMessageUuids = [sourceCursor];
|
||||
metadata.forkUpToMessageId = sourceCursor;
|
||||
metadata.forkedNativeSessionId = forked.sessionId;
|
||||
entries.push({
|
||||
type: "emit_inbound",
|
||||
label: "session.forked",
|
||||
frame: { type: "session.forked", sessionId: forked.sessionId },
|
||||
});
|
||||
|
||||
const forkQueue = new PromptQueue();
|
||||
const forkOptions = queryOptions({ cwd, nativeThreadId: forked.sessionId, resume: true });
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:fork",
|
||||
frame: { type: "query.open", options: stableOptions(forkOptions) },
|
||||
});
|
||||
const forkRuntime = query({ prompt: forkQueue, options: forkOptions });
|
||||
const forkIterator = forkRuntime[Symbol.asyncIterator]();
|
||||
const forkFirstCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: forkIterator,
|
||||
promptQueue: forkQueue,
|
||||
prompt: FORK_FIRST_PROMPT,
|
||||
label: "prompt.offer:fork-first",
|
||||
pathFragments,
|
||||
});
|
||||
const forkSecondCursor = await recordTurn({
|
||||
entries,
|
||||
iterator: forkIterator,
|
||||
promptQueue: forkQueue,
|
||||
prompt: FORK_SECOND_PROMPT,
|
||||
label: "prompt.offer:fork-second",
|
||||
pathFragments,
|
||||
});
|
||||
forkQueue.close();
|
||||
forkRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
metadata.forkAssistantMessageUuids = [forkFirstCursor, forkSecondCursor];
|
||||
metadata.resumeSessionAt = forkFirstCursor;
|
||||
|
||||
const resumedQueue = new PromptQueue();
|
||||
const resumedOptions = queryOptions({
|
||||
cwd,
|
||||
nativeThreadId: forked.sessionId,
|
||||
resume: true,
|
||||
resumeSessionAt: forkFirstCursor,
|
||||
});
|
||||
entries.push({
|
||||
type: "expect_outbound",
|
||||
label: "query.open:fork-resume-at-cursor",
|
||||
frame: { type: "query.open", options: stableOptions(resumedOptions) },
|
||||
});
|
||||
const resumedRuntime = query({ prompt: resumedQueue, options: resumedOptions });
|
||||
await recordTurn({
|
||||
entries,
|
||||
iterator: resumedRuntime[Symbol.asyncIterator](),
|
||||
promptQueue: resumedQueue,
|
||||
prompt: FORK_AFTER_ROLLBACK_PROMPT,
|
||||
label: "prompt.offer:fork-after-rollback",
|
||||
pathFragments,
|
||||
});
|
||||
resumedQueue.close();
|
||||
resumedRuntime.close();
|
||||
entries.push({ type: "runtime_exit", status: "success" });
|
||||
} catch (error) {
|
||||
sourceQueue.close();
|
||||
sourceRuntime.close();
|
||||
entries.push({
|
||||
type: "runtime_exit",
|
||||
status: "error",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
yield* fs.makeDirectory(dirname(outputPath), { recursive: true });
|
||||
yield* fs.writeFileString(outputPath, encodeTranscript({ entries, metadata }));
|
||||
yield* Console.log(`Wrote ${entries.length} ${PROTOCOL} replay entries to ${outputPath}`);
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
Loaded 100 of 883 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user