Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
02ed33118c | ||
|
|
e9921b0231 | ||
|
|
73cc66ff74 | ||
|
|
021853bc73 |
No files matched your search
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
@@ -50,13 +50,24 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
|
||||
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
```
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
|
||||
+9
-12
@@ -1,14 +1,12 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# `cp .env.example .env` enables T3 Connect against the production deployment.
|
||||
# These are the same public identifiers baked into official release builds, not
|
||||
# secrets. Remove or comment them out to build with cloud features disabled.
|
||||
# Do not add server-side secrets to this file.
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
|
||||
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
|
||||
# under API keys, JWT templates, and OAuth applications.
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
|
||||
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
@@ -17,9 +15,8 @@ T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
|
||||
# automatically.
|
||||
T3CODE_RELAY_URL=https://relay.t3.codes
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
|
||||
@@ -11,7 +11,6 @@
|
||||
# Keep entries sorted alphabetically.
|
||||
github:adityavardhansharma
|
||||
github:binbandit
|
||||
github:chrisdeeming
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:gbarros-dev
|
||||
@@ -27,7 +26,6 @@ github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:StiensWout
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -84,29 +84,8 @@ jobs:
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
|
||||
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
|
||||
run: vp run test
|
||||
|
||||
- name: Publish transfer budget report
|
||||
if: always()
|
||||
run: |
|
||||
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
|
||||
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
|
||||
else
|
||||
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
- name: Upload thread transfer result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer-result.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
|
||||
@@ -747,9 +747,15 @@ jobs:
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
@@ -817,7 +823,7 @@ jobs:
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v3
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -834,11 +840,11 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ github.token }}
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v3
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -854,7 +860,7 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ github.token }}
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
|
||||
@@ -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 });
|
||||
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
|
||||
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
|
||||
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
|
||||
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
|
||||
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
|
||||
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
|
||||
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
|
||||
- Stop what you started, by the PID you tracked. See rule 1.
|
||||
|
||||
## Test data
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.32",
|
||||
"version": "0.0.31",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -23,21 +23,6 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
|
||||
"ElectronDialogPickFilesError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
@@ -84,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
@@ -97,12 +81,6 @@ export interface ElectronDialogPickFolderInput {
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface ElectronDialogPickFilesInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
@@ -114,9 +92,6 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
@@ -162,32 +137,6 @@ export const make = ElectronDialog.of({
|
||||
}
|
||||
return Option.fromNullishOr(result.filePaths[0]);
|
||||
}),
|
||||
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = {
|
||||
properties: ["openFile", "multiSelections"],
|
||||
filters: [...input.filters],
|
||||
...(defaultPath === null ? {} : { defaultPath }),
|
||||
};
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFilesError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
|
||||
@@ -38,7 +38,6 @@ import {
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
pickThemeFiles,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
@@ -80,7 +79,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
|
||||
export const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
export const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
|
||||
@@ -3,15 +3,10 @@ import {
|
||||
DesktopAppBrandingSchema,
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickedThemeFileSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type PickedThemeFile,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -273,49 +268,3 @@ export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
return yield* shell.openExternal(url);
|
||||
}),
|
||||
});
|
||||
|
||||
/** Theme files are a few KB; anything larger returns empty text and lets the
|
||||
* renderer reject it by size without the contents ever crossing the bridge. */
|
||||
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
|
||||
|
||||
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
|
||||
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
// The VS Code extensions directory is the same dotfolder on Windows,
|
||||
// macOS, and Linux; when it is missing the picker opens wherever the
|
||||
// platform would by default.
|
||||
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
|
||||
const defaultPath = yield* fileSystem
|
||||
.exists(extensionsDir)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const paths = yield* dialog.pickFiles({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
|
||||
filters: [{ name: "JSON", extensions: ["json"] }],
|
||||
});
|
||||
if (paths.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.forEach(paths, (filePath) => {
|
||||
const name = path.basename(filePath);
|
||||
return Effect.gen(function* () {
|
||||
const info = yield* fileSystem.stat(filePath);
|
||||
const size = Number(info.size);
|
||||
if (size > PICKED_THEME_FILE_MAX_BYTES) {
|
||||
return { name, size, text: "" } satisfies PickedThemeFile;
|
||||
}
|
||||
const text = yield* fileSystem.readFileString(filePath);
|
||||
return { name, size, text } satisfies PickedThemeFile;
|
||||
}).pipe(
|
||||
// An unreadable file degrades to an entry the renderer reports.
|
||||
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
|
||||
);
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -97,7 +97,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
|
||||
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) =>
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
@@ -29,7 +30,6 @@ const clientSettings: ClientSettings = {
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
|
||||
@@ -52,7 +52,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
|
||||
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
Looking for older versions? Check the{" "}
|
||||
Looking for older versions? Check the
|
||||
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.2",
|
||||
version: "1.0.1",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
|
||||
+11
-11
@@ -100,13 +100,13 @@
|
||||
|
||||
@variant dark {
|
||||
/* Page backgrounds */
|
||||
--color-screen: #0a0a0a;
|
||||
--color-sheet: rgba(14, 14, 14, 0.98);
|
||||
--color-screen: #000000;
|
||||
--color-sheet: rgba(6, 6, 7, 0.98);
|
||||
|
||||
/* Card / surface */
|
||||
--color-card: #171717;
|
||||
--color-card-alt: #1c1c1c;
|
||||
--color-card-translucent: rgba(17, 17, 17, 0.8);
|
||||
--color-card: #111113;
|
||||
--color-card-alt: #171719;
|
||||
--color-card-translucent: rgba(13, 13, 15, 0.92);
|
||||
|
||||
/* Text */
|
||||
--color-foreground: #f5f5f5;
|
||||
@@ -143,7 +143,7 @@
|
||||
--color-danger-foreground: #fca5a5;
|
||||
|
||||
/* Inputs */
|
||||
--color-input: #141414;
|
||||
--color-input: #0d0d0f;
|
||||
--color-input-border: rgba(255, 255, 255, 0.08);
|
||||
--color-sidebar-search: rgba(118, 118, 128, 0.24);
|
||||
--color-placeholder: #8e8e93;
|
||||
@@ -154,13 +154,13 @@
|
||||
--color-icon-subtle: #8e8e93;
|
||||
|
||||
/* Header / glass chrome */
|
||||
--color-header: rgba(10, 10, 10, 0.97);
|
||||
--color-header: rgba(0, 0, 0, 0.97);
|
||||
--color-header-border: rgba(255, 255, 255, 0.06);
|
||||
--color-glass-surface: rgba(23, 23, 23, 0.78);
|
||||
--color-glass-tint: rgba(23, 23, 23, 0.24);
|
||||
--color-glass-surface: rgba(13, 13, 15, 0.92);
|
||||
--color-glass-tint: rgba(13, 13, 15, 0.24);
|
||||
|
||||
/* StatusBar */
|
||||
--color-status-bar: #0a0a0a;
|
||||
--color-status-bar: #000000;
|
||||
|
||||
/* Markdown */
|
||||
--color-md-body: #e5e5e5;
|
||||
@@ -183,7 +183,7 @@
|
||||
|
||||
/* Drawer / modal backdrop */
|
||||
--color-backdrop: rgba(0, 0, 0, 0.48);
|
||||
--color-drawer: rgba(14, 14, 14, 0.99);
|
||||
--color-drawer: rgba(6, 6, 7, 0.99);
|
||||
--color-drawer-shadow: rgba(0, 0, 0, 0.32);
|
||||
|
||||
/* Misc */
|
||||
|
||||
@@ -535,12 +535,6 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.isEmpty {
|
||||
feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
|
||||
lastAppliedBuffer = ""
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.hasPrefix(lastAppliedBuffer) {
|
||||
let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
|
||||
feedData(Data(suffix.utf8))
|
||||
|
||||
@@ -138,10 +138,5 @@
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
},
|
||||
"reanimated": {
|
||||
"staticFeatureFlags": {
|
||||
"DISABLE_COMMIT_PAUSING_MECHANISM": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,7 +47,6 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
@@ -176,13 +175,6 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Appearance",
|
||||
},
|
||||
}),
|
||||
SettingsProjectGrouping: createNativeStackScreen({
|
||||
screen: SettingsProjectGroupingRouteScreen,
|
||||
linking: "project-grouping",
|
||||
options: {
|
||||
title: "Project Grouping",
|
||||
},
|
||||
}),
|
||||
SettingsClientStorage: createNativeStackScreen({
|
||||
screen: SettingsClientStorageRouteScreen,
|
||||
linking: "client-storage",
|
||||
|
||||
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={props.onBack}
|
||||
className="-mr-2 size-11 items-center justify-center"
|
||||
className="size-11 items-center justify-center"
|
||||
>
|
||||
<SymbolView
|
||||
name="chevron.left"
|
||||
|
||||
@@ -50,6 +50,7 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPaperclip,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
@@ -61,6 +62,8 @@ import {
|
||||
IconServer,
|
||||
IconSettings,
|
||||
IconSparkles,
|
||||
IconStar,
|
||||
IconStarFilled,
|
||||
IconLayoutSidebarRight,
|
||||
IconTerminal2,
|
||||
IconTextDecrease,
|
||||
@@ -122,6 +125,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"line.3.horizontal.decrease.circle.fill": IconFilter,
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
paperclip: IconPaperclip,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
@@ -137,6 +141,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
"slider.horizontal.3": IconAdjustmentsHorizontal,
|
||||
"square.and.pencil": IconEdit,
|
||||
"square.split.2x1": IconLayoutColumns,
|
||||
star: IconStar,
|
||||
"star.fill": IconStarFilled,
|
||||
"stop.fill": IconPlayerStopFilled,
|
||||
terminal: IconTerminal2,
|
||||
"text.bubble": IconMessage,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import Constants from "expo-constants";
|
||||
import type {
|
||||
NativeStackHeaderItem,
|
||||
NativeStackNavigationOptions,
|
||||
@@ -8,7 +7,6 @@ import { Platform, View } from "react-native";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { T3Wordmark } from "./T3Wordmark";
|
||||
import { IPAD_HOME_TITLE_OFFSET } from "../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../lib/mobileBranding";
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
|
||||
@@ -16,18 +14,6 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
|
||||
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
|
||||
|
||||
/**
|
||||
* Horizontal correction applied to content rendered in the brand title slot,
|
||||
* shared with the connection-status swap so both align identically.
|
||||
*/
|
||||
export function brandTitleOffset(nativeLeadingItem: boolean): number {
|
||||
if (Platform.OS !== "ios") return 0;
|
||||
if (nativeLeadingItem) {
|
||||
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
|
||||
}
|
||||
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
@@ -38,9 +24,16 @@ export function CompactBrandTitle(
|
||||
) {
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
|
||||
const titleOffset =
|
||||
Platform.OS !== "ios"
|
||||
? 0
|
||||
: props.nativeLeadingItem
|
||||
? Platform.isPad
|
||||
? IPAD_NATIVE_LEADING_TITLE_OFFSET
|
||||
: IOS_NATIVE_LEADING_TITLE_OFFSET
|
||||
: Platform.isPad
|
||||
? IPAD_HOME_TITLE_OFFSET
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<View
|
||||
@@ -51,7 +44,7 @@ export function CompactBrandTitle(
|
||||
style={{
|
||||
alignItems: "center",
|
||||
flexDirection: "row",
|
||||
gap: 6,
|
||||
gap: 4,
|
||||
marginLeft: titleOffset,
|
||||
}}
|
||||
>
|
||||
@@ -66,26 +59,6 @@ export function CompactBrandTitle(
|
||||
>
|
||||
Code
|
||||
</Text>
|
||||
<View
|
||||
style={{
|
||||
backgroundColor: subtleColor,
|
||||
borderRadius: 999,
|
||||
paddingHorizontal: 6,
|
||||
paddingVertical: 2,
|
||||
}}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
color: mutedColor,
|
||||
fontFamily: "DMSans-Bold",
|
||||
fontSize: 9,
|
||||
letterSpacing: 0.9,
|
||||
textTransform: "uppercase",
|
||||
}}
|
||||
>
|
||||
{stageLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import Svg, { Circle } from "react-native-svg";
|
||||
|
||||
import { useThemeColor } from "../lib/useThemeColor";
|
||||
import { cn } from "../lib/cn";
|
||||
@@ -146,8 +147,9 @@ export function ComposerToolbarButton(props: {
|
||||
readonly minWidth?: number;
|
||||
readonly onPress?: () => void;
|
||||
readonly showChevron?: boolean;
|
||||
readonly size?: "default" | "compact";
|
||||
readonly textTransform?: "none" | "uppercase";
|
||||
readonly variant?: "default" | "primary" | "danger";
|
||||
readonly variant?: "default" | "ghost" | "primary" | "danger";
|
||||
readonly className?: string;
|
||||
readonly style?: StyleProp<ViewStyle>;
|
||||
}) {
|
||||
@@ -157,6 +159,7 @@ export function ComposerToolbarButton(props: {
|
||||
const primaryFg = useThemeColor("--color-primary-foreground");
|
||||
const dangerFg = useThemeColor("--color-danger-foreground");
|
||||
const variant = props.variant ?? "default";
|
||||
const isCompact = props.size === "compact";
|
||||
const isCircle = !props.label && props.showChevron === false;
|
||||
const defaultBorderColor = isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)";
|
||||
const activeBorderColor = isDarkMode ? "rgba(255,255,255,0.13)" : "rgba(0,0,0,0.1)";
|
||||
@@ -173,66 +176,86 @@ export function ComposerToolbarButton(props: {
|
||||
: primaryFg
|
||||
: variant === "danger"
|
||||
? dangerFg
|
||||
: iconColor;
|
||||
: variant === "ghost"
|
||||
? iconSubtle
|
||||
: iconColor;
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={props.accessibilityLabel ?? props.label}
|
||||
accessibilityRole="button"
|
||||
disabled={props.disabled}
|
||||
hitSlop={isCompact ? 4 : undefined}
|
||||
onPress={props.onPress}
|
||||
className={cn(
|
||||
// Default width cap lives in the class chain (not the inline style)
|
||||
// so callers can lift it with max-w-full — flex-filling pills in the
|
||||
// thread composer stretch to the row's edge. The numeric maxWidth
|
||||
// prop still wins via the inline style below.
|
||||
"h-11 max-w-[172px] flex-row items-center justify-center rounded-full active:opacity-70",
|
||||
isCircle ? "w-11" : "gap-2 px-3.5",
|
||||
"max-w-[172px] flex-row items-center justify-center rounded-full active:opacity-70",
|
||||
isCompact ? "h-9" : "h-11",
|
||||
isCircle ? (isCompact ? "w-9" : "w-11") : isCompact ? "gap-1.5 px-1.5" : "gap-2 px-3.5",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "bg-subtle-strong"
|
||||
: "bg-primary"
|
||||
: variant === "danger"
|
||||
? "bg-danger"
|
||||
: props.active
|
||||
? "bg-subtle-strong"
|
||||
: "bg-subtle",
|
||||
: variant === "ghost"
|
||||
? "bg-transparent"
|
||||
: props.active
|
||||
? "bg-subtle-strong"
|
||||
: "bg-subtle",
|
||||
props.className,
|
||||
)}
|
||||
style={({ pressed }) => [
|
||||
{
|
||||
borderColor:
|
||||
variant === "default"
|
||||
? props.active
|
||||
? activeBorderColor
|
||||
: defaultBorderColor
|
||||
: filledBorderColor,
|
||||
borderWidth: 1,
|
||||
variant === "ghost"
|
||||
? "transparent"
|
||||
: variant === "default"
|
||||
? props.active
|
||||
? activeBorderColor
|
||||
: defaultBorderColor
|
||||
: filledBorderColor,
|
||||
borderWidth: variant === "ghost" ? 0 : 1,
|
||||
maxWidth: props.maxWidth,
|
||||
minWidth: props.minWidth,
|
||||
opacity: props.disabled ? 0.55 : pressed ? 0.72 : 1,
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: isDarkMode ? 3 : 2 },
|
||||
shadowOpacity: props.disabled ? 0 : isDarkMode ? 0.24 : 0.08,
|
||||
shadowOpacity: props.disabled || variant === "ghost" ? 0 : isDarkMode ? 0.24 : 0.08,
|
||||
shadowRadius: isDarkMode ? 10 : 8,
|
||||
},
|
||||
props.style,
|
||||
]}
|
||||
>
|
||||
{props.iconNode ? (
|
||||
<View className="h-4 w-4 items-center justify-center">{props.iconNode}</View>
|
||||
<View
|
||||
className={cn("items-center justify-center", isCompact ? "h-4 w-4" : "h-[18px] w-[18px]")}
|
||||
>
|
||||
{props.iconNode}
|
||||
</View>
|
||||
) : props.icon ? (
|
||||
<SymbolView name={props.icon} size={16} tintColor={iconTintColor} type="monochrome" />
|
||||
<SymbolView
|
||||
name={props.icon}
|
||||
size={isCompact ? 16 : 18}
|
||||
tintColor={iconTintColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
{props.label ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-center text-sm font-t3-bold",
|
||||
"shrink text-center font-t3-bold",
|
||||
isCompact ? "text-sm" : "text-base",
|
||||
variant === "primary"
|
||||
? props.disabled
|
||||
? "text-foreground-muted"
|
||||
: "text-primary-foreground"
|
||||
: "text-foreground",
|
||||
: variant === "ghost"
|
||||
? "text-foreground-muted"
|
||||
: "text-foreground",
|
||||
)}
|
||||
ellipsizeMode="tail"
|
||||
numberOfLines={1}
|
||||
@@ -248,4 +271,49 @@ export function ComposerToolbarButton(props: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mobile composer keeps the web context-window affordance in the footer.
|
||||
* Usage is optional because the mobile thread shell does not always include a
|
||||
* context snapshot; in that case the quiet track still reserves the control.
|
||||
*/
|
||||
export function ComposerContextRing(props: { readonly usedPercentage?: number | null }) {
|
||||
const trackColor = useThemeColor("--color-border");
|
||||
const progressColor = useThemeColor("--color-icon-subtle");
|
||||
const normalizedPercentage = Math.max(0, Math.min(100, props.usedPercentage ?? 0));
|
||||
const radius = 7;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
|
||||
|
||||
return (
|
||||
<View
|
||||
accessible
|
||||
accessibilityLabel={
|
||||
props.usedPercentage == null
|
||||
? "Context window"
|
||||
: `Context window ${Math.round(normalizedPercentage)} percent used`
|
||||
}
|
||||
className="h-11 w-9 items-center justify-center"
|
||||
>
|
||||
<Svg width={20} height={20} viewBox="0 0 18 18">
|
||||
<Circle cx={9} cy={9} r={radius} fill="none" stroke={trackColor} strokeWidth={2.5} />
|
||||
{normalizedPercentage > 0 ? (
|
||||
<Circle
|
||||
cx={9}
|
||||
cy={9}
|
||||
r={radius}
|
||||
fill="none"
|
||||
rotation={-90}
|
||||
origin="9, 9"
|
||||
stroke={progressColor}
|
||||
strokeDasharray={`${circumference} ${circumference}`}
|
||||
strokeDashoffset={dashOffset}
|
||||
strokeLinecap="round"
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
) : null}
|
||||
</Svg>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export const ComposerToolbarTrigger = ComposerToolbarButton;
|
||||
@@ -0,0 +1,277 @@
|
||||
import type { ModelSelection, ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { FlatList, Keyboard, Modal, Platform, Pressable, TextInput, View } from "react-native";
|
||||
import { SafeAreaView, useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
buildModelPickerProviderGroups,
|
||||
type ModelOption,
|
||||
type ProviderGroup,
|
||||
} from "../lib/modelOptions";
|
||||
import { AppText as Text } from "./AppText";
|
||||
import { SymbolView } from "./AppSymbol";
|
||||
import { ProviderIcon } from "./ProviderIcon";
|
||||
|
||||
type ModelPickerListItem =
|
||||
| {
|
||||
readonly key: string;
|
||||
readonly type: "provider";
|
||||
readonly providerLabel: string;
|
||||
}
|
||||
| {
|
||||
readonly key: string;
|
||||
readonly type: "legacy";
|
||||
readonly providerKey: ProviderInstanceId;
|
||||
readonly count: number;
|
||||
readonly expanded: boolean;
|
||||
readonly searching: boolean;
|
||||
}
|
||||
| {
|
||||
readonly key: string;
|
||||
readonly type: "model";
|
||||
readonly option: ModelOption;
|
||||
};
|
||||
|
||||
function selectedModelKey(selection: ModelSelection | null): string | null {
|
||||
return selection ? `${selection.instanceId}:${selection.model}` : null;
|
||||
}
|
||||
|
||||
function favoriteModelsFirst(
|
||||
models: ReadonlyArray<ModelOption>,
|
||||
favoriteModelKeys: ReadonlySet<string>,
|
||||
): ReadonlyArray<ModelOption> {
|
||||
return models
|
||||
.map((model, index) => ({ model, index }))
|
||||
.sort((a, b) => {
|
||||
const favoriteDelta =
|
||||
Number(favoriteModelKeys.has(b.model.key)) - Number(favoriteModelKeys.has(a.model.key));
|
||||
return favoriteDelta === 0 ? a.index - b.index : favoriteDelta;
|
||||
})
|
||||
.map(({ model }) => model);
|
||||
}
|
||||
|
||||
export function ModelPickerSheet(props: {
|
||||
readonly visible: boolean;
|
||||
readonly groups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly favoriteModelKeys: ReadonlySet<string>;
|
||||
readonly favoritesEnabled: boolean;
|
||||
readonly onClose: () => void;
|
||||
readonly onSelectModel: (option: ModelOption) => void;
|
||||
readonly onToggleFavorite: (option: ModelOption) => void;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const [query, setQuery] = useState("");
|
||||
const [expandedLegacyProviders, setExpandedLegacyProviders] = useState(
|
||||
() => new Set<ProviderInstanceId>(),
|
||||
);
|
||||
const selectedKey = selectedModelKey(props.selectedModel);
|
||||
|
||||
useEffect(() => {
|
||||
if (!props.visible) return;
|
||||
setQuery("");
|
||||
const selectedLegacy = props.groups
|
||||
.flatMap((group) => group.models)
|
||||
.find((model) => model.key === selectedKey && model.isLegacy);
|
||||
setExpandedLegacyProviders(selectedLegacy ? new Set([selectedLegacy.providerKey]) : new Set());
|
||||
}, [props.groups, props.visible, selectedKey]);
|
||||
|
||||
const filteredGroups = useMemo(
|
||||
() => buildModelPickerProviderGroups(props.groups, query),
|
||||
[props.groups, query],
|
||||
);
|
||||
const searching = query.trim().length > 0;
|
||||
const listItems = useMemo(() => {
|
||||
const items: ModelPickerListItem[] = [];
|
||||
for (const group of filteredGroups) {
|
||||
items.push({
|
||||
key: `provider:${group.providerKey}`,
|
||||
type: "provider",
|
||||
providerLabel: group.providerLabel,
|
||||
});
|
||||
for (const option of favoriteModelsFirst(group.currentModels, props.favoriteModelKeys)) {
|
||||
items.push({ key: `model:${option.key}`, type: "model", option });
|
||||
}
|
||||
if (group.legacyModels.length > 0) {
|
||||
const expanded = searching || expandedLegacyProviders.has(group.providerKey);
|
||||
items.push({
|
||||
key: `legacy:${group.providerKey}`,
|
||||
type: "legacy",
|
||||
providerKey: group.providerKey,
|
||||
count: group.legacyModels.length,
|
||||
expanded,
|
||||
searching,
|
||||
});
|
||||
if (expanded) {
|
||||
for (const option of favoriteModelsFirst(group.legacyModels, props.favoriteModelKeys)) {
|
||||
items.push({ key: `model:${option.key}`, type: "model", option });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return items;
|
||||
}, [expandedLegacyProviders, filteredGroups, props.favoriteModelKeys, searching]);
|
||||
|
||||
const toggleLegacyProvider = (providerKey: ProviderInstanceId) => {
|
||||
setExpandedLegacyProviders((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(providerKey)) next.delete(providerKey);
|
||||
else next.add(providerKey);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal
|
||||
allowSwipeDismissal
|
||||
animationType="slide"
|
||||
onRequestClose={props.onClose}
|
||||
presentationStyle={Platform.OS === "ios" ? "pageSheet" : "fullScreen"}
|
||||
statusBarTranslucent={Platform.OS === "android"}
|
||||
visible={props.visible}
|
||||
>
|
||||
<SafeAreaView
|
||||
className="flex-1 bg-black"
|
||||
edges={["bottom"]}
|
||||
style={{ paddingTop: Platform.OS === "android" ? insets.top : 0 }}
|
||||
>
|
||||
<View className="items-center pb-1 pt-2">
|
||||
<View className="h-1.5 w-16 rounded-full bg-[#515157]" />
|
||||
</View>
|
||||
|
||||
<View className="h-[68px] flex-row items-center px-5">
|
||||
<Pressable
|
||||
accessibilityLabel="Close model picker"
|
||||
accessibilityRole="button"
|
||||
className="h-12 w-[92px] items-center justify-center rounded-full border border-white/10 bg-[#242426] active:opacity-70"
|
||||
onPress={props.onClose}
|
||||
>
|
||||
<Text className="text-lg font-t3-medium text-[#f4f4f5]">Cancel</Text>
|
||||
</Pressable>
|
||||
<Text className="flex-1 text-center text-xl font-t3-bold text-white">Choose model</Text>
|
||||
<View className="w-[92px]" />
|
||||
</View>
|
||||
|
||||
<View className="px-5 pb-3">
|
||||
<View className="h-[52px] flex-row items-center gap-3 rounded-full border border-white/10 bg-[#202022] px-4">
|
||||
<SymbolView name="magnifyingglass" size={22} tintColor="#f4f4f5" type="monochrome" />
|
||||
<TextInput
|
||||
accessibilityLabel="Search models"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="min-w-0 flex-1 text-lg text-white"
|
||||
clearButtonMode="while-editing"
|
||||
onChangeText={setQuery}
|
||||
placeholder="Search models"
|
||||
placeholderTextColor="#85858b"
|
||||
selectionColor="#60a5fa"
|
||||
value={query}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<FlatList
|
||||
data={listItems}
|
||||
keyExtractor={(item) => item.key}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 24) }}
|
||||
ListEmptyComponent={
|
||||
<View className="items-center px-8 py-16">
|
||||
<Text className="text-center text-base text-[#85858b]">
|
||||
{query.trim().length > 0
|
||||
? `No models match “${query.trim()}”.`
|
||||
: "No models found."}
|
||||
</Text>
|
||||
</View>
|
||||
}
|
||||
renderItem={({ item }) => {
|
||||
if (item.type === "provider") {
|
||||
return (
|
||||
<Text className="px-5 pb-3 pt-8 text-lg font-t3-bold text-[#85858b]">
|
||||
{item.providerLabel}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
if (item.type === "legacy") {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={`${item.expanded ? "Hide" : "Show"} ${item.count} legacy models`}
|
||||
accessibilityRole="button"
|
||||
className="mx-5 min-h-[58px] flex-row items-center border-b border-white/10 active:opacity-70"
|
||||
disabled={item.searching}
|
||||
onPress={() => toggleLegacyProvider(item.providerKey)}
|
||||
>
|
||||
<SymbolView name="archivebox" size={20} tintColor="#77777d" type="monochrome" />
|
||||
<Text className="ml-3 flex-1 text-base font-t3-medium text-[#a2a2a8]">
|
||||
Legacy models
|
||||
</Text>
|
||||
<Text className="mr-2 text-sm text-[#6f6f75]">{item.count}</Text>
|
||||
{!item.searching ? (
|
||||
<SymbolView
|
||||
name={item.expanded ? "chevron.up" : "chevron.down"}
|
||||
size={14}
|
||||
tintColor="#77777d"
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
const selected = item.option.key === selectedKey;
|
||||
const favorite = props.favoriteModelKeys.has(item.option.key);
|
||||
return (
|
||||
<View className="mx-5 min-h-[82px] flex-row items-center border-b border-white/10">
|
||||
<Pressable
|
||||
accessibilityLabel={`${item.option.label}, ${item.option.selection.model}`}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className="min-w-0 flex-1 flex-row items-center self-stretch active:opacity-70"
|
||||
onPress={() => {
|
||||
Keyboard.dismiss();
|
||||
props.onSelectModel(item.option);
|
||||
props.onClose();
|
||||
}}
|
||||
>
|
||||
<View className="w-12 items-start">
|
||||
<ProviderIcon provider={item.option.providerDriver} size={28} />
|
||||
</View>
|
||||
<View className="min-w-0 flex-1 py-3">
|
||||
<Text className="text-lg font-t3-bold text-[#f5f5f6]" numberOfLines={1}>
|
||||
{item.option.label}
|
||||
</Text>
|
||||
<Text className="mt-0.5 text-sm text-[#909096]" numberOfLines={1}>
|
||||
{item.option.selection.model}
|
||||
</Text>
|
||||
</View>
|
||||
{selected ? (
|
||||
<SymbolView name="checkmark" size={22} tintColor="#f5f5f6" type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityLabel={favorite ? "Remove from favorites" : "Add to favorites"}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: !props.favoritesEnabled }}
|
||||
className="ml-3 h-11 w-11 items-center justify-center active:opacity-60"
|
||||
disabled={!props.favoritesEnabled}
|
||||
hitSlop={4}
|
||||
onPress={() => props.onToggleFavorite(item.option)}
|
||||
style={{ opacity: props.favoritesEnabled ? 1 : 0.45 }}
|
||||
>
|
||||
<SymbolView
|
||||
name={favorite ? "star.fill" : "star"}
|
||||
size={23}
|
||||
tintColor={favorite ? "#facc15" : "#77777d"}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
</View>
|
||||
);
|
||||
}}
|
||||
/>
|
||||
</SafeAreaView>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -17,10 +17,7 @@ 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 THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
@@ -43,11 +42,6 @@ interface CloudEnvironmentRowsProps {
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*
|
||||
* Already-connected relay environments render even without cloud config or a
|
||||
* signed-in account — they are registered on this device and must stay
|
||||
* reachable and removable. Only discovery (the available list, refresh, and
|
||||
* its errors) requires a signed-in session.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
|
||||
@@ -56,33 +50,20 @@ export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
if (props.showcaseSignedIn !== undefined) {
|
||||
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
|
||||
}
|
||||
// No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
|
||||
if (!hasCloudPublicConfig()) {
|
||||
return <ConnectedOnlyCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
return <SignedInCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
|
||||
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
|
||||
if (!isSignedIn) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} />;
|
||||
}
|
||||
|
||||
function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
if (props.connectedCloudEnvironments.length === 0) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(
|
||||
props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
|
||||
) {
|
||||
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const discoveryAvailable = props.discoveryAvailable ?? true;
|
||||
const availableCloudEnvironments = discoveryAvailable
|
||||
? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
|
||||
: [];
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -108,27 +89,25 @@ function CloudEnvironmentRowsContent(
|
||||
{showHeader ? (
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
|
||||
{discoveryAvailable ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
) : null}
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -173,9 +152,7 @@ function CloudEnvironmentRowsContent(
|
||||
|
||||
{/* Rendered alongside any connected rows — a failed discovery must not
|
||||
hide behind an otherwise-healthy list. */}
|
||||
{discoveryAvailable &&
|
||||
controller.relayDiscovery.error &&
|
||||
!controller.relayDiscovery.isRefreshing ? (
|
||||
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
Could not load T3 Connect environments
|
||||
|
||||
@@ -58,8 +58,8 @@ export function ConnectionsRouteScreen() {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
|
||||
@@ -1,41 +1,36 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import Constants from "expo-constants";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
import type { SearchBarCommands } from "react-native-screens";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, TextInput, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { HOME_HORIZONTAL_INSET } from "../../lib/layoutMetrics";
|
||||
import { resolveMobileStageLabel } from "../../lib/mobileBranding";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import {
|
||||
createNativeMailSearchToolbarItem,
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { WorkspaceConnectionTitle } from "./WorkspaceConnectionTitle";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
type HomeListFilterMenuEnvironment,
|
||||
type HomeListFilterMenuProject,
|
||||
import type {
|
||||
HomeListFilterMenuEnvironment,
|
||||
HomeListFilterMenuProject,
|
||||
} from "./home-list-filter-menu";
|
||||
import {
|
||||
hasCustomHomeListOptions,
|
||||
PROJECT_SORT_OPTIONS,
|
||||
THREAD_SORT_OPTIONS,
|
||||
} from "./home-list-options";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
|
||||
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment;
|
||||
export type HomeHeaderEnvironment = HomeListFilterMenuEnvironment & {
|
||||
readonly connectionState: EnvironmentConnectionPhase;
|
||||
};
|
||||
|
||||
export function HomeHeader(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
readonly environments: ReadonlyArray<HomeHeaderEnvironment>;
|
||||
readonly projects: ReadonlyArray<HomeListFilterMenuProject>;
|
||||
readonly searchQuery: string;
|
||||
@@ -48,35 +43,27 @@ export function HomeHeader(props: {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
readonly onReconnectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
}) {
|
||||
if (Platform.OS === "android") {
|
||||
return <AndroidHomeHeader {...props} />;
|
||||
}
|
||||
|
||||
return <IosHomeHeader {...props} />;
|
||||
}
|
||||
|
||||
type HomeHeaderProps = Parameters<typeof HomeHeader>[0];
|
||||
|
||||
function checkedMenuState(checked: boolean) {
|
||||
return checked ? ("on" as const) : undefined;
|
||||
}
|
||||
|
||||
function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const searchInputRef = useRef<TextInput>(null);
|
||||
const [searchVisible, setSearchVisible] = useState(props.searchQuery.length > 0);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
|
||||
const focusSearch = useCallback(() => {
|
||||
setSearchVisible(true);
|
||||
searchInputRef.current?.focus();
|
||||
return true;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
useEffect(() => {
|
||||
if (searchVisible) searchInputRef.current?.focus();
|
||||
}, [searchVisible]);
|
||||
|
||||
const menuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -86,12 +73,15 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
{
|
||||
id: "environment:all",
|
||||
title: "All environments",
|
||||
state: checkedMenuState(props.selectedEnvironmentId === null),
|
||||
state: props.selectedEnvironmentId === null ? "on" : undefined,
|
||||
},
|
||||
...props.environments.map((environment) => ({
|
||||
id: `environment:${environment.environmentId}`,
|
||||
title: environment.label,
|
||||
state: checkedMenuState(props.selectedEnvironmentId === environment.environmentId),
|
||||
state:
|
||||
props.selectedEnvironmentId === environment.environmentId
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
],
|
||||
},
|
||||
@@ -105,12 +95,12 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
{
|
||||
id: "project:all",
|
||||
title: "All projects",
|
||||
state: checkedMenuState(props.selectedProjectKey === null),
|
||||
state: props.selectedProjectKey === null ? ("on" as const) : undefined,
|
||||
},
|
||||
...props.projects.map((project) => ({
|
||||
id: `project:${project.key}`,
|
||||
title: project.label,
|
||||
state: checkedMenuState(props.selectedProjectKey === project.key),
|
||||
state: props.selectedProjectKey === project.key ? ("on" as const) : undefined,
|
||||
})),
|
||||
],
|
||||
},
|
||||
@@ -124,7 +114,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
subactions: PROJECT_SORT_OPTIONS.map((option) => ({
|
||||
id: `project-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.projectSortOrder === option.value),
|
||||
state: props.projectSortOrder === option.value ? ("on" as const) : undefined,
|
||||
})),
|
||||
},
|
||||
{
|
||||
@@ -133,10 +123,11 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
subactions: THREAD_SORT_OPTIONS.map((option) => ({
|
||||
id: `thread-sort:${option.value}`,
|
||||
title: option.label,
|
||||
state: checkedMenuState(props.threadSortOrder === option.value),
|
||||
state: props.threadSortOrder === option.value ? ("on" as const) : undefined,
|
||||
})),
|
||||
},
|
||||
] satisfies MenuAction[])),
|
||||
{ id: "settings", title: "Settings", image: "gearshape" },
|
||||
],
|
||||
[
|
||||
props.environments,
|
||||
@@ -148,30 +139,30 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
threadListV2Enabled,
|
||||
],
|
||||
);
|
||||
|
||||
const handleMenuAction = useCallback(
|
||||
(event: { nativeEvent: { event: string } }) => {
|
||||
const id = event.nativeEvent.event;
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
const id = nativeEvent.event;
|
||||
if (id === "settings") {
|
||||
props.onOpenSettings();
|
||||
return;
|
||||
}
|
||||
if (id === "environment:all") {
|
||||
props.onEnvironmentChange(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (id.startsWith("environment:")) {
|
||||
const environmentId = id.slice("environment:".length);
|
||||
const environment = props.environments.find(
|
||||
(candidate) => candidate.environmentId === environmentId,
|
||||
);
|
||||
if (environment) {
|
||||
props.onEnvironmentChange(environment.environmentId);
|
||||
}
|
||||
if (environment) props.onEnvironmentChange(environment.environmentId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (id === "project:all") {
|
||||
props.onProjectChange(null);
|
||||
return;
|
||||
}
|
||||
|
||||
if (id.startsWith("project:")) {
|
||||
const projectKey = id.slice("project:".length);
|
||||
if (props.projects.some((project) => project.key === projectKey)) {
|
||||
@@ -179,7 +170,6 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const projectSort = PROJECT_SORT_OPTIONS.find(
|
||||
(option) => id === `project-sort:${option.value}`,
|
||||
);
|
||||
@@ -187,290 +177,161 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
props.onProjectSortOrderChange(projectSort.value);
|
||||
return;
|
||||
}
|
||||
|
||||
const threadSort = THREAD_SORT_OPTIONS.find((option) => id === `thread-sort:${option.value}`);
|
||||
if (threadSort) {
|
||||
props.onThreadSortOrderChange(threadSort.value);
|
||||
return;
|
||||
}
|
||||
if (threadSort) props.onThreadSortOrderChange(threadSort.value);
|
||||
},
|
||||
[props],
|
||||
);
|
||||
|
||||
const troubledEnvironment =
|
||||
(props.selectedEnvironmentId === null
|
||||
? undefined
|
||||
: props.environments.find(
|
||||
(environment) =>
|
||||
environment.environmentId === props.selectedEnvironmentId &&
|
||||
environment.connectionState !== "connected",
|
||||
)) ??
|
||||
props.environments.find(
|
||||
(environment) =>
|
||||
environment.connectionState === "connecting" ||
|
||||
environment.connectionState === "reconnecting",
|
||||
) ??
|
||||
props.environments.find((environment) => environment.connectionState !== "connected") ??
|
||||
props.environments[0];
|
||||
const selectedEnvironment =
|
||||
props.selectedEnvironmentId === null
|
||||
? null
|
||||
: (props.environments.find(
|
||||
(environment) => environment.environmentId === props.selectedEnvironmentId,
|
||||
) ?? null);
|
||||
const selectedProjectLabel =
|
||||
props.projects.find((project) => project.key === props.selectedProjectKey)?.label ??
|
||||
"All projects";
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View
|
||||
className="border-b border-header-border bg-header pb-3"
|
||||
style={{
|
||||
paddingHorizontal: HOME_HORIZONTAL_INSET,
|
||||
paddingTop: Math.max(insets.top, 12),
|
||||
backgroundColor: "#000",
|
||||
borderBottomColor: "rgba(255,255,255,0.06)",
|
||||
borderBottomWidth: 1,
|
||||
paddingTop: insets.top,
|
||||
}}
|
||||
>
|
||||
<View className="w-full max-w-[720px] self-center gap-3">
|
||||
<View className="flex-row items-center gap-2.5">
|
||||
{/* Brand slot doubles as the connection status surface: while an
|
||||
environment reconnects, the lockup fades to a status label in
|
||||
place (no layout shift in the list below). */}
|
||||
<WorkspaceConnectionTitle
|
||||
grow
|
||||
onPress={props.onOpenEnvironments}
|
||||
brand={
|
||||
<View className="flex-row items-center gap-2">
|
||||
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
|
||||
<T3Wordmark color={iconColor} height={15} />
|
||||
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
|
||||
<View className="h-14 flex-row items-center px-4">
|
||||
<View className="min-w-0 flex-1">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
environmentLabel={troubledEnvironment?.label}
|
||||
environmentConnectionState={troubledEnvironment?.connectionState}
|
||||
onPress={props.onOpenSettings}
|
||||
onReconnect={
|
||||
troubledEnvironment
|
||||
? () => props.onReconnectEnvironment(troubledEnvironment.environmentId)
|
||||
: undefined
|
||||
}
|
||||
variant="header"
|
||||
fallback={
|
||||
<View
|
||||
accessibilityLabel="T3 Code, Threads"
|
||||
accessibilityRole="header"
|
||||
className="flex-row items-center gap-2"
|
||||
>
|
||||
<T3Wordmark color="#f5f5f5" height={16} />
|
||||
<Text className="text-[21px] font-t3-medium tracking-[-0.5px] text-[#8e8e93]">
|
||||
Code
|
||||
</RNText>
|
||||
<View className="rounded-full bg-subtle px-2 py-0.75">
|
||||
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
|
||||
{stageLabel}
|
||||
</RNText>
|
||||
</View>
|
||||
</Text>
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
|
||||
<ControlPillMenu
|
||||
actions={menuActions}
|
||||
isAnchoredToRight
|
||||
onPressAction={handleMenuAction}
|
||||
>
|
||||
<Pressable
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
accessibilityRole="button"
|
||||
className="size-11 items-center justify-center rounded-full bg-subtle"
|
||||
>
|
||||
<SymbolView
|
||||
name={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
size={16}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
{/* Built identically to the filter button so the two circles
|
||||
match exactly (ControlPill sizes via Tailwind classes and
|
||||
resolves to a different box). */}
|
||||
<Pressable
|
||||
accessibilityLabel="Open settings"
|
||||
accessibilityRole="button"
|
||||
onPress={props.onOpenSettings}
|
||||
className="size-11 items-center justify-center rounded-full bg-subtle"
|
||||
>
|
||||
<SymbolView name="gearshape" size={18} tintColor={iconColor} type="monochrome" />
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View className="min-h-12 flex-row items-center gap-2.5 rounded-2xl border border-input-border bg-input px-3.5">
|
||||
<SymbolView name="magnifyingglass" size={17} tintColor={mutedColor} type="monochrome" />
|
||||
<TextInput
|
||||
accessibilityLabel="Search threads"
|
||||
autoCapitalize="none"
|
||||
onChangeText={props.onSearchQueryChange}
|
||||
placeholder="Search threads"
|
||||
placeholderTextColorClassName="accent-placeholder"
|
||||
className="flex-1 py-2.5 text-base font-sans text-foreground"
|
||||
value={props.searchQuery}
|
||||
<Pressable
|
||||
accessibilityLabel={searchVisible ? "Close thread search" : "Search threads"}
|
||||
accessibilityRole="button"
|
||||
className="size-12 items-center justify-center"
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
if (searchVisible) {
|
||||
props.onSearchQueryChange("");
|
||||
setSearchVisible(false);
|
||||
} else {
|
||||
setSearchVisible(true);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SymbolView
|
||||
name={searchVisible ? "xmark" : "magnifyingglass"}
|
||||
size={20}
|
||||
tintColor="#b9bbc2"
|
||||
type="monochrome"
|
||||
/>
|
||||
{props.searchQuery.length > 0 ? (
|
||||
<Pressable
|
||||
accessibilityLabel="Clear search"
|
||||
hitSlop={10}
|
||||
onPress={() => props.onSearchQueryChange("")}
|
||||
>
|
||||
<SymbolView
|
||||
name="xmark.circle.fill"
|
||||
size={17}
|
||||
tintColor={mutedColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</Pressable>
|
||||
<ControlPillMenu actions={menuActions} isAnchoredToRight onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel="Filter threads and open settings"
|
||||
accessibilityRole="button"
|
||||
className="size-12 items-center justify-center"
|
||||
hitSlop={4}
|
||||
>
|
||||
<SymbolView
|
||||
name={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
size={20}
|
||||
tintColor="#b9bbc2"
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
|
||||
<View className="h-11 flex-row items-center px-4">
|
||||
{searchVisible ? (
|
||||
<>
|
||||
<SymbolView name="magnifyingglass" size={16} tintColor="#71717a" type="monochrome" />
|
||||
<TextInput
|
||||
ref={searchInputRef}
|
||||
accessibilityLabel="Search threads"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
className="ml-2 flex-1 py-0 text-base font-sans text-white"
|
||||
onChangeText={props.onSearchQueryChange}
|
||||
placeholder="Search threads"
|
||||
placeholderTextColor="#52525b"
|
||||
returnKeyType="search"
|
||||
value={props.searchQuery}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<View className="flex-1">
|
||||
<ControlPillMenu actions={menuActions} onPressAction={handleMenuAction}>
|
||||
<Pressable
|
||||
accessibilityLabel={`Project filter, ${selectedProjectLabel}`}
|
||||
accessibilityRole="button"
|
||||
className="h-11 w-full flex-row items-center"
|
||||
>
|
||||
<SymbolView name="folder" size={16} tintColor="#71717a" type="monochrome" />
|
||||
<Text
|
||||
className="ml-2 max-w-[70%] text-sm font-t3-medium text-[#8e8e93]"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{selectedProjectLabel}
|
||||
</Text>
|
||||
<SymbolView name="chevron.down" size={10} tintColor="#636366" type="monochrome" />
|
||||
{selectedEnvironment ? (
|
||||
<Text className="ml-2 text-xs text-[#71717a]" numberOfLines={1}>
|
||||
{selectedEnvironment.label}
|
||||
</Text>
|
||||
) : null}
|
||||
</Pressable>
|
||||
</ControlPillMenu>
|
||||
</View>
|
||||
)}
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
const focusSearch = useCallback(() => {
|
||||
searchBarRef.current?.focus();
|
||||
return searchBarRef.current !== null;
|
||||
}, []);
|
||||
useHardwareKeyboardCommand("focusSearch", focusSearch);
|
||||
const filterMenu = buildHomeListFilterMenu({
|
||||
...props,
|
||||
listOrganization: !threadListV2Enabled,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={filterMenu.items}
|
||||
options={{
|
||||
// Static header config (glass, title, fonts) lives in Stack.tsx
|
||||
// (GLASS_HEADER_OPTIONS). Only dynamic values are set here.
|
||||
headerTintColor: iconColor,
|
||||
unstable_headerRightItems:
|
||||
Platform.OS === "ios"
|
||||
? () => [
|
||||
withNativeGlassHeaderItem({
|
||||
accessibilityLabel: "Open settings",
|
||||
icon: { name: "ellipsis", type: "sfSymbol" } as const,
|
||||
identifier: "home-settings",
|
||||
label: "",
|
||||
onPress: props.onOpenSettings,
|
||||
type: "button",
|
||||
}),
|
||||
]
|
||||
: undefined,
|
||||
// The keys below are set per-branch (not `undefined`) so a later
|
||||
// reapply cannot clobber options owned by NativeHeaderToolbar.
|
||||
...(NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED
|
||||
? {
|
||||
unstable_headerToolbarItems: () => [
|
||||
createNativeMailSearchToolbarItem({
|
||||
composeButtonId: "home-new-task",
|
||||
composeSystemImageName: "square.and.pencil",
|
||||
filterMenu,
|
||||
filterButtonId: "home-filter",
|
||||
filterSystemImageName: hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease",
|
||||
onComposePress: props.onStartNewTask,
|
||||
onSearchTextChange: props.onSearchQueryChange,
|
||||
placeholder: "Search",
|
||||
searchTextChangeId: "home-search-text",
|
||||
}),
|
||||
],
|
||||
}
|
||||
: {
|
||||
// Pre-Liquid-Glass iOS: standard pull-down search in the nav
|
||||
// bar; create + sort live in the plain bottom toolbar below.
|
||||
headerSearchBarOptions: {
|
||||
ref: searchBarRef,
|
||||
autoCapitalize: "none" as const,
|
||||
hideNavigationBar: false,
|
||||
placeholder: "Search",
|
||||
onCancelButtonPress: () => {
|
||||
props.onSearchQueryChange("");
|
||||
},
|
||||
onChangeText: (event) => {
|
||||
props.onSearchQueryChange(event.nativeEvent.text);
|
||||
},
|
||||
},
|
||||
}),
|
||||
}}
|
||||
/>
|
||||
|
||||
{NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED ? null : (
|
||||
<NativeHeaderToolbar placement="bottom">
|
||||
<NativeHeaderToolbar.Menu
|
||||
accessibilityLabel="Filter and sort threads"
|
||||
icon={
|
||||
hasCustomListOptions
|
||||
? "line.3.horizontal.decrease.circle.fill"
|
||||
: "line.3.horizontal.decrease.circle"
|
||||
}
|
||||
title="Thread list options"
|
||||
separateBackground
|
||||
>
|
||||
<NativeHeaderToolbar.Menu title="Environment">
|
||||
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedEnvironmentId === null}
|
||||
onPress={() => props.onEnvironmentChange(null)}
|
||||
subtitle="Show threads from every environment"
|
||||
>
|
||||
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.environments.map((environment) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={environment.environmentId}
|
||||
isOn={props.selectedEnvironmentId === environment.environmentId}
|
||||
onPress={() => props.onEnvironmentChange(environment.environmentId)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
|
||||
{props.projects.length > 0 ? (
|
||||
<NativeHeaderToolbar.Menu title="Project">
|
||||
<NativeHeaderToolbar.Label>Project</NativeHeaderToolbar.Label>
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
isOn={props.selectedProjectKey === null}
|
||||
onPress={() => props.onProjectChange(null)}
|
||||
subtitle="Show threads from every project"
|
||||
>
|
||||
<NativeHeaderToolbar.Label>All projects</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
{props.projects.map((project) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={project.key}
|
||||
isOn={props.selectedProjectKey === project.key}
|
||||
onPress={() => props.onProjectChange(project.key)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{project.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
) : null}
|
||||
|
||||
{threadListV2Enabled ? null : (
|
||||
<NativeHeaderToolbar.Menu title="Sort projects">
|
||||
<NativeHeaderToolbar.Label>Sort projects</NativeHeaderToolbar.Label>
|
||||
{PROJECT_SORT_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.projectSortOrder === option.value}
|
||||
onPress={() => props.onProjectSortOrderChange(option.value)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
)}
|
||||
|
||||
{threadListV2Enabled ? null : (
|
||||
<NativeHeaderToolbar.Menu title="Sort threads">
|
||||
<NativeHeaderToolbar.Label>Sort threads</NativeHeaderToolbar.Label>
|
||||
{THREAD_SORT_OPTIONS.map((option) => (
|
||||
<NativeHeaderToolbar.MenuAction
|
||||
key={option.value}
|
||||
isOn={props.threadSortOrder === option.value}
|
||||
onPress={() => props.onThreadSortOrderChange(option.value)}
|
||||
>
|
||||
<NativeHeaderToolbar.Label>{option.label}</NativeHeaderToolbar.Label>
|
||||
</NativeHeaderToolbar.MenuAction>
|
||||
))}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
)}
|
||||
</NativeHeaderToolbar.Menu>
|
||||
<NativeHeaderToolbar.Spacer flexible />
|
||||
<NativeHeaderToolbar.Button
|
||||
accessibilityLabel="New task"
|
||||
icon="square.and.pencil"
|
||||
onPress={props.onStartNewTask}
|
||||
separateBackground
|
||||
/>
|
||||
</NativeHeaderToolbar>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -2,24 +2,27 @@ import * as Arr from "effect/Array";
|
||||
import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import {
|
||||
useRemoteConnections,
|
||||
useSavedRemoteConnections,
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { WorkspaceEmptyDetail } from "../layout/WorkspaceEmptyDetail";
|
||||
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { checkForAppUpdateOnLaunch } from "../updates/app-updates";
|
||||
import { AndroidHomeFabLayout } from "./AndroidHomeFab";
|
||||
import { HomeScreen } from "./HomeScreen";
|
||||
import { HomeHeader } from "./HomeHeader";
|
||||
import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { resolveHomeEnvironmentConnectionPhase } from "./workspace-connection-status";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -29,6 +32,7 @@ export function HomeRouteScreen() {
|
||||
const threads = useThreadShells();
|
||||
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const { onReconnectEnvironment } = useRemoteConnections();
|
||||
const navigation = useNavigation();
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
|
||||
@@ -44,7 +48,6 @@ export function HomeRouteScreen() {
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -59,12 +62,14 @@ export function HomeRouteScreen() {
|
||||
Object.values(savedConnectionsById).map((connection) => ({
|
||||
environmentId: connection.environmentId,
|
||||
label: connection.environmentLabel,
|
||||
connectionState:
|
||||
connectionStateByEnvironmentId.get(connection.environmentId) ?? "available",
|
||||
connectionState: resolveHomeEnvironmentConnectionPhase(
|
||||
connectionStateByEnvironmentId.get(connection.environmentId),
|
||||
catalogState.isLoadingConnections,
|
||||
),
|
||||
})),
|
||||
Order.mapInput(Order.String, (environment: { readonly label: string }) => environment.label),
|
||||
);
|
||||
}, [savedConnectionsById, workspaceEnvironments]);
|
||||
}, [catalogState.isLoadingConnections, savedConnectionsById, workspaceEnvironments]);
|
||||
const availableEnvironmentIds = useMemo(
|
||||
() => new Set(environments.map((environment) => environment.environmentId)),
|
||||
[environments],
|
||||
@@ -104,7 +109,12 @@ export function HomeRouteScreen() {
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions
|
||||
options={{ title: "", headerTitle: "", unstable_headerLeftItems: () => [] }}
|
||||
options={{
|
||||
headerShown: true,
|
||||
title: "",
|
||||
headerTitle: "",
|
||||
unstable_headerLeftItems: () => [],
|
||||
}}
|
||||
/>
|
||||
<WorkspaceSidebarToolbar
|
||||
afterSidebarButton={
|
||||
@@ -123,94 +133,80 @@ export function HomeRouteScreen() {
|
||||
}
|
||||
|
||||
return (
|
||||
<AndroidHomeFabLayout
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title after the split branch blanks the detail
|
||||
header. The brand slot doubles as the connection status surface:
|
||||
while an environment reconnects, the lockup fades to a status label
|
||||
in place (no layout shift in the list below). */}
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
<View className="flex-1 bg-black">
|
||||
<HomeHeader
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
/>
|
||||
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
// Settled threads are live shells: opening one is plain
|
||||
// navigation, and sending a message un-settles server-side.
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
}}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
onNewThreadInProject={(project) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(project.environmentId),
|
||||
projectId: String(project.id),
|
||||
title: project.title,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
pendingTasks={pendingTasks}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</>
|
||||
</AndroidHomeFabLayout>
|
||||
<HomeScreen
|
||||
catalogState={catalogState}
|
||||
environments={environments}
|
||||
onAddConnection={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
|
||||
}
|
||||
onArchiveThread={archiveThread}
|
||||
onDeleteThread={confirmDeleteThread}
|
||||
onSettleThread={settleThread}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
onSelectThread={(thread) => {
|
||||
// Settled threads are live shells: opening one is plain
|
||||
// navigation, and sending a message un-settles server-side.
|
||||
navigation.navigate("Thread", {
|
||||
environmentId: thread.environmentId,
|
||||
threadId: thread.id,
|
||||
});
|
||||
}}
|
||||
onSelectPendingTask={openPendingTask}
|
||||
onDeletePendingTask={confirmDeletePendingTask}
|
||||
onNewThreadInProject={(project) => {
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: String(project.environmentId),
|
||||
projectId: String(project.id),
|
||||
title: project.title,
|
||||
},
|
||||
});
|
||||
}}
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
onThreadSortOrderChange={setThreadSortOrder}
|
||||
pendingTasks={pendingTasks}
|
||||
projectGroupingMode={listOptions.projectGroupingMode}
|
||||
projects={projects}
|
||||
projectSortOrder={listOptions.projectSortOrder}
|
||||
savedConnectionsById={savedConnectionsById}
|
||||
searchQuery={searchQuery}
|
||||
selectedEnvironmentId={selectedEnvironmentId}
|
||||
selectedProjectKey={selectedProjectKey}
|
||||
threads={threads}
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
threadSearchMatchKey,
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
@@ -20,17 +19,16 @@ import type {
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ActivityIndicator, FlatList, Platform, Pressable, View } from "react-native";
|
||||
import { FlatList, Platform, Pressable, View } from "react-native";
|
||||
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import type { WorkspaceEnvironment, WorkspaceState } from "../../state/workspaceModel";
|
||||
import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadSearch } from "../../state/queries";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
@@ -96,6 +94,7 @@ interface HomeScreenProps {
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -111,10 +110,6 @@ interface HomeScreenProps {
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onMovePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -122,14 +117,7 @@ interface HomeScreenProps {
|
||||
|
||||
/* ─── Layout constants ───────────────────────────────────────────────── */
|
||||
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 72;
|
||||
const PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT = 44;
|
||||
/**
|
||||
* Top spacing between the list and the Android custom header. The Android
|
||||
* header (AndroidHomeHeader) is rendered in-flow above this screen and
|
||||
* already consumes the top safe-area inset, so the list only needs breathing
|
||||
* room here.
|
||||
*/
|
||||
const ESTIMATED_THREAD_ROW_HEIGHT = 92;
|
||||
|
||||
function deriveEmptyState(props: {
|
||||
readonly catalogState: WorkspaceState;
|
||||
@@ -194,10 +182,6 @@ function deriveEmptyState(props: {
|
||||
};
|
||||
}
|
||||
|
||||
function HomeTopContentSpacer() {
|
||||
return <View className="h-4" />;
|
||||
}
|
||||
|
||||
/* ─── Main screen ────────────────────────────────────────────────────── */
|
||||
|
||||
export function HomeScreen(props: HomeScreenProps) {
|
||||
@@ -210,11 +194,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
const insets = useSafeAreaInsets();
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const iosBottomToolbarClearance =
|
||||
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? PRE_LIQUID_GLASS_BOTTOM_TOOLBAR_HEIGHT
|
||||
: 0;
|
||||
const searchEnvironmentIds = useMemo(
|
||||
() =>
|
||||
props.selectedEnvironmentId === null
|
||||
@@ -418,6 +397,16 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
return map;
|
||||
}, [props.projects]);
|
||||
|
||||
const connectionStateByEnvironmentId = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
props.environments.map(
|
||||
(environment) => [environment.environmentId, environment.connectionState] as const,
|
||||
),
|
||||
),
|
||||
[props.environments],
|
||||
);
|
||||
|
||||
const v2ProjectScopeKey = props.selectedProjectKey;
|
||||
const v2ScopeProjects = useMemo(
|
||||
() =>
|
||||
@@ -526,12 +515,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onPinThread],
|
||||
);
|
||||
const handleMovePinnedThread = useCallback(
|
||||
(thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
void props.onMovePinnedThread(thread, direction);
|
||||
},
|
||||
[props.onMovePinnedThread],
|
||||
);
|
||||
const handleUnpinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnpinThread(thread);
|
||||
@@ -606,29 +589,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
props.threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, props.threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -725,11 +685,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item, index }: { readonly item: ThreadListV2ListItem; readonly index: number }) => {
|
||||
const nextItem = threadListV2Items[index + 1];
|
||||
const showTrailingDivider =
|
||||
nextItem?.type === "v2-thread" ||
|
||||
(nextItem?.type === "v2-pending" && !nextItem.showPendingDivider);
|
||||
({ item }: { readonly item: ThreadListV2ListItem }) => {
|
||||
if (item.type === "v2-pending") {
|
||||
const pendingScopeKey = scopedProjectKey(
|
||||
item.pendingTask.message.environmentId,
|
||||
@@ -741,13 +697,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
project={projectByKey.get(pendingScopeKey) ?? null}
|
||||
projectTitle={v2ProjectTitleByProjectKey.get(pendingScopeKey)}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null)
|
||||
: null
|
||||
props.savedConnectionsById[item.pendingTask.message.environmentId]
|
||||
?.environmentLabel ?? null
|
||||
}
|
||||
environmentConnectionState={connectionStateByEnvironmentId.get(
|
||||
item.pendingTask.message.environmentId,
|
||||
)}
|
||||
showPendingDivider={item.showPendingDivider}
|
||||
showTrailingDivider={showTrailingDivider}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
@@ -780,7 +736,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
showTrailingDivider={showTrailingDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
@@ -797,10 +752,9 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
)?.driver ?? null
|
||||
}
|
||||
environmentLabel={
|
||||
Object.keys(props.savedConnectionsById).length > 1
|
||||
? (props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null)
|
||||
: null
|
||||
props.savedConnectionsById[thread.environmentId]?.environmentLabel ?? null
|
||||
}
|
||||
environmentConnectionState={connectionStateByEnvironmentId.get(thread.environmentId)}
|
||||
searchMatch={threadSearchMatchByKey.get(
|
||||
threadSearchMatchKey({
|
||||
environmentId: thread.environmentId,
|
||||
@@ -815,18 +769,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
|
||||
canMovePinnedUp={arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0}
|
||||
canMovePinnedDown={(() => {
|
||||
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
|
||||
return index !== -1 && index < arrangedPinnedKeys.length - 1;
|
||||
})()}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onPinThread={handlePinThread}
|
||||
onUnpinThread={handleUnpinThread}
|
||||
onMovePinnedThread={handleMovePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
@@ -839,8 +786,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
@@ -850,7 +795,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
pinReorderEnvironmentIds,
|
||||
connectionStateByEnvironmentId,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
@@ -861,7 +806,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
@@ -877,6 +821,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
// HomeScreen render.
|
||||
const v2ExtraData = useMemo(
|
||||
() => ({
|
||||
connectionStateByEnvironmentId,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey: v2ProjectTitleByProjectKey,
|
||||
@@ -887,6 +832,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
threadSearchMatchByKey,
|
||||
}),
|
||||
[
|
||||
connectionStateByEnvironmentId,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.searchQuery,
|
||||
@@ -1017,22 +963,34 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
? null
|
||||
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
|
||||
"this environment");
|
||||
// Connection state surfaces in the header title slot
|
||||
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
|
||||
// reconnects never shift the rows.
|
||||
const emptyState = deriveEmptyState({
|
||||
catalogState: props.catalogState,
|
||||
projectCount: props.projects.length,
|
||||
});
|
||||
const composeAction = (
|
||||
<Pressable
|
||||
accessibilityLabel="New task"
|
||||
accessibilityRole="button"
|
||||
className="absolute right-4 size-14 items-center justify-center rounded-full bg-white"
|
||||
onPress={props.onStartNewTask}
|
||||
style={({ pressed }) => ({
|
||||
bottom: Math.max(insets.bottom, 16) + 9,
|
||||
opacity: pressed ? 0.72 : 1,
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 10 },
|
||||
shadowOpacity: 0.7,
|
||||
shadowRadius: 26,
|
||||
})}
|
||||
>
|
||||
<SymbolView name="square.and.pencil" size={22} tintColor="#000" type="monochrome" />
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
if (!hasAnyThreads) {
|
||||
return (
|
||||
<View
|
||||
className="flex-1 items-center justify-center bg-screen px-8"
|
||||
style={{
|
||||
paddingBottom: Math.max(insets.bottom, 24) + iosBottomToolbarClearance,
|
||||
paddingTop: NATIVE_LIQUID_GLASS_SUPPORTED ? insets.top + 72 : 0,
|
||||
}}
|
||||
className="flex-1 items-center justify-center px-8"
|
||||
style={{ backgroundColor: "#000", paddingBottom: Math.max(insets.bottom, 24) }}
|
||||
>
|
||||
<View className="w-full max-w-[430px]">
|
||||
<EmptyState
|
||||
@@ -1042,21 +1000,15 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{composeAction}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
|
||||
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
// mobile — the menu is the one filter surface).
|
||||
const v2ListHeader = listHeader;
|
||||
const listHeader = null;
|
||||
|
||||
const listEmpty = !hasResults ? (
|
||||
hasSearchQuery && threadSearch.isPending ? null : hasSearchQuery ? (
|
||||
@@ -1093,14 +1045,14 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
|
||||
if (threadListV2Enabled) {
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<View className="flex-1" style={{ backgroundColor: "#000" }}>
|
||||
<SwipeableScrollGateProvider enabled={swipeEnabled}>
|
||||
<FlatList
|
||||
data={threadListV2Items}
|
||||
renderItem={renderV2Item}
|
||||
keyExtractor={v2KeyExtractor}
|
||||
extraData={v2ExtraData}
|
||||
ListHeaderComponent={v2ListHeader}
|
||||
ListHeaderComponent={listHeader}
|
||||
ListFooterComponent={
|
||||
settledShelfExpanded && threadListV2Layout.hiddenSettledCount > 0 ? (
|
||||
<Pressable
|
||||
@@ -1118,27 +1070,25 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
ListEmptyComponent={v2ListEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={Platform.OS === "ios"}
|
||||
contentInsetAdjustmentBehavior={Platform.OS === "ios" ? "automatic" : "never"}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
{...scrollGateHandlers}
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 96 + iosBottomToolbarClearance
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
paddingBottom: Math.max(insets.bottom, 16) + 80,
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{composeAction}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<View className="flex-1" style={{ backgroundColor: "#000" }}>
|
||||
{/* Sticky headers are deliberately not wired up: LegendList's JS sticky
|
||||
implementation mispositions pinned headers at mount under iOS
|
||||
automatic content insets (headers render one nav-inset too low until
|
||||
@@ -1158,8 +1108,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ListHeaderComponent={listHeader}
|
||||
ListEmptyComponent={listEmpty}
|
||||
style={{ flex: 1 }}
|
||||
automaticallyAdjustsScrollIndicatorInsets={NATIVE_LIQUID_GLASS_SUPPORTED}
|
||||
contentInsetAdjustmentBehavior={NATIVE_LIQUID_GLASS_SUPPORTED ? "automatic" : "never"}
|
||||
automaticallyAdjustsScrollIndicatorInsets={false}
|
||||
contentInsetAdjustmentBehavior="never"
|
||||
showsVerticalScrollIndicator={false}
|
||||
keyboardDismissMode="on-drag"
|
||||
keyboardShouldPersistTaps="handled"
|
||||
@@ -1167,26 +1117,19 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
recycleItems
|
||||
scrollEventThrottle={16}
|
||||
contentContainerStyle={{
|
||||
// Android reserves room for the floating new-task FAB
|
||||
// (56 button + 16 gap + bottom inset). Pre-glass iOS shows a
|
||||
// standard 44pt bottom toolbar that overlays the list and is not
|
||||
// reflected in insets while contentInsetAdjustmentBehavior is
|
||||
// "never".
|
||||
paddingBottom:
|
||||
Platform.OS === "ios"
|
||||
? Math.max(insets.bottom, 24) + 24 + iosBottomToolbarClearance
|
||||
: Math.max(insets.bottom, 16) + 88,
|
||||
paddingBottom: Math.max(insets.bottom, 16) + 80,
|
||||
}}
|
||||
scrollIndicatorInsets={
|
||||
Platform.OS === "ios"
|
||||
? {
|
||||
bottom: Math.max(insets.bottom, 16) + 24 + iosBottomToolbarClearance,
|
||||
bottom: Math.max(insets.bottom, 16) + 80,
|
||||
top: 0,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{composeAction}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
+41
-14
@@ -2,9 +2,10 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import {
|
||||
resolveHomeEnvironmentConnectionPhase,
|
||||
shouldShowWorkspaceConnectionStatus,
|
||||
workspaceConnectionHeaderPresentation,
|
||||
workspaceConnectionStatusLabel,
|
||||
workspaceConnectionStatusPresentation,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
|
||||
@@ -26,6 +27,12 @@ function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState
|
||||
}
|
||||
|
||||
describe("workspace connection status", () => {
|
||||
it("treats uncatalogued saved environments as connecting during startup", () => {
|
||||
expect(resolveHomeEnvironmentConnectionPhase(undefined, true)).toBe("connecting");
|
||||
expect(resolveHomeEnvironmentConnectionPhase(undefined, false)).toBe("available");
|
||||
expect(resolveHomeEnvironmentConnectionPhase("connected", true)).toBe("connected");
|
||||
});
|
||||
|
||||
it("stays hidden while a ready environment is connected", () => {
|
||||
expect(shouldShowWorkspaceConnectionStatus(workspaceState())).toBe(false);
|
||||
});
|
||||
@@ -86,18 +93,19 @@ describe("workspace connection status", () => {
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
|
||||
});
|
||||
|
||||
it("presents nothing while connected", () => {
|
||||
expect(workspaceConnectionStatusPresentation(workspaceState())).toBeNull();
|
||||
it("keeps healthy shell synchronization out of the Home wordmark", () => {
|
||||
const state = workspaceState({ hasPendingShellSnapshot: true });
|
||||
|
||||
expect(workspaceConnectionHeaderPresentation(state, "Leftbook")).toBeNull();
|
||||
});
|
||||
|
||||
it("presents progress while reconnecting but not while offline", () => {
|
||||
const reconnecting = workspaceState({
|
||||
it("presents reconnecting environments in amber", () => {
|
||||
const state = workspaceState({
|
||||
hasConnectingEnvironment: true,
|
||||
hasReadyEnvironment: false,
|
||||
connectingEnvironments: [
|
||||
{
|
||||
environmentId: "environment-1" as never,
|
||||
environmentLabel: "Julius’s Mac mini",
|
||||
environmentLabel: "Leftbook",
|
||||
displayUrl: "",
|
||||
isRelayManaged: false,
|
||||
connectionState: "reconnecting",
|
||||
@@ -106,15 +114,34 @@ describe("workspace connection status", () => {
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(workspaceConnectionStatusPresentation(reconnecting)).toEqual({
|
||||
label: "Reconnecting to Julius’s Mac mini",
|
||||
showsProgress: true,
|
||||
|
||||
expect(workspaceConnectionHeaderPresentation(state, "Other device")).toEqual({
|
||||
detail: "reconnecting",
|
||||
label: "Leftbook",
|
||||
tone: "amber",
|
||||
});
|
||||
});
|
||||
|
||||
it("presents unreachable environments in red", () => {
|
||||
const state = workspaceState({
|
||||
connectionError: "Connection refused",
|
||||
hasReadyEnvironment: false,
|
||||
});
|
||||
|
||||
const offline = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
|
||||
expect(workspaceConnectionStatusPresentation(offline)).toEqual({
|
||||
label: "You are offline",
|
||||
showsProgress: false,
|
||||
expect(workspaceConnectionHeaderPresentation(state, "Steambox")).toEqual({
|
||||
detail: "unreachable",
|
||||
label: "Steambox",
|
||||
tone: "red",
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces one unavailable device while other environments stay connected", () => {
|
||||
const state = workspaceState();
|
||||
|
||||
expect(workspaceConnectionHeaderPresentation(state, "Steambox", "available")).toEqual({
|
||||
detail: "unreachable",
|
||||
label: "Steambox",
|
||||
tone: "red",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { ReactNode } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import {
|
||||
workspaceConnectionHeaderPresentation,
|
||||
workspaceConnectionStatusLabel,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
export function WorkspaceConnectionStatus(props: {
|
||||
readonly state: WorkspaceState;
|
||||
readonly onPress: () => void;
|
||||
readonly onReconnect?: () => void;
|
||||
readonly environmentLabel?: string;
|
||||
readonly environmentConnectionState?: EnvironmentConnectionPhase;
|
||||
readonly fallback?: ReactNode;
|
||||
readonly variant?: "floating" | "header" | "sidebar";
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
if (props.variant === "header") {
|
||||
const presentation = workspaceConnectionHeaderPresentation(
|
||||
props.state,
|
||||
props.environmentLabel,
|
||||
props.environmentConnectionState,
|
||||
);
|
||||
if (presentation === null) return <>{props.fallback}</>;
|
||||
|
||||
const tintColor = presentation.tone === "amber" ? "#fbbf24" : "#f87171";
|
||||
const label = `${presentation.label} ${presentation.detail}`;
|
||||
return (
|
||||
<View className="h-12 min-w-0 flex-row items-center gap-2.5">
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={label}
|
||||
accessibilityRole="button"
|
||||
className="min-w-0 flex-1 flex-row items-center gap-2.5 self-stretch"
|
||||
onPress={props.onPress}
|
||||
>
|
||||
<SymbolView
|
||||
name={
|
||||
presentation.tone === "amber" ? "point.3.connected.trianglepath.dotted" : "wifi.slash"
|
||||
}
|
||||
size={17}
|
||||
tintColor={tintColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 shrink text-base font-t3-bold"
|
||||
numberOfLines={1}
|
||||
style={{ color: tintColor }}
|
||||
>
|
||||
{presentation.label}{" "}
|
||||
<Text className="text-sm font-t3-medium" style={{ color: tintColor, opacity: 0.72 }}>
|
||||
{presentation.detail}
|
||||
</Text>
|
||||
</Text>
|
||||
</Pressable>
|
||||
{presentation.tone === "red" && props.onReconnect ? (
|
||||
<Pressable
|
||||
accessibilityLabel={`Reconnect ${presentation.label}`}
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={props.onReconnect}
|
||||
>
|
||||
<Text className="text-xs font-t3-bold" style={{ color: tintColor }}>
|
||||
Reconnect
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isSynchronizing =
|
||||
props.state.networkStatus !== "offline" &&
|
||||
props.state.connectionError === null &&
|
||||
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
|
||||
const variant = props.variant ?? "floating";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
className={
|
||||
variant === "sidebar"
|
||||
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
|
||||
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
|
||||
}
|
||||
style={
|
||||
variant === "floating"
|
||||
? {
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 10 },
|
||||
shadowOpacity: 0.12,
|
||||
shadowRadius: 24,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isSynchronizing ? (
|
||||
<SymbolView
|
||||
name="point.3.connected.trianglepath.dotted"
|
||||
size={15}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : (
|
||||
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
|
||||
)}
|
||||
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{workspaceConnectionStatusLabel(props.state)}
|
||||
</Text>
|
||||
{variant === "sidebar" ? (
|
||||
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -1,194 +0,0 @@
|
||||
import type {
|
||||
NativeStackHeaderItem,
|
||||
NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Animated, Platform, Pressable, View } from "react-native";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { brandTitleOffset, CompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
workspaceConnectionStatusPresentation,
|
||||
type WorkspaceConnectionStatusPresentation,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
/**
|
||||
* Delay before a connection interruption surfaces in the title slot. Sub-second
|
||||
* blips (the common reconnect case) resolve without any UI at all.
|
||||
*/
|
||||
const STATUS_SHOW_DELAY_MS = 800;
|
||||
const FADE_IN_MS = 250;
|
||||
|
||||
/**
|
||||
* Connection status presentation, debounced for display: null until the
|
||||
* workspace has been in a non-connected state for STATUS_SHOW_DELAY_MS,
|
||||
* then live-updating until the workspace reconnects (null again immediately).
|
||||
*/
|
||||
function useDelayedConnectionStatus(): WorkspaceConnectionStatusPresentation | null {
|
||||
const { state } = useWorkspaceState();
|
||||
const presentation = workspaceConnectionStatusPresentation(state);
|
||||
const hasStatus = presentation !== null;
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasStatus) {
|
||||
setVisible(false);
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => setVisible(true), STATUS_SHOW_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [hasStatus]);
|
||||
|
||||
return visible ? presentation : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-shot entrance fade for the status label. Deliberately JS-driven: this can
|
||||
* mount inside a native header item (RNSScreenStackHeaderSubview), where
|
||||
* native-driver animated nodes blank the re-hosted view entirely. The JS driver
|
||||
* updates opacity through the ordinary style path, which those subviews handle.
|
||||
*/
|
||||
function StatusFadeIn(props: { readonly children: ReactNode; readonly grow?: boolean }) {
|
||||
const opacity = useRef(new Animated.Value(0)).current;
|
||||
|
||||
useEffect(() => {
|
||||
const animation = Animated.timing(opacity, {
|
||||
duration: FADE_IN_MS,
|
||||
toValue: 1,
|
||||
useNativeDriver: false,
|
||||
});
|
||||
animation.start();
|
||||
return () => animation.stop();
|
||||
}, [opacity]);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
{ alignItems: "center", flexDirection: "row", opacity },
|
||||
props.grow ? { flex: 1, minWidth: 0 } : null,
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the brand/title slot of a thread-list surface, swapping the brand
|
||||
* for the workspace connection status while an environment is unavailable.
|
||||
*
|
||||
* Both states occupy the same slot, so connection changes never shift the
|
||||
* layout below. While connected the brand renders untouched — no wrapper —
|
||||
* keeping the native header item on the exact element tree that predates the
|
||||
* status swap. Replaces the old WorkspaceConnectionStatus pill, which inserted
|
||||
* a row above the thread list.
|
||||
*/
|
||||
export function WorkspaceConnectionTitle(props: {
|
||||
/** Content shown while connected (brand lockup or a screen title). */
|
||||
readonly brand: ReactNode;
|
||||
/** Opens environment settings. Status is not pressable when omitted. */
|
||||
readonly onPress?: () => void;
|
||||
/** Fill the available row width (in-flow headers) instead of hugging content (native title slots). */
|
||||
readonly grow?: boolean;
|
||||
readonly size?: "navbar" | "pageTitle";
|
||||
/** Horizontal correction so the status aligns with the brand in native title slots. */
|
||||
readonly statusOffset?: number;
|
||||
}) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const status = useDelayedConnectionStatus();
|
||||
const size = props.size ?? "navbar";
|
||||
|
||||
if (status === null) {
|
||||
return props.grow ? (
|
||||
<View style={{ alignItems: "center", flex: 1, flexDirection: "row", minWidth: 0 }}>
|
||||
{props.brand}
|
||||
</View>
|
||||
) : (
|
||||
<>{props.brand}</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusFadeIn grow={props.grow}>
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={status.label}
|
||||
accessibilityRole="button"
|
||||
disabled={props.onPress === undefined}
|
||||
hitSlop={8}
|
||||
onPress={props.onPress}
|
||||
className="flex-row items-center gap-2"
|
||||
style={{ marginLeft: props.statusOffset ?? 0 }}
|
||||
>
|
||||
{status.showsProgress ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="wifi.slash"
|
||||
size={size === "pageTitle" ? 17 : 15}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
<Text
|
||||
className={
|
||||
size === "pageTitle"
|
||||
? "text-[20px] font-t3-bold text-foreground-muted"
|
||||
: "text-[16px] font-t3-bold text-foreground-muted"
|
||||
}
|
||||
numberOfLines={1}
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</StatusFadeIn>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* getCompactBrandHeaderOptions with the brand slot upgraded to the
|
||||
* connection-status swap. Screens with an environment-settings callback apply
|
||||
* this over the static brand options at mount.
|
||||
*/
|
||||
export function getConnectionAwareBrandHeaderOptions(opts: {
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"];
|
||||
}): NativeStackNavigationOptions {
|
||||
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
|
||||
return {
|
||||
headerTitle: "Threads",
|
||||
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
|
||||
title: "Threads",
|
||||
unstable_headerLeftItems: (): NativeStackHeaderItem[] => [
|
||||
{
|
||||
element: (
|
||||
<WorkspaceConnectionTitle
|
||||
brand={<CompactBrandTitle nativeLeadingItem />}
|
||||
onPress={opts.onOpenEnvironments}
|
||||
statusOffset={brandTitleOffset(true)}
|
||||
/>
|
||||
),
|
||||
hidesSharedBackground: true,
|
||||
type: "custom",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
headerTitle: () => (
|
||||
<WorkspaceConnectionTitle
|
||||
brand={<CompactBrandTitle />}
|
||||
onPress={opts.onOpenEnvironments}
|
||||
statusOffset={brandTitleOffset(false)}
|
||||
/>
|
||||
),
|
||||
headerTitleStyle: opts.fallbackTitleStyle,
|
||||
title: "Threads",
|
||||
};
|
||||
}
|
||||
@@ -31,6 +31,12 @@ export interface ResolvedHomeListOptions extends HomeListOptions {
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}
|
||||
|
||||
export function resolveProjectGroupingMode(
|
||||
projectGroupingEnabled: boolean | undefined,
|
||||
): SidebarProjectGroupingMode {
|
||||
return projectGroupingEnabled === false ? "separate" : "repository";
|
||||
}
|
||||
|
||||
export const PROJECT_SORT_OPTIONS: ReadonlyArray<{
|
||||
readonly value: HomeProjectSortOrder;
|
||||
readonly label: string;
|
||||
@@ -70,9 +76,7 @@ const HomeListOptionsContext = createContext<HomeListOptionsContextValue | null>
|
||||
export function HomeListOptionsProvider({
|
||||
children,
|
||||
projectGroupingMode,
|
||||
}: PropsWithChildren<{
|
||||
readonly projectGroupingMode: SidebarProjectGroupingMode;
|
||||
}>) {
|
||||
}: PropsWithChildren<{ readonly projectGroupingMode: SidebarProjectGroupingMode }>) {
|
||||
const [options, setOptions] = useState<HomeListOptions>(defaultHomeListOptions);
|
||||
const value = useMemo(
|
||||
() => ({ options, setOptions, projectGroupingMode }),
|
||||
|
||||
@@ -375,7 +375,7 @@ describe("buildHomeThreadGroups", () => {
|
||||
).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("uses the physical project title for a singleton scope", () => {
|
||||
it("uses the repository label for a singleton repository scope", () => {
|
||||
const project = makeProject({
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
id: ProjectId.make("project-1"),
|
||||
@@ -408,8 +408,8 @@ describe("buildHomeThreadGroups", () => {
|
||||
],
|
||||
);
|
||||
|
||||
expect(scopes[0]?.title).toBe("local-worktree-name");
|
||||
expect(groups[0]?.title).toBe("local-worktree-name");
|
||||
expect(scopes[0]?.title).toBe("codething-mvp");
|
||||
expect(groups[0]?.title).toBe("codething-mvp");
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
@@ -565,16 +565,10 @@ describe("buildHomeThreadGroups", () => {
|
||||
);
|
||||
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
|
||||
expect(
|
||||
buildGroups(projects, threads, { projectGroupingMode: "repository_path" }).map(
|
||||
(group) => group.title,
|
||||
),
|
||||
).toEqual(["Mobile", "Web"]);
|
||||
expect(
|
||||
buildGroups(projects, threads, { projectGroupingMode: "separate" }).map(
|
||||
(group) => group.title,
|
||||
),
|
||||
).toEqual(["Mobile", "Web"]);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
|
||||
2,
|
||||
);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("default view shows only threads from the last 5 days", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
buildProjectGroups,
|
||||
deriveLogicalProjectKey,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
@@ -37,6 +37,10 @@ export interface HomeProjectScope {
|
||||
readonly projectRefs: ReadonlyArray<ScopedProjectRef>;
|
||||
}
|
||||
|
||||
function getProjectFreshnessTimestamp(project: EnvironmentProject): number {
|
||||
return toSortableTimestamp(project.updatedAt) ?? toSortableTimestamp(project.createdAt) ?? 0;
|
||||
}
|
||||
|
||||
function getProjectSortTimestamp(
|
||||
project: EnvironmentProject,
|
||||
sortOrder: HomeProjectSortOrder,
|
||||
@@ -56,19 +60,64 @@ export function buildHomeProjectScopes(input: {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
return buildProjectGroups({
|
||||
projects,
|
||||
settings: {
|
||||
sidebarProjectGroupingMode: input.projectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: {},
|
||||
},
|
||||
}).map((group) => {
|
||||
const projectsByPhysicalKey = new Map<string, EnvironmentProject[]>();
|
||||
for (const project of projects) {
|
||||
const physicalKey = derivePhysicalProjectKey(project);
|
||||
const existing = projectsByPhysicalKey.get(physicalKey);
|
||||
if (existing) existing.push(project);
|
||||
else projectsByPhysicalKey.set(physicalKey, [project]);
|
||||
}
|
||||
|
||||
const winnersByPhysicalKey = new Map<
|
||||
string,
|
||||
{ readonly key: string; readonly project: EnvironmentProject }
|
||||
>();
|
||||
for (const [physicalKey, members] of projectsByPhysicalKey) {
|
||||
const project = members.reduce((winner, candidate) => {
|
||||
const freshnessDelta =
|
||||
getProjectFreshnessTimestamp(candidate) - getProjectFreshnessTimestamp(winner);
|
||||
return freshnessDelta > 0 || (freshnessDelta === 0 && candidate.id > winner.id)
|
||||
? candidate
|
||||
: winner;
|
||||
});
|
||||
const identitySource = members.find((member) => member.repositoryIdentity !== null) ?? project;
|
||||
winnersByPhysicalKey.set(physicalKey, {
|
||||
key: deriveLogicalProjectKey(identitySource, { groupingMode: input.projectGroupingMode }),
|
||||
project,
|
||||
});
|
||||
}
|
||||
|
||||
const groups = new Map<string, EnvironmentProject[]>();
|
||||
for (const { key, project } of winnersByPhysicalKey.values()) {
|
||||
const existing = groups.get(key);
|
||||
if (existing) existing.push(project);
|
||||
else groups.set(key, [project]);
|
||||
}
|
||||
|
||||
const projectRefsByGroup = new Map<string, ScopedProjectRef[]>();
|
||||
const seenProjectRefs = new Set<string>();
|
||||
for (const project of projects) {
|
||||
const refKey = scopedProjectKey(project.environmentId, project.id);
|
||||
if (seenProjectRefs.has(refKey)) continue;
|
||||
seenProjectRefs.add(refKey);
|
||||
|
||||
const key =
|
||||
winnersByPhysicalKey.get(derivePhysicalProjectKey(project))?.key ??
|
||||
deriveLogicalProjectKey(project, { groupingMode: input.projectGroupingMode });
|
||||
const refs = projectRefsByGroup.get(key);
|
||||
const projectRef = { environmentId: project.environmentId, projectId: project.id };
|
||||
if (refs) refs.push(projectRef);
|
||||
else projectRefsByGroup.set(key, [projectRef]);
|
||||
}
|
||||
|
||||
return Array.from(groups, ([key, projects]) => {
|
||||
const representative = projects[0]!;
|
||||
return {
|
||||
key: group.key,
|
||||
title: group.label,
|
||||
representative: group.representative,
|
||||
projects: group.members.map((member) => member.project),
|
||||
projectRefs: group.memberProjectRefs,
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -215,11 +264,9 @@ export function buildHomeThreadGroups(input: {
|
||||
}): ReadonlyArray<HomeThreadGroup> {
|
||||
const now = input.now ?? Date.now();
|
||||
const groups = new Map<string, MutableHomeThreadGroup>();
|
||||
const groupTitleByKey = new Map<string, string>();
|
||||
const groupKeyByProjectKey = new Map<string, string>();
|
||||
|
||||
for (const scope of buildHomeProjectScopes(input)) {
|
||||
groupTitleByKey.set(scope.key, scope.title);
|
||||
groups.set(scope.key, {
|
||||
key: scope.key,
|
||||
projects: [...scope.projects],
|
||||
@@ -298,9 +345,7 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title =
|
||||
groupTitleByKey.get(group.key) ??
|
||||
deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
|
||||
@@ -8,14 +8,9 @@ import { Alert } from "react-native";
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import {
|
||||
pinOrderKeyBetween,
|
||||
planPinnedMove,
|
||||
sortPinnedThreadsByOrderKey,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
@@ -41,13 +36,6 @@ function environmentSupportsPinning(environmentId: EnvironmentThreadShell["envir
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinReorder === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -223,10 +211,6 @@ export function useThreadListActions(): {
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly movePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
@@ -347,21 +331,9 @@ export function useThreadListActions(): {
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
// Same placement as web: a fresh pin takes the top of the arranged
|
||||
// run. Servers that predate reordering get the bare pin (keyless).
|
||||
let orderKey: string | undefined;
|
||||
if (environmentSupportsPinReorder(thread.environmentId)) {
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
let firstKey: string | null = null;
|
||||
for (const shell of shells) {
|
||||
if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
|
||||
if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
|
||||
}
|
||||
orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
|
||||
}
|
||||
const result = await pinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
@@ -406,85 +378,6 @@ export function useThreadListActions(): {
|
||||
[unpinMutation],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
// while search or a project scope filters rows: the same fractional-key
|
||||
// scheme web dragging uses, one write to one thread per move (plus a
|
||||
// one-time section materialization when legacy keyless pins are involved).
|
||||
const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// One move at a time: a second tap before the first write's event lands
|
||||
// would plan from the same stale snapshot and silently collapse two moves
|
||||
// into one — same double-dispatch guard as snoozeThread.
|
||||
const movePinnedInFlightRef = useRef(false);
|
||||
const movePinnedThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
if (movePinnedInFlightRef.current) return false;
|
||||
if (!environmentSupportsPinReorder(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
"This environment's server does not support pinned reordering yet. Update the server to reorder pins.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
shells.filter(
|
||||
(shell) =>
|
||||
shell.pinnedAt != null &&
|
||||
shell.archivedAt === null &&
|
||||
environmentSupportsPinReorder(shell.environmentId),
|
||||
),
|
||||
);
|
||||
const orderedIds = pinned.map((shell) => scopedThreadKey(shell.environmentId, shell.id));
|
||||
const assignments = planPinnedMove({
|
||||
orderedIds,
|
||||
keysById: new Map(
|
||||
pinned.map((shell) => [
|
||||
scopedThreadKey(shell.environmentId, shell.id),
|
||||
shell.pinOrderKey ?? null,
|
||||
]),
|
||||
),
|
||||
movedId: scopedThreadKey(thread.environmentId, thread.id),
|
||||
direction,
|
||||
});
|
||||
if (assignments === null || assignments.length === 0) return false;
|
||||
const shellByKey = new Map(
|
||||
pinned.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
|
||||
);
|
||||
selectionHaptic();
|
||||
movePinnedInFlightRef.current = true;
|
||||
try {
|
||||
for (const assignment of assignments) {
|
||||
const target = shellByKey.get(assignment.id);
|
||||
if (target === undefined) continue;
|
||||
const result = await reorderPinnedMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.id, orderKey: assignment.orderKey },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The pinned thread could not be moved.",
|
||||
);
|
||||
// No rollback: keys already written are valid orderings on their
|
||||
// own (each write is a complete, consistent placement), so a
|
||||
// partial materialization leaves the list sensible, not corrupt.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
movePinnedInFlightRef.current = false;
|
||||
}
|
||||
},
|
||||
[reorderPinnedMutation],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return {
|
||||
@@ -496,7 +389,6 @@ export function useThreadListActions(): {
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
|
||||
export interface WorkspaceConnectionStatusPresentation {
|
||||
readonly label: string;
|
||||
/** True while actively working (connecting/syncing) — render a spinner. False for offline/error/idle states — render a wifi-slash icon. */
|
||||
readonly showsProgress: boolean;
|
||||
export function resolveHomeEnvironmentConnectionPhase(
|
||||
connectionState: EnvironmentConnectionPhase | undefined,
|
||||
isLoadingConnections: boolean,
|
||||
): EnvironmentConnectionPhase {
|
||||
return connectionState ?? (isLoadingConnections ? "connecting" : "available");
|
||||
}
|
||||
|
||||
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
|
||||
@@ -31,16 +34,70 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
|
||||
return "Not connected";
|
||||
}
|
||||
|
||||
/** Header-title presentation of the connection state, or null while connected. */
|
||||
export function workspaceConnectionStatusPresentation(
|
||||
state: WorkspaceState,
|
||||
): WorkspaceConnectionStatusPresentation | null {
|
||||
if (!shouldShowWorkspaceConnectionStatus(state)) return null;
|
||||
return {
|
||||
label: workspaceConnectionStatusLabel(state),
|
||||
showsProgress:
|
||||
state.networkStatus !== "offline" &&
|
||||
state.connectionError === null &&
|
||||
(state.connectingEnvironments.length > 0 || state.hasPendingShellSnapshot),
|
||||
};
|
||||
export interface WorkspaceConnectionHeaderPresentation {
|
||||
readonly detail: "reconnecting" | "unreachable";
|
||||
readonly label: string;
|
||||
readonly tone: "amber" | "red";
|
||||
}
|
||||
|
||||
/**
|
||||
* Only actual connection trouble displaces the Home wordmark. Shell catch-up
|
||||
* is healthy background work and deliberately leaves the header unchanged.
|
||||
*/
|
||||
export function workspaceConnectionHeaderPresentation(
|
||||
state: WorkspaceState,
|
||||
environmentLabel?: string,
|
||||
environmentConnectionState?: EnvironmentConnectionPhase,
|
||||
): WorkspaceConnectionHeaderPresentation | null {
|
||||
if (state.networkStatus === "offline") {
|
||||
return {
|
||||
detail: "unreachable",
|
||||
label: environmentLabel ?? "Network",
|
||||
tone: "red",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
environmentConnectionState === "connecting" ||
|
||||
environmentConnectionState === "reconnecting"
|
||||
) {
|
||||
return {
|
||||
detail: "reconnecting",
|
||||
label: environmentLabel ?? "Environment",
|
||||
tone: "amber",
|
||||
};
|
||||
}
|
||||
|
||||
if (environmentConnectionState && environmentConnectionState !== "connected") {
|
||||
return {
|
||||
detail: "unreachable",
|
||||
label: environmentLabel ?? "Environment",
|
||||
tone: "red",
|
||||
};
|
||||
}
|
||||
|
||||
if (state.connectingEnvironments.length > 0) {
|
||||
const connecting = state.connectingEnvironments[0];
|
||||
return {
|
||||
detail: "reconnecting",
|
||||
label:
|
||||
state.connectingEnvironments.length === 1
|
||||
? (connecting?.environmentLabel ?? environmentLabel ?? "Environment")
|
||||
: `${state.connectingEnvironments.length} environments`,
|
||||
tone: "amber",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
state.connectionError !== null ||
|
||||
(state.hasConnections && state.hasLoadedShellSnapshot && !state.hasReadyEnvironment)
|
||||
) {
|
||||
return {
|
||||
detail: "unreachable",
|
||||
label: environmentLabel ?? "Environment",
|
||||
tone: "red",
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -37,15 +37,11 @@ import {
|
||||
import { resolveThreadSelectionNavigationAction } from "../../lib/adaptive-navigation";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import {
|
||||
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "../../state/project-grouping";
|
||||
import {
|
||||
parseActiveThreadPath,
|
||||
useHardwareKeyboardCommand,
|
||||
} from "../keyboard/hardwareKeyboardCommands";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -194,17 +190,15 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
|
||||
/>
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
) : null;
|
||||
}
|
||||
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,25 +1,15 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
|
||||
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
|
||||
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
|
||||
|
||||
export function SettingsAppearanceRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { useEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -21,18 +21,16 @@ export function SettingsAuthRouteScreen() {
|
||||
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<NativeStackScreenOptions options={{ title: isSignedIn ? "Account" : "Sign in" }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
<UserProfileView isDismissible={false} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
<AuthView isDismissible={false} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -8,6 +8,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
|
||||
import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
@@ -160,19 +161,18 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Always mounted: already-connected relay environments must stay
|
||||
visible (and removable) even when cloud config is missing or the
|
||||
user is signed out — the component gates discovery itself. */}
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import {
|
||||
mobileProjectGroupingModePatch,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "../../state/project-grouping";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
|
||||
const GROUPING_OPTIONS: ReadonlyArray<{
|
||||
readonly mode: SidebarProjectGroupingMode;
|
||||
readonly label: string;
|
||||
readonly description: string;
|
||||
}> = [
|
||||
{
|
||||
mode: "repository",
|
||||
label: "Group by repository",
|
||||
description: "Matching repositories appear as one project.",
|
||||
},
|
||||
{
|
||||
mode: "repository_path",
|
||||
label: "Group by repository path",
|
||||
description: "Keep monorepo paths separate.",
|
||||
},
|
||||
{
|
||||
mode: "separate",
|
||||
label: "Keep separate",
|
||||
description: "Show every workspace as its own project.",
|
||||
},
|
||||
];
|
||||
|
||||
export function SettingsProjectGroupingRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
const checkmarkColor = useThemeColor("--color-icon");
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const preferencesReady = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
|
||||
const selectedMode = AsyncResult.isSuccess(preferencesResult)
|
||||
? resolveMobileProjectGroupingSettings(preferencesResult.value).sidebarProjectGroupingMode
|
||||
: null;
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Project Grouping" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentContainerClassName="gap-3 px-5 pt-4"
|
||||
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
>
|
||||
<SettingsSection title="Default grouping">
|
||||
{GROUPING_OPTIONS.map((option, index) => (
|
||||
<Pressable
|
||||
key={option.mode}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{
|
||||
checked: selectedMode === option.mode,
|
||||
disabled: !preferencesReady,
|
||||
}}
|
||||
disabled={!preferencesReady}
|
||||
onPress={() => savePreferences(mobileProjectGroupingModePatch(option.mode))}
|
||||
className={
|
||||
index === 0
|
||||
? "flex-row items-center gap-4 p-4"
|
||||
: "flex-row items-center gap-4 border-t border-border-subtle p-4"
|
||||
}
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-1">
|
||||
<Text className="text-lg text-foreground">{option.label}</Text>
|
||||
<Text className="text-sm leading-normal text-foreground-muted">
|
||||
{option.description}
|
||||
</Text>
|
||||
</View>
|
||||
{selectedMode === option.mode ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={18}
|
||||
tintColor={checkmarkColor}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
) : null}
|
||||
</Pressable>
|
||||
))}
|
||||
</SettingsSection>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -530,9 +530,20 @@ function ConfiguredSettingsRouteScreen() {
|
||||
}
|
||||
|
||||
function GeneralSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const projectGroupingEnabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.projectGroupingEnabled !== false
|
||||
: true;
|
||||
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,4 @@
|
||||
import {
|
||||
Platform,
|
||||
ScrollView,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
View,
|
||||
useColorScheme,
|
||||
} from "react-native";
|
||||
import { Platform, ScrollView, View, useColorScheme } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../../../components/AppText";
|
||||
import {
|
||||
@@ -61,48 +54,14 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
|
||||
fontSize: props.fontSize,
|
||||
lineHeight,
|
||||
} as const;
|
||||
// AppText stamps the sans font on every node, so nested spans must
|
||||
// re-apply the terminal font instead of relying on inheritance, exactly
|
||||
// like the code preview's tokens below.
|
||||
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
|
||||
lineStyle,
|
||||
{ color, ...extra },
|
||||
];
|
||||
|
||||
return (
|
||||
<View className="p-4">
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>→ </Text>
|
||||
<Text style={span(theme.palette[6])}>t3code </Text>
|
||||
<Text style={span(theme.palette[4])}>git:(</Text>
|
||||
<Text style={span(theme.palette[1])}>main</Text>
|
||||
<Text style={span(theme.palette[4])}>)</Text>
|
||||
<Text style={span(theme.palette[3])}> ✗</Text>
|
||||
<Text style={span(theme.foreground)}> vpr dev</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
|
||||
<Text style={span(theme.mutedForeground)}> ready in</Text>
|
||||
<Text style={span(theme.foreground)}> 1.24s</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>→ </Text>
|
||||
<Text style={span(theme.mutedForeground)}>Local: </Text>
|
||||
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
|
||||
http://127.0.0.1:5173/
|
||||
</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
|
||||
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
|
||||
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
|
||||
</Text>
|
||||
<Text style={span(theme.foreground)}>
|
||||
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
|
||||
{" READY "}
|
||||
</Text>
|
||||
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
|
||||
<Text style={span(theme.cursorForeground)}>▏</Text>
|
||||
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
|
||||
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
|
||||
<Text style={[lineStyle, { color: theme.foreground }]}>
|
||||
Local: http://localhost:3000{" "}
|
||||
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -2,7 +2,6 @@ export type SettingsSheetTarget =
|
||||
| "SettingsEnvironments"
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -1,11 +1,10 @@
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
|
||||
import { Alert, Keyboard, Pressable, View, useColorScheme } from "react-native";
|
||||
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -20,9 +19,11 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStrip";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ModelPickerSheet } from "../../components/ModelPickerSheet";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { ComposerSurface } from "./ThreadComposer";
|
||||
|
||||
@@ -31,7 +32,6 @@ import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/
|
||||
import {
|
||||
applyProviderOptionMenuEvent,
|
||||
buildProviderOptionMenuActions,
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
@@ -43,27 +43,15 @@ import {
|
||||
type ComposerDraft,
|
||||
} from "../../state/use-composer-drafts";
|
||||
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
|
||||
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
|
||||
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
|
||||
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
|
||||
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
|
||||
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
|
||||
import { branchBadgeLabel, useNewTaskFlow } from "./new-task-flow-provider";
|
||||
import { useCreateProjectThread } from "./use-project-actions";
|
||||
import { resolveDraftProjectSelection } from "./new-task-project-selection";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
|
||||
function formatWorkspaceLabel(input: {
|
||||
readonly workspaceMode: string;
|
||||
readonly currentBranchName: string | null;
|
||||
readonly selectedBranchName: string | null;
|
||||
}): string {
|
||||
const branchName = input.selectedBranchName ?? input.currentBranchName;
|
||||
if (input.workspaceMode === "worktree") {
|
||||
return branchName ? `New worktree · ${branchName}` : "New worktree";
|
||||
}
|
||||
return branchName ? `Current · ${branchName}` : "Current checkout";
|
||||
}
|
||||
import { useModelFavorites } from "./useModelFavorites";
|
||||
|
||||
export function NewTaskDraftScreen(props: {
|
||||
readonly initialProjectRef?: {
|
||||
@@ -90,11 +78,14 @@ export function NewTaskDraftScreen(props: {
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
);
|
||||
const { favoriteModelKeys, favoritesReady, toggleFavorite } = useModelFavorites(
|
||||
selectedProject?.environmentId ?? null,
|
||||
);
|
||||
const environmentConnected =
|
||||
selectedProject !== null &&
|
||||
connectedEnvironments.find(
|
||||
@@ -102,12 +93,12 @@ export function NewTaskDraftScreen(props: {
|
||||
)?.connectionState === "connected";
|
||||
const promptInputRef = useRef<ComposerEditorHandle>(null);
|
||||
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
|
||||
const [isComposerFocused, setIsComposerFocused] = useState(false);
|
||||
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
|
||||
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
|
||||
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
|
||||
const [isReturningToProjectPicker, setIsReturningToProjectPicker] = useState(false);
|
||||
const [shareImportAttempt, setShareImportAttempt] = useState(0);
|
||||
const [modelPickerVisible, setModelPickerVisible] = useState(false);
|
||||
const startedShareImportKeyRef = useRef<string | null>(null);
|
||||
const cancellingShareImportKeyRef = useRef<string | null>(null);
|
||||
const shareImportDraftBackupRef = useRef(new Map<string, ComposerDraft>());
|
||||
@@ -222,11 +213,8 @@ export function NewTaskDraftScreen(props: {
|
||||
}, [props.pendingTaskId, cancelEditingPendingTask]);
|
||||
|
||||
const foregroundColor = useThemeColor("--color-foreground");
|
||||
const regularFontFamily = useFontFamily("regular");
|
||||
const bodyText = useScaledTextRole("body");
|
||||
const headlineText = useScaledTextRole("headline");
|
||||
const sheetFadeOpaque = colorScheme === "dark" ? "rgba(14,14,14,0.98)" : "rgba(242,242,247,0.98)";
|
||||
const sheetFadeTransparent = colorScheme === "dark" ? "rgba(14,14,14,0)" : "rgba(242,242,247,0)";
|
||||
|
||||
// A new navigation to this mounted screen delivers a fresh initialProjectRef
|
||||
// reference — treat it as a new request and let it apply again.
|
||||
@@ -278,25 +266,24 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
|
||||
if (selection.kind === "preserve") {
|
||||
if (selectedProject) {
|
||||
return;
|
||||
}
|
||||
if (selection.kind === "select") {
|
||||
setProject(selection.project);
|
||||
|
||||
if (logicalProjects.length === 1) {
|
||||
setProject(logicalProjects[0]!.project);
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.dispatch(StackActions.replace("NewTask"));
|
||||
}, [
|
||||
projectScopes,
|
||||
logicalProjects,
|
||||
projects,
|
||||
props.initialProjectRef,
|
||||
props.incomingShareId,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
setProject,
|
||||
]);
|
||||
|
||||
@@ -512,26 +499,6 @@ export function NewTaskDraftScreen(props: {
|
||||
shareImportAttempt,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
// Android starts with the collapsed composer pill (like an open thread)
|
||||
// and only expands/focuses when tapped.
|
||||
if (!selectedProject || Platform.OS === "android") {
|
||||
return;
|
||||
}
|
||||
|
||||
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
|
||||
const interaction = InteractionManager.runAfterInteractions(() => {
|
||||
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
|
||||
});
|
||||
|
||||
return () => {
|
||||
interaction.cancel();
|
||||
if (focusFrame !== null) {
|
||||
cancelAnimationFrame(focusFrame);
|
||||
}
|
||||
};
|
||||
}, [selectedProject]);
|
||||
|
||||
const environmentMenuActions = useMemo(
|
||||
() =>
|
||||
flow.environments.map((environment) => ({
|
||||
@@ -544,10 +511,6 @@ export function NewTaskDraftScreen(props: {
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
|
||||
[flow.providerGroups, flow.selectedModel],
|
||||
);
|
||||
const providerOptionDescriptors = useMemo(
|
||||
() =>
|
||||
resolveProviderOptionDescriptors({
|
||||
@@ -671,30 +634,19 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.environments.find(
|
||||
(environment) => environment.environmentId === flow.selectedEnvironmentId,
|
||||
)?.environmentLabel ?? "Environment";
|
||||
const currentBranchName =
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const configurationLabel = useMemo(
|
||||
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
|
||||
[providerOptionDescriptors],
|
||||
const configurationMenuActions = useMemo(
|
||||
() => [
|
||||
...optionsMenuActions,
|
||||
{
|
||||
id: "options-environment",
|
||||
title: "Environment",
|
||||
subtitle: selectedEnvironmentLabel,
|
||||
subactions: environmentMenuActions,
|
||||
},
|
||||
...workspaceMenuActions,
|
||||
],
|
||||
[environmentMenuActions, optionsMenuActions, selectedEnvironmentLabel, workspaceMenuActions],
|
||||
);
|
||||
const workspaceLabel = useMemo(
|
||||
() =>
|
||||
formatWorkspaceLabel({
|
||||
currentBranchName,
|
||||
selectedBranchName: flow.selectedBranchName,
|
||||
workspaceMode: flow.workspaceMode,
|
||||
}),
|
||||
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
|
||||
);
|
||||
function handleModelMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
flow.setSelectedModelKey(event.slice("model:".length));
|
||||
}
|
||||
|
||||
function handleEnvironmentMenuAction(event: string) {
|
||||
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
|
||||
return;
|
||||
@@ -747,6 +699,12 @@ export function NewTaskDraftScreen(props: {
|
||||
}
|
||||
}
|
||||
|
||||
function handleConfigurationMenuAction(event: string) {
|
||||
handleOptionsMenuAction(event);
|
||||
handleEnvironmentMenuAction(event);
|
||||
handleWorkspaceMenuAction(event);
|
||||
}
|
||||
|
||||
async function handlePickImages(): Promise<void> {
|
||||
if (isIncomingShareTransferPending) {
|
||||
return;
|
||||
@@ -913,24 +871,13 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
if (!selectedProject) {
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : (
|
||||
<NativeStackScreenOptions options={{ title: "Loading task" }} />
|
||||
)}
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isAndroid = Platform.OS === "android";
|
||||
const isDarkMode = colorScheme === "dark";
|
||||
// Android expansion follows native editor focus so relayout cannot race
|
||||
// the touch gesture that opens the keyboard.
|
||||
const isExpanded = !isAndroid || isComposerFocused;
|
||||
const canStart =
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
@@ -942,90 +889,57 @@ export function NewTaskDraftScreen(props: {
|
||||
const promptEditor = (
|
||||
<ComposerEditor
|
||||
ref={promptInputRef}
|
||||
// Native autoFocus fires becomeFirstResponder in didMoveToWindow, which
|
||||
// forces the iOS keyboard bring-up during the formSheet present
|
||||
// animation and stalls it. The runAfterInteractions effect above focuses
|
||||
// the editor once the transition settles instead.
|
||||
autoFocus={false}
|
||||
editable={!isIncomingShareTransferPending}
|
||||
multiline
|
||||
scrollEnabled={isExpanded}
|
||||
scrollEnabled
|
||||
value={flow.prompt}
|
||||
skills={flow.selectedProviderSkills}
|
||||
onChangeText={flow.setPrompt}
|
||||
onFocus={() => setIsComposerFocused(true)}
|
||||
onBlur={() => setIsComposerFocused(false)}
|
||||
onPasteImages={(uris) => void handleNativePasteImages(uris)}
|
||||
placeholder={`Describe a coding task in ${selectedProject.title}`}
|
||||
// Same collapsed centering as ThreadComposer: native vertical gravity
|
||||
// in a pill-height box.
|
||||
singleLineCentered={!isExpanded}
|
||||
contentInsetVertical={isAndroid ? 0 : undefined}
|
||||
style={
|
||||
isAndroid
|
||||
? isExpanded
|
||||
? { minHeight: 80, maxHeight: 160, paddingHorizontal: 4, paddingVertical: 4 }
|
||||
: { height: 36 }
|
||||
: { flex: 1, minHeight: 0 }
|
||||
}
|
||||
textStyle={
|
||||
isAndroid
|
||||
? { ...bodyText, color: foregroundColor, fontFamily: regularFontFamily }
|
||||
: headlineText
|
||||
}
|
||||
placeholder="Ask anything..."
|
||||
contentInsetVertical={0}
|
||||
style={{
|
||||
minHeight: 76,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
}}
|
||||
textStyle={{ ...bodyText, color: foregroundColor }}
|
||||
/>
|
||||
);
|
||||
|
||||
const toolbarPills = (
|
||||
<>
|
||||
<ComposerToolbarButton
|
||||
icon="plus"
|
||||
accessibilityLabel="Add attachment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="paperclip"
|
||||
onPress={() => void handlePickImages()}
|
||||
showChevron={false}
|
||||
variant="ghost"
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Choose model"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={18} />}
|
||||
label={flow.selectedModelOption?.label ?? "Model"}
|
||||
onPress={() => {
|
||||
Keyboard.dismiss();
|
||||
setModelPickerVisible(true);
|
||||
}}
|
||||
variant="ghost"
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={flow.selectedModelOption?.label ?? "Model"}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
actions={configurationMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleConfigurationMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Environment"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="desktopcomputer"
|
||||
label={selectedEnvironmentLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={workspaceMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleWorkspaceMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Workspace"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
icon="point.topleft.down.curvedto.point.bottomright.up"
|
||||
label={workspaceLabel}
|
||||
showChevron={false}
|
||||
variant="ghost"
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
</>
|
||||
@@ -1036,7 +950,7 @@ export function NewTaskDraftScreen(props: {
|
||||
accessibilityLabel={
|
||||
flow.submitting ? "Starting task" : environmentConnected ? "Start task" : "Queue task"
|
||||
}
|
||||
icon={environmentConnected ? "arrow.up" : "tray.and.arrow.up"}
|
||||
icon="arrow.up"
|
||||
onPress={() => void handleStart()}
|
||||
variant="primary"
|
||||
showChevron={false}
|
||||
@@ -1044,115 +958,126 @@ export function NewTaskDraftScreen(props: {
|
||||
/>
|
||||
);
|
||||
|
||||
if (isAndroid) {
|
||||
// The draft is a thread that doesn't exist yet, so it mirrors the thread
|
||||
// page: in-screen header, empty feed canvas above, and the same floating
|
||||
// composer chrome as ThreadComposer (collapsed pill → expanded card).
|
||||
return (
|
||||
<View className="flex-1 bg-screen">
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="flex-1" />
|
||||
|
||||
<View
|
||||
className="px-4 pt-2"
|
||||
return (
|
||||
<View
|
||||
className="flex-1 overflow-hidden"
|
||||
style={{
|
||||
backgroundColor: isDarkMode ? "#000000" : "#f2f2f7",
|
||||
borderColor: isDarkMode ? "rgba(255,255,255,0.14)" : "rgba(0,0,0,0.1)",
|
||||
borderTopLeftRadius: 20,
|
||||
borderTopRightRadius: 20,
|
||||
borderTopWidth: 1,
|
||||
}}
|
||||
>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View style={{ paddingTop: Math.max(insets.top, 8) }}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={isIncomingShareTransferPending || isCancellingShareImport}
|
||||
hitSlop={8}
|
||||
onPress={() => navigation.goBack()}
|
||||
className="self-start px-4 py-3 active:opacity-60"
|
||||
style={{
|
||||
paddingBottom: controlsBottomPadding,
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.85) 40%, rgba(0,0,0,0.95) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.85) 40%, rgba(255,255,255,0.95) 100%)",
|
||||
opacity: isIncomingShareTransferPending || isCancellingShareImport ? 0.45 : 1,
|
||||
}}
|
||||
>
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
overflow: "hidden",
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
overflow: "hidden",
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
paddingLeft: 18,
|
||||
paddingRight: 5,
|
||||
paddingVertical: 5,
|
||||
}
|
||||
}
|
||||
<Text className="text-sm text-foreground-muted">Cancel</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
|
||||
<View className="min-h-0 flex-1 items-center justify-center px-6 pb-12">
|
||||
<Text
|
||||
className="text-center font-t3-medium text-foreground"
|
||||
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
|
||||
>
|
||||
What should we build
|
||||
</Text>
|
||||
<View className="max-w-full flex-row items-center justify-center">
|
||||
<Text
|
||||
className="font-t3-medium text-foreground"
|
||||
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
|
||||
>
|
||||
{isExpanded && flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<View className={isExpanded ? undefined : "min-w-0 flex-1"}>{promptEditor}</View>
|
||||
{!isExpanded ? (
|
||||
<ControlPill
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canStart}
|
||||
onPress={() => void handleStart()}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)"}
|
||||
fadeTransparent={isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)"}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View className="flex-1 bg-sheet">
|
||||
<NativeStackScreenOptions options={{ title: selectedProject.title }} />
|
||||
|
||||
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
|
||||
<View className="min-h-0 flex-1 px-5 pt-2">{promptEditor}</View>
|
||||
|
||||
<View className="border-t border-border" style={{ paddingBottom: controlsBottomPadding }}>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="px-4 pt-3">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={isIncomingShareTransferPending ? () => undefined : flow.removeAttachment}
|
||||
imageSize={88}
|
||||
imageBorderRadius={20}
|
||||
/>
|
||||
in{" "}
|
||||
</Text>
|
||||
<View
|
||||
className="max-w-[240px] border-b border-foreground-muted"
|
||||
style={{ borderStyle: "dotted" }}
|
||||
>
|
||||
<Text
|
||||
className="font-t3-medium text-foreground"
|
||||
ellipsizeMode="tail"
|
||||
numberOfLines={1}
|
||||
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
|
||||
>
|
||||
{selectedProject.title}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<ComposerToolbarRow paddingBottom={controlsBottomPadding} paddingHorizontal={6}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={sheetFadeOpaque}
|
||||
fadeTransparent={sheetFadeTransparent}
|
||||
<Text
|
||||
className="font-t3-medium text-foreground"
|
||||
style={[headlineText, { fontSize: 28, lineHeight: 34, letterSpacing: -0.6 }]}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
?
|
||||
</Text>
|
||||
</View>
|
||||
<View className="mt-2 flex-row items-center gap-1.5">
|
||||
<SymbolView
|
||||
name="desktopcomputer"
|
||||
size={12}
|
||||
tintColor={isDarkMode ? "#66676d" : "#8e8e93"}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text className="text-xs text-foreground-tertiary">on {selectedEnvironmentLabel}</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View
|
||||
style={{ paddingBottom: controlsBottomPadding, paddingHorizontal: 10, paddingTop: 8 }}
|
||||
>
|
||||
<ComposerSurface
|
||||
isDarkMode={isDarkMode}
|
||||
style={{
|
||||
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
|
||||
borderRadius: 22,
|
||||
overflow: "hidden",
|
||||
paddingBottom: 6,
|
||||
paddingHorizontal: 12,
|
||||
paddingTop: 10,
|
||||
}}
|
||||
>
|
||||
{flow.attachments.length > 0 ? (
|
||||
<View className="pb-2.5">
|
||||
<ComposerAttachmentStrip
|
||||
attachments={flow.attachments}
|
||||
onRemove={
|
||||
isIncomingShareTransferPending ? () => undefined : flow.removeAttachment
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
{promptEditor}
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)"}
|
||||
fadeTransparent={isDarkMode ? "rgba(17,17,19,0)" : "rgba(255,255,255,0)"}
|
||||
>
|
||||
{toolbarPills}
|
||||
</ComposerToolbarScroller>
|
||||
{startButton}
|
||||
</ComposerToolbarRow>
|
||||
</ComposerSurface>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
<ModelPickerSheet
|
||||
favoriteModelKeys={favoriteModelKeys}
|
||||
favoritesEnabled={favoritesReady}
|
||||
groups={flow.providerGroups}
|
||||
onClose={() => setModelPickerVisible(false)}
|
||||
onSelectModel={(option) => flow.setSelectedModelKey(option.key)}
|
||||
onToggleFavorite={toggleFavorite}
|
||||
selectedModel={flow.selectedModel}
|
||||
visible={modelPickerVisible}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { ActivityIndicator, Alert, Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
@@ -11,13 +11,12 @@ import { cn } from "../../lib/cn";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
@@ -80,7 +79,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const { projectScopes } = useNewTaskFlow();
|
||||
const threads = useThreadShells();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
@@ -88,7 +87,6 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
const insets = useSafeAreaInsets();
|
||||
const chevronColor = useThemeColor("--color-chevron");
|
||||
const accentColor = useThemeColor("--color-icon-muted");
|
||||
const [expandedGroupKeys, setExpandedGroupKeys] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const { getShare, releaseShareReservation } = useIncomingShare();
|
||||
const routeShareId = Array.isArray(route.params?.incomingShareId)
|
||||
? route.params.incomingShareId[0]
|
||||
@@ -102,6 +100,33 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
: `Choose a project for the ${incomingShare.attachments.length} images you shared`
|
||||
: null;
|
||||
const screenTitle = incomingShare ? "Start a task" : "Choose project";
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
const items = useMemo(() => {
|
||||
const nextItems: Array<{
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly id: ProjectId;
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
}> = [];
|
||||
for (const group of repositoryGroups) {
|
||||
const project = group.projects[0]?.project;
|
||||
if (!project) {
|
||||
continue;
|
||||
}
|
||||
nextItems.push({
|
||||
environmentId: project.environmentId,
|
||||
id: project.id,
|
||||
key: group.key,
|
||||
title: project.title,
|
||||
workspaceRoot: project.workspaceRoot,
|
||||
});
|
||||
}
|
||||
return nextItems;
|
||||
}, [repositoryGroups]);
|
||||
const projectEmptyState = deriveProjectEmptyState(catalogState);
|
||||
const resumedDestinationKeyRef = useRef<string | null>(null);
|
||||
const reservedDestinationProject = incomingShare?.destination
|
||||
@@ -112,7 +137,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
async function selectProject(project: EnvironmentProject): Promise<void> {
|
||||
async function selectProject(item: (typeof items)[number]): Promise<void> {
|
||||
if (incomingShare?.destination && !reservedDestinationProject) {
|
||||
try {
|
||||
await releaseShareReservation(incomingShare.id, incomingShare.destination);
|
||||
@@ -129,26 +154,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
incomingShareId: incomingShare?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function toggleGroup(groupKey: string): void {
|
||||
setExpandedGroupKeys((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(groupKey)) {
|
||||
next.delete(groupKey);
|
||||
} else {
|
||||
next.add(groupKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const destination = incomingShare?.destination;
|
||||
if (!destination) {
|
||||
@@ -235,14 +248,14 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 12,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
>
|
||||
{projectScopes.length === 0 ? (
|
||||
{items.length === 0 ? (
|
||||
<View collapsable={false} className="items-center gap-3 rounded-[24px] bg-card px-6 py-8">
|
||||
{projectEmptyState.loading ? <ActivityIndicator color={accentColor} /> : null}
|
||||
<Text className="text-center text-lg font-t3-bold text-foreground">
|
||||
@@ -273,89 +286,42 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{projectScopes.map((scope, scopeIndex) => {
|
||||
const hasMultipleProjects = scope.projects.length > 1;
|
||||
const expanded = expandedGroupKeys.has(scope.key);
|
||||
const singleProject = hasMultipleProjects ? null : scope.projects[0];
|
||||
{items.map((item, index) => {
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === items.length - 1;
|
||||
|
||||
return (
|
||||
<View
|
||||
key={scope.key}
|
||||
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
|
||||
<Pressable
|
||||
key={item.key}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(item)}
|
||||
className={cn(
|
||||
"bg-card px-4 py-3.5",
|
||||
!isFirst && "border-t border-border-subtle",
|
||||
isFirst && "rounded-t-[24px]",
|
||||
isLast && "rounded-b-[24px]",
|
||||
)}
|
||||
>
|
||||
<Pressable
|
||||
disabled={singleProject !== null && reservedDestinationProject !== null}
|
||||
onPress={() => {
|
||||
if (singleProject) {
|
||||
void selectProject(singleProject);
|
||||
} else {
|
||||
toggleGroup(scope.key);
|
||||
}
|
||||
}}
|
||||
className="flex-row items-center gap-3 bg-card px-4 py-3.5"
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<View className="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={scope.representative.environmentId}
|
||||
environmentId={item.environmentId}
|
||||
size={20}
|
||||
projectTitle={scope.title}
|
||||
workspaceRoot={scope.representative.workspaceRoot}
|
||||
projectTitle={item.title}
|
||||
workspaceRoot={item.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-base leading-snug font-t3-bold">{scope.title}</Text>
|
||||
<Text
|
||||
className="text-xs leading-snug text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{hasMultipleProjects
|
||||
? `${scope.projects.length} workspaces`
|
||||
: singleProject?.workspaceRoot}
|
||||
</Text>
|
||||
<View className="flex-1">
|
||||
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
{hasMultipleProjects && expanded
|
||||
? scope.projects.map((project) => (
|
||||
<Pressable
|
||||
key={scopedProjectKey(project.environmentId, project.id)}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(project)}
|
||||
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">
|
||||
{project.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
@@ -2,10 +2,12 @@ import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contr
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { PendingApproval } from "../../lib/threadActivity";
|
||||
|
||||
export interface PendingApprovalCardProps {
|
||||
readonly approval: PendingApproval;
|
||||
readonly approvalCount: number;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly onRespond: (
|
||||
requestId: ApprovalRequestId,
|
||||
@@ -13,46 +15,106 @@ export interface PendingApprovalCardProps {
|
||||
) => Promise<unknown>;
|
||||
}
|
||||
|
||||
const APPROVAL_COPY = {
|
||||
command: {
|
||||
eyebrow: "Command",
|
||||
title: "Command approval requested",
|
||||
},
|
||||
"file-read": {
|
||||
eyebrow: "File read",
|
||||
title: "File read approval requested",
|
||||
},
|
||||
"file-change": {
|
||||
eyebrow: "File change",
|
||||
title: "File change approval requested",
|
||||
},
|
||||
} as const satisfies Record<PendingApproval["requestKind"], { eyebrow: string; title: string }>;
|
||||
|
||||
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 copy = APPROVAL_COPY[props.approval.requestKind];
|
||||
const isResponding = props.respondingApprovalId === props.approval.requestId;
|
||||
const respond = (decision: ProviderApprovalDecision) => {
|
||||
void props.onRespond(props.approval.requestId, decision);
|
||||
};
|
||||
|
||||
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">
|
||||
Approval needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
{props.approval.requestKind}
|
||||
</Text>
|
||||
{props.approval.detail ? (
|
||||
<Text className="font-sans text-sm leading-normal text-neutral-600 dark:text-neutral-400">
|
||||
{props.approval.detail}
|
||||
</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}
|
||||
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}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
|
||||
Allow session
|
||||
<View
|
||||
accessibilityLabel={copy.title}
|
||||
className="overflow-hidden rounded-[22px] border border-border bg-card"
|
||||
>
|
||||
<View className="gap-2.5 px-4 pb-3.5 pt-3.5">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.2px] text-amber-600 dark:text-amber-300">
|
||||
Pending approval
|
||||
</Text>
|
||||
</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}
|
||||
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
|
||||
</Pressable>
|
||||
<Text className="font-t3-medium text-sm tabular-nums text-foreground-tertiary">
|
||||
1/{Math.max(1, props.approvalCount)}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="font-t3-bold text-lg text-foreground">{copy.title}</Text>
|
||||
<View className="gap-1.5 rounded-xl border border-border-subtle bg-screen px-3 py-2.5">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-foreground-tertiary">
|
||||
{copy.eyebrow}
|
||||
</Text>
|
||||
<Text selectable className="font-mono text-sm leading-[21px] text-foreground-secondary">
|
||||
{props.approval.detail ?? "Review the requested operation before continuing."}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
<View className="gap-2.5 border-t border-border px-3 pb-3 pt-2.5">
|
||||
<View className="flex-row gap-2">
|
||||
<Pressable
|
||||
accessibilityLabel="Approve once"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: isResponding }}
|
||||
className={cn(
|
||||
"min-h-12 flex-1 items-center justify-center rounded-xl bg-blue-600 px-3",
|
||||
isResponding && "opacity-50",
|
||||
)}
|
||||
disabled={isResponding}
|
||||
onPress={() => respond("accept")}
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-white">Approve once</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityLabel="Always allow for this session"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: isResponding }}
|
||||
className={cn(
|
||||
"min-h-12 flex-1 items-center justify-center rounded-xl border border-secondary-border bg-secondary px-3",
|
||||
isResponding && "opacity-50",
|
||||
)}
|
||||
disabled={isResponding}
|
||||
onPress={() => respond("acceptForSession")}
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-secondary-foreground">Always allow</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
<View className="flex-row items-center justify-center gap-8">
|
||||
<Pressable
|
||||
accessibilityLabel="Decline approval"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: isResponding }}
|
||||
className={cn("min-h-7 justify-center px-2", isResponding && "opacity-50")}
|
||||
disabled={isResponding}
|
||||
hitSlop={8}
|
||||
onPress={() => respond("decline")}
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-red-600 dark:text-red-400">Decline</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityLabel="Cancel turn"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: isResponding }}
|
||||
className={cn("min-h-7 justify-center px-2", isResponding && "opacity-50")}
|
||||
disabled={isResponding}
|
||||
hitSlop={8}
|
||||
onPress={() => respond("cancel")}
|
||||
>
|
||||
<Text className="font-t3-medium text-base text-foreground-muted">Cancel turn</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import type { ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { useState } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
|
||||
export interface PendingUserInputCardProps {
|
||||
readonly pendingUserInput: PendingUserInput;
|
||||
@@ -23,86 +26,176 @@ export interface PendingUserInputCardProps {
|
||||
readonly onSubmit: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
function hasDraftAnswer(draft: PendingUserInputDraftAnswer | undefined): boolean {
|
||||
return Boolean(draft?.customAnswer?.trim() || draft?.selectedOptionLabel?.trim());
|
||||
}
|
||||
|
||||
function firstUnansweredQuestionIndex(
|
||||
questions: PendingUserInput["questions"],
|
||||
drafts: Record<string, PendingUserInputDraftAnswer>,
|
||||
): number {
|
||||
const index = questions.findIndex((question) => !hasDraftAnswer(drafts[question.id]));
|
||||
return index === -1 ? Math.max(questions.length - 1, 0) : index;
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
const [questionIndex, setQuestionIndex] = useState(() =>
|
||||
firstUnansweredQuestionIndex(props.pendingUserInput.questions, props.drafts),
|
||||
);
|
||||
const selectedColor = useThemeColor("--color-md-link");
|
||||
const activeQuestion = props.pendingUserInput.questions[questionIndex] ?? null;
|
||||
const draft = activeQuestion ? props.drafts[activeQuestion.id] : undefined;
|
||||
const isResponding = props.respondingUserInputId === props.pendingUserInput.requestId;
|
||||
const isLastQuestion = questionIndex >= props.pendingUserInput.questions.length - 1;
|
||||
const canGoBack = questionIndex > 0 && !isResponding;
|
||||
const canAdvance = hasDraftAnswer(draft);
|
||||
const canContinue = isLastQuestion ? props.answers !== null : canAdvance;
|
||||
|
||||
if (!activeQuestion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleAdvance = () => {
|
||||
if (!canContinue || isResponding) {
|
||||
return;
|
||||
}
|
||||
if (!isLastQuestion) {
|
||||
setQuestionIndex((current) =>
|
||||
Math.min(current + 1, props.pendingUserInput.questions.length - 1),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (props.answers) {
|
||||
void props.onSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
const handleBack = () => {
|
||||
if (!canGoBack) return;
|
||||
setQuestionIndex((current) => Math.max(0, current - 1));
|
||||
};
|
||||
|
||||
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">
|
||||
User input needed
|
||||
</Text>
|
||||
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
|
||||
Fill in the pending answers
|
||||
</Text>
|
||||
{props.pendingUserInput.questions.map((question) => {
|
||||
const draft = props.drafts[question.id];
|
||||
return (
|
||||
<View key={question.id} className="gap-2 pt-1">
|
||||
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
|
||||
{question.header}
|
||||
</Text>
|
||||
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
|
||||
{question.question}
|
||||
</Text>
|
||||
<View className="flex-row flex-wrap gap-2.5">
|
||||
{question.options.map((option) => {
|
||||
const selected =
|
||||
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-2.5 ",
|
||||
selected
|
||||
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
|
||||
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
|
||||
)}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
question.id,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-sm",
|
||||
selected
|
||||
? "text-sky-700 dark:text-sky-300"
|
||||
: "text-neutral-600 dark:text-neutral-300",
|
||||
)}
|
||||
>
|
||||
{option.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
<TextInput
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
|
||||
<View
|
||||
accessibilityLabel={`Input needed: ${activeQuestion.question}`}
|
||||
className="overflow-hidden rounded-[22px] border border-border bg-card"
|
||||
>
|
||||
<View className="gap-2 px-4 pb-3 pt-3.5">
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<Text
|
||||
numberOfLines={1}
|
||||
className="min-w-0 flex-1 font-t3-bold text-2xs uppercase tracking-[1.2px] text-indigo-600 dark:text-indigo-300"
|
||||
>
|
||||
{activeQuestion.header}
|
||||
</Text>
|
||||
<Text className="font-t3-medium text-sm tabular-nums text-foreground-tertiary">
|
||||
{questionIndex + 1}/{props.pendingUserInput.questions.length}
|
||||
</Text>
|
||||
</View>
|
||||
<Text className="font-t3-bold text-lg leading-[24px] text-foreground">
|
||||
{activeQuestion.question}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
<View className="gap-1.5 border-t border-border px-3 py-2.5">
|
||||
{activeQuestion.options.map((option, index) => {
|
||||
const selected =
|
||||
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
|
||||
return (
|
||||
<Pressable
|
||||
key={option.label}
|
||||
accessibilityLabel={`${option.label}. ${option.description}`}
|
||||
accessibilityRole="radio"
|
||||
accessibilityState={{ checked: selected, disabled: isResponding }}
|
||||
className={cn(
|
||||
"min-h-[68px] flex-row items-center gap-3 rounded-xl border px-3 py-3",
|
||||
selected ? "border-blue-500/45 bg-blue-500/10" : "border-transparent bg-subtle",
|
||||
isResponding && "opacity-50",
|
||||
)}
|
||||
disabled={isResponding}
|
||||
onPress={() =>
|
||||
props.onSelectOption(
|
||||
props.pendingUserInput.requestId,
|
||||
activeQuestion.id,
|
||||
option.label,
|
||||
)
|
||||
}
|
||||
placeholder="Or type a custom answer"
|
||||
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
<Pressable
|
||||
className={cn(
|
||||
"items-center justify-center rounded-2xl px-4 py-3.5",
|
||||
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
|
||||
>
|
||||
<View className="min-w-0 flex-1 gap-0.5">
|
||||
<Text className="font-t3-bold text-base text-foreground">{option.label}</Text>
|
||||
{option.description !== option.label ? (
|
||||
<Text className="font-sans text-sm leading-[19px] text-foreground-muted">
|
||||
{option.description}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{selected ? (
|
||||
<SymbolView
|
||||
name="checkmark"
|
||||
size={16}
|
||||
tintColor={selectedColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : index < 9 ? (
|
||||
<View className="size-6 items-center justify-center rounded-md border border-border bg-screen/40">
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-foreground-muted">
|
||||
{index + 1}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
})}
|
||||
|
||||
<TextInput
|
||||
accessibilityLabel="Write a custom answer"
|
||||
editable={!isResponding}
|
||||
value={draft?.customAnswer ?? ""}
|
||||
onChangeText={(value) =>
|
||||
props.onChangeCustomAnswer(props.pendingUserInput.requestId, activeQuestion.id, value)
|
||||
}
|
||||
placeholder="Write a different answer"
|
||||
selectionColor={selectedColor}
|
||||
className="mt-1 min-h-12 rounded-xl bg-screen px-3 py-3 text-base"
|
||||
/>
|
||||
</View>
|
||||
|
||||
<View className="flex-row items-center justify-between border-t border-border px-3 py-2.5">
|
||||
{questionIndex > 0 ? (
|
||||
<Pressable
|
||||
accessibilityLabel="Previous question"
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: !canGoBack }}
|
||||
className={cn("min-h-11 items-center justify-center px-3", !canGoBack && "opacity-50")}
|
||||
disabled={!canGoBack}
|
||||
onPress={handleBack}
|
||||
>
|
||||
<Text className="font-t3-bold text-base text-foreground-muted">Back</Text>
|
||||
</Pressable>
|
||||
) : (
|
||||
<View />
|
||||
)}
|
||||
disabled={
|
||||
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
|
||||
}
|
||||
onPress={() => void props.onSubmit()}
|
||||
>
|
||||
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
|
||||
</Pressable>
|
||||
<Pressable
|
||||
accessibilityLabel={isLastQuestion ? "Submit answers" : "Next question"}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ disabled: !canContinue || isResponding }}
|
||||
className={cn(
|
||||
"min-h-11 items-center justify-center rounded-full px-5",
|
||||
canContinue && !isResponding ? "bg-blue-600" : "bg-subtle-strong",
|
||||
)}
|
||||
disabled={!canContinue || isResponding}
|
||||
onPress={handleAdvance}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-bold text-base",
|
||||
canContinue && !isResponding ? "text-white" : "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{isLastQuestion ? "Submit answers" : "Next question"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -17,11 +17,10 @@ import {
|
||||
import type { ReactNode } from "react";
|
||||
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Image,
|
||||
Keyboard,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
useColorScheme,
|
||||
View,
|
||||
type ViewStyle,
|
||||
@@ -51,10 +50,11 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ModelPickerSheet } from "../../components/ModelPickerSheet";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import type { RemoteClientConnectionState } from "../../lib/connection";
|
||||
import {
|
||||
@@ -65,23 +65,23 @@ import {
|
||||
import {
|
||||
applyProviderOptionMenuEvent,
|
||||
buildProviderOptionMenuActions,
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { useModelFavorites } from "./useModelFavorites";
|
||||
|
||||
/**
|
||||
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
|
||||
* Exported so the parent can compute feed overlap / content insets.
|
||||
*/
|
||||
export const COMPOSER_COLLAPSED_CHROME = 60;
|
||||
export const COMPOSER_COLLAPSED_CHROME = 68;
|
||||
|
||||
/**
|
||||
* Height of the expanded composer (card + toolbar + vertical padding, excluding safe-area inset).
|
||||
* Used by the parent to compute the larger feed bottom inset when the composer is focused.
|
||||
*/
|
||||
export const COMPOSER_EXPANDED_CHROME = 174;
|
||||
export const COMPOSER_EXPANDED_CHROME = 184;
|
||||
|
||||
export interface ThreadComposerProps {
|
||||
readonly draftMessage: string;
|
||||
@@ -169,7 +169,7 @@ export function ComposerSurface(props: {
|
||||
style={[
|
||||
props.style,
|
||||
{
|
||||
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
|
||||
backgroundColor: props.isDarkMode ? "rgba(17,17,19,0.96)" : "rgba(255,255,255,0.96)",
|
||||
borderWidth: 1,
|
||||
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
|
||||
},
|
||||
@@ -250,11 +250,11 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
onPress={props.onPress}
|
||||
className="max-w-full flex-row items-center gap-2 rounded-full bg-white/90 px-3 py-2 shadow-sm active:opacity-70 dark:bg-neutral-900/90"
|
||||
>
|
||||
{isReconnecting ? (
|
||||
<ActivityIndicator size="small" color="#8e8e93" />
|
||||
) : (
|
||||
<View className="h-2 w-2 rounded-full bg-red-500" />
|
||||
)}
|
||||
<View
|
||||
className={
|
||||
isReconnecting ? "h-2 w-2 rounded-full bg-sky-400" : "h-2 w-2 rounded-full bg-red-500"
|
||||
}
|
||||
/>
|
||||
<Text
|
||||
className="max-w-[260px] text-sm font-t3-bold leading-snug text-foreground"
|
||||
numberOfLines={1}
|
||||
@@ -278,6 +278,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
const { onExpandedChange } = props;
|
||||
|
||||
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
|
||||
const [modelPickerVisible, setModelPickerVisible] = useState(false);
|
||||
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
|
||||
const isExpanded = isFocused;
|
||||
const canSend = hasContent;
|
||||
@@ -323,7 +324,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
environmentLabel: props.environmentLabel,
|
||||
threadSyncPhase: props.threadSyncPhase,
|
||||
});
|
||||
const toolbarFadeOpaque = isDarkMode ? "rgba(0,0,0,0.95)" : "rgba(255,255,255,0.95)";
|
||||
const toolbarFadeOpaque = isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)";
|
||||
const toolbarFadeTransparent = isDarkMode ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)";
|
||||
const selectedProviderStatus = useMemo(() => {
|
||||
if (!props.serverConfig) return null;
|
||||
@@ -602,13 +603,8 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}),
|
||||
[currentModelOption?.capabilities, currentModelSelection.options],
|
||||
);
|
||||
const configurationLabel = useMemo(
|
||||
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
|
||||
[providerOptionDescriptors],
|
||||
);
|
||||
const modelMenuActions = useMemo(
|
||||
() => buildModelMenuActions(providerGroups, currentModelSelection),
|
||||
[providerGroups, currentModelSelection],
|
||||
const { favoriteModelKeys, favoritesReady, toggleFavorite } = useModelFavorites(
|
||||
props.environmentId,
|
||||
);
|
||||
|
||||
// ── Options menu ─────────────────────────────────────────
|
||||
@@ -661,17 +657,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
);
|
||||
|
||||
// ── Menu handlers ────────────────────────────────────────
|
||||
function handleModelMenuAction(event: string) {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
const modelKey = event.slice("model:".length);
|
||||
const option = modelOptions.find((o) => o.key === modelKey);
|
||||
if (option) {
|
||||
props.onUpdateModelSelection(option.selection);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOptionsMenuAction(event: string) {
|
||||
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
|
||||
if (providerOptions) {
|
||||
@@ -694,27 +679,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
className="px-4"
|
||||
layout={COMPOSER_LAYOUT_TRANSITION}
|
||||
style={{
|
||||
paddingHorizontal: 14,
|
||||
paddingTop: isExpanded ? 8 : 6,
|
||||
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
|
||||
}}
|
||||
>
|
||||
{/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
|
||||
silently drops experimental_backgroundImage on Android, which left this
|
||||
strip fully transparent and the feed text legible through the composer. */}
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
StyleSheet.absoluteFill,
|
||||
{
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
className="relative w-full self-center"
|
||||
layout={COMPOSER_LAYOUT_TRANSITION}
|
||||
@@ -743,19 +717,23 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
borderRadius: 20,
|
||||
borderRadius: 22,
|
||||
overflow: "hidden" as const,
|
||||
paddingHorizontal: 14,
|
||||
paddingVertical: 12,
|
||||
paddingHorizontal: 12,
|
||||
paddingBottom: 6,
|
||||
paddingTop: 10,
|
||||
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
|
||||
}
|
||||
: {
|
||||
borderRadius: 999,
|
||||
borderRadius: 28,
|
||||
overflow: "hidden" as const,
|
||||
flexDirection: "row" as const,
|
||||
alignItems: "center" as const,
|
||||
minHeight: 54,
|
||||
paddingLeft: 18,
|
||||
paddingRight: 5,
|
||||
paddingVertical: 5,
|
||||
paddingVertical: 6,
|
||||
backgroundColor: isDarkMode ? "rgba(17,17,19,0.95)" : "rgba(255,255,255,0.95)",
|
||||
}
|
||||
}
|
||||
>
|
||||
@@ -784,7 +762,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onChangeText={props.onChangeDraftMessage}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onPasteImages={(uris) => void props.onNativePasteImages(uris)}
|
||||
placeholder={props.placeholder}
|
||||
placeholder={showStopAction ? "Message to queue..." : props.placeholder}
|
||||
onFocus={handleFocus}
|
||||
onBlur={handleBlur}
|
||||
onSubmit={handleSend}
|
||||
@@ -796,7 +774,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={
|
||||
isExpanded
|
||||
? {
|
||||
minHeight: 80,
|
||||
minHeight: 76,
|
||||
maxHeight: 160,
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 4,
|
||||
@@ -834,81 +812,88 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
{!isExpanded ? (
|
||||
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(100)}>
|
||||
{showStopAction ? (
|
||||
<ControlPill icon="stop.fill" variant="danger" onPress={props.onStopThread} />
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
onPress={props.onStopThread}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : (
|
||||
<ControlPill
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
showChevron={false}
|
||||
/>
|
||||
)}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{isExpanded ? (
|
||||
// Toolbar row — matches draft page layout (expanded only)
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={8} paddingHorizontal={0} paddingTop={8}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
icon="plus"
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
{isExpanded ? (
|
||||
<Animated.View entering={FadeIn.duration(160)} exiting={FadeOut.duration(120)}>
|
||||
<ComposerToolbarRow paddingBottom={0} paddingHorizontal={0} paddingTop={4}>
|
||||
<ComposerToolbarScroller
|
||||
fadeOpaque={toolbarFadeOpaque}
|
||||
fadeTransparent={toolbarFadeTransparent}
|
||||
>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Add attachment"
|
||||
icon="paperclip"
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
variant="ghost"
|
||||
/>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
accessibilityLabel="Choose model"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={18} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
onPress={() => {
|
||||
Keyboard.dismiss();
|
||||
setModelPickerVisible(true);
|
||||
}}
|
||||
variant="ghost"
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
onPress={props.onStopThread}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
showChevron={false}
|
||||
variant="ghost"
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
icon="stop.fill"
|
||||
variant="danger"
|
||||
onPress={props.onStopThread}
|
||||
showChevron={false}
|
||||
/>
|
||||
) : null}
|
||||
</ComposerToolbarScroller>
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel={sendLabel}
|
||||
icon="arrow.up"
|
||||
variant="primary"
|
||||
disabled={!canSend}
|
||||
onPress={handleSend}
|
||||
showChevron={false}
|
||||
/>
|
||||
</ComposerToolbarRow>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</ComposerSurface>
|
||||
|
||||
{/* Queue count */}
|
||||
{props.queueCount > 0 ? (
|
||||
<Animated.View entering={FadeIn.duration(180)} exiting={FadeOut.duration(120)}>
|
||||
<Text className="pt-2 text-xs text-foreground-muted">
|
||||
<Text className="pt-1 text-sm text-foreground-muted">
|
||||
{props.queueCount} queued message{props.queueCount === 1 ? "" : "s"} will send
|
||||
automatically.
|
||||
</Text>
|
||||
@@ -924,6 +909,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
swipeToCloseEnabled
|
||||
doubleTapToZoomEnabled
|
||||
/>
|
||||
<ModelPickerSheet
|
||||
favoriteModelKeys={favoriteModelKeys}
|
||||
favoritesEnabled={favoritesReady}
|
||||
groups={providerGroups}
|
||||
onClose={() => setModelPickerVisible(false)}
|
||||
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
|
||||
onToggleFavorite={toggleFavorite}
|
||||
selectedModel={currentModelSelection}
|
||||
visible={modelPickerVisible}
|
||||
/>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
@@ -51,6 +51,7 @@ export interface ThreadDetailScreenProps {
|
||||
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly activePendingApproval: PendingApproval | null;
|
||||
readonly activePendingApprovalCount: number;
|
||||
readonly respondingApprovalId: ApprovalRequestId | null;
|
||||
readonly activePendingUserInput: PendingUserInput | null;
|
||||
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
|
||||
@@ -61,8 +62,6 @@ export interface ThreadDetailScreenProps {
|
||||
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;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
@@ -183,6 +182,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
|
||||
const [composerExpanded, setComposerExpanded] = useState(false);
|
||||
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
|
||||
const activePendingRequest = props.activePendingApproval ?? props.activePendingUserInput;
|
||||
const activePendingRequestId = activePendingRequest?.requestId ?? null;
|
||||
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
|
||||
const contentPresentationKind = props.contentPresentation.kind;
|
||||
// The raw sync status enters "synchronizing" on every full fetch, cached or
|
||||
@@ -203,7 +204,11 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
})();
|
||||
const selectedThreadFeed = props.selectedThreadFeed;
|
||||
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
|
||||
const composerOverlapHeight = composerChrome + composerBottomInset;
|
||||
const requestChrome =
|
||||
(props.activePendingApproval ? 270 : 0) + (props.activePendingUserInput ? 430 : 0);
|
||||
const composerOverlapHeight = activePendingRequest
|
||||
? requestChrome + Math.max(insets.bottom, 12)
|
||||
: composerChrome + composerBottomInset;
|
||||
const estimatedOverlayHeight = composerOverlapHeight;
|
||||
// The overlay's measured height includes the home-indicator inset (the
|
||||
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
|
||||
@@ -244,6 +249,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
freeze.set(false);
|
||||
}, [freeze, selectedThreadKey]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activePendingRequestId) {
|
||||
return;
|
||||
}
|
||||
setComposerExpanded(false);
|
||||
composerEditorRef.current?.blur();
|
||||
}, [activePendingRequestId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
anchorMessageId === null ||
|
||||
@@ -373,7 +386,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
@@ -391,21 +403,24 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
pushes the resting content floor up by the same amount. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
{activePendingRequest ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
className="shrink-0 gap-2 px-2.5 pt-1.5"
|
||||
entering={FadeInDown.duration(220)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
style={{ paddingBottom: Math.max(insets.bottom, 10) }}
|
||||
>
|
||||
{props.activePendingApproval ? (
|
||||
<PendingApprovalCard
|
||||
approval={props.activePendingApproval}
|
||||
approvalCount={props.activePendingApprovalCount}
|
||||
respondingApprovalId={props.respondingApprovalId}
|
||||
onRespond={props.onRespondToApproval}
|
||||
/>
|
||||
) : null}
|
||||
{props.activePendingUserInput ? (
|
||||
<PendingUserInputCard
|
||||
key={props.activePendingUserInput.requestId}
|
||||
pendingUserInput={props.activePendingUserInput}
|
||||
drafts={props.activePendingUserInputDrafts}
|
||||
answers={props.activePendingUserInputAnswers}
|
||||
@@ -419,35 +434,37 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask the repo agent, or run a command…"
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
{activePendingRequest ? null : (
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
draftMessage={props.draftMessage}
|
||||
draftAttachments={props.draftAttachments}
|
||||
placeholder="Ask anything..."
|
||||
contentMaxWidth={contentMaxWidth}
|
||||
connectionState={props.connectionStateLabel}
|
||||
connectionError={props.connectionError}
|
||||
environmentLabel={props.environmentLabel}
|
||||
threadSyncPhase={threadSyncPhase}
|
||||
selectedThread={props.selectedThread}
|
||||
serverConfig={props.serverConfig}
|
||||
queueCount={props.selectedThreadQueueCount}
|
||||
activeThreadBusy={props.activeThreadBusy}
|
||||
environmentId={props.environmentId}
|
||||
projectCwd={props.projectWorkspaceRoot}
|
||||
bottomInset={composerBottomInset}
|
||||
onChangeDraftMessage={props.onChangeDraftMessage}
|
||||
onPickDraftImages={props.onPickDraftImages}
|
||||
onNativePasteImages={props.onNativePasteImages}
|
||||
onRemoveDraftImage={props.onRemoveDraftImage}
|
||||
onStopThread={props.onStopThread}
|
||||
onSendMessage={handleSendMessage}
|
||||
onReconnectEnvironment={props.onReconnectEnvironment}
|
||||
onUpdateModelSelection={props.onUpdateThreadModelSelection}
|
||||
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
|
||||
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
|
||||
onExpandedChange={setComposerExpanded}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
</KeyboardStickyView>
|
||||
) : null}
|
||||
|
||||
@@ -45,7 +45,14 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInUp,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type LayoutAnimationsValues,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
@@ -110,6 +117,14 @@ function formatMessageTime(input: string): string {
|
||||
return MESSAGE_TIME_FORMATTER.format(timestamp);
|
||||
}
|
||||
|
||||
// Rows shift when content above them grows (streaming text, work-log folds);
|
||||
// animating the container position turns those jumps into slides. Applied
|
||||
// conditionally — see the gated transition in ThreadFeed: while browsing
|
||||
// history the animation must NOT run, or every estimate→actual size
|
||||
// correction plays as a visible slide against the instant scroll-offset
|
||||
// compensation from maintainVisibleContentPosition.
|
||||
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
|
||||
|
||||
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
|
||||
// classNames. The fold row's min-h-11 (44px) stays taller than its single
|
||||
// text-sm line at every supported base font size (26px at the 22pt maximum),
|
||||
@@ -149,11 +164,6 @@ export interface ThreadFeedProps {
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: 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;
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -1320,24 +1330,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const [viewportHeight, setViewportHeight] = useState(0);
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
|
||||
// whenever the viewport drifts back inside its geometric threshold, which
|
||||
// yanked users off history they were reading every time a stream chunk grew
|
||||
// a row. Follow breaks when the user scrolls up and away, and re-arms only
|
||||
// when the list actually returns to the end (or on send / thread switch).
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
// A "user scroll session" spans from drag start through the end of its
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1442,6 +1434,11 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
},
|
||||
[props.onHeaderMaterialVisibilityChange],
|
||||
);
|
||||
// True while the viewport sits within ~one screen of the list end — the
|
||||
// only region where layout shifts should animate. Starts true because the
|
||||
// list opens pinned to the end.
|
||||
const nearListEnd = useSharedValue(true);
|
||||
|
||||
const handleScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
// anchorTopInset, not topContentInset: under automatic insets the list
|
||||
@@ -1449,41 +1446,40 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
|
||||
// header height back or the material toggles a full header too late.
|
||||
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
|
||||
nearListEnd.value =
|
||||
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
|
||||
);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
}
|
||||
}, []);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
// Gated variant of the 180ms feed layout slide. Instant while browsing
|
||||
// history: maintainVisibleContentPosition compensates the scroll offset in
|
||||
// the same frame a row's measured size lands, so an instant reposition is
|
||||
// invisible — animating it is exactly what made cold upward scrolls slide
|
||||
// and jump. Near the end the slide stays on: streaming growth and sends
|
||||
// shift rows at rest, where the animation is the thing preventing a hard
|
||||
// visual snap.
|
||||
const feedItemLayoutTransition = useMemo(() => {
|
||||
return (values: LayoutAnimationsValues) => {
|
||||
"worklet";
|
||||
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
|
||||
return {
|
||||
initialValues: {
|
||||
originX: values.currentOriginX,
|
||||
originY: values.currentOriginY,
|
||||
width: values.currentWidth,
|
||||
height: values.currentHeight,
|
||||
},
|
||||
animations: {
|
||||
originX: withTiming(values.targetOriginX, { duration }),
|
||||
originY: withTiming(values.targetOriginY, { duration }),
|
||||
width: withTiming(values.targetWidth, { duration }),
|
||||
height: withTiming(values.targetHeight, { duration }),
|
||||
},
|
||||
};
|
||||
};
|
||||
}, [nearListEnd]);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
@@ -1495,20 +1491,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
@@ -1835,6 +1817,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
itemLayoutAnimation={feedItemLayoutTransition}
|
||||
// Patched LegendList prop (patches/@[email protected]):
|
||||
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||
@@ -1859,7 +1842,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// anchor scrolls also lets it correct a scroll that landed on a
|
||||
// stale end target once the anchor row finishes measuring.
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling || !endFollowEnabled
|
||||
disclosureToggleSettling
|
||||
? false
|
||||
: {
|
||||
animated: true,
|
||||
@@ -1908,25 +1891,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
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>
|
||||
) : null}
|
||||
</>
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -11,7 +11,6 @@ import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
@@ -56,10 +55,8 @@ import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThrea
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
import {
|
||||
getConnectionAwareBrandHeaderOptions,
|
||||
WorkspaceConnectionTitle,
|
||||
} from "../home/WorkspaceConnectionTitle";
|
||||
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
|
||||
import { SidebarHeaderActions } from "./sidebar-header-actions";
|
||||
import { SidebarFilterButton } from "./sidebar-filter-button";
|
||||
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
|
||||
@@ -210,7 +207,6 @@ function ThreadNavigationSidebarPane(
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -496,28 +492,6 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -626,6 +600,7 @@ function ThreadNavigationSidebarPane(
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
|
||||
const listMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -954,20 +929,11 @@ function ThreadNavigationSidebarPane(
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
|
||||
canMovePinnedUp={
|
||||
arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0
|
||||
}
|
||||
canMovePinnedDown={(() => {
|
||||
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
|
||||
return index !== -1 && index < arrangedPinnedKeys.length - 1;
|
||||
})()}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
@@ -1088,16 +1054,13 @@ function ThreadNavigationSidebarPane(
|
||||
},
|
||||
[
|
||||
archiveThread,
|
||||
arrangedPinnedKeys,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
movePinnedThread,
|
||||
openPendingTask,
|
||||
pinReorderEnvironmentIds,
|
||||
pinThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
@@ -1190,13 +1153,6 @@ function ThreadNavigationSidebarPane(
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={nativeHeaderItems}
|
||||
options={{
|
||||
// Re-applies the shell's static brand slot with the
|
||||
// connection-status swap so reconnects surface in the header
|
||||
// instead of shifting the list.
|
||||
...getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: props.onOpenEnvironmentSettings,
|
||||
fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
}),
|
||||
headerSearchBarOptions: {
|
||||
ref: searchBarRef,
|
||||
autoCapitalize: "none",
|
||||
@@ -1247,6 +1203,17 @@ function ThreadNavigationSidebarPane(
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={styles.threadList}
|
||||
ListHeaderComponent={
|
||||
showsConnectionStatus ? (
|
||||
<View className="px-1.5 pt-0.5 pb-2">
|
||||
<WorkspaceConnectionStatus
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
state={catalogState}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={listEmpty}
|
||||
/>
|
||||
</GestureDetector>
|
||||
@@ -1337,19 +1304,9 @@ function ThreadNavigationSidebarPane(
|
||||
</Svg>
|
||||
</View>
|
||||
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
|
||||
{/* Title slot doubles as the connection status surface: while an
|
||||
environment reconnects, "Threads" fades to a status label in
|
||||
place (no layout shift in the list below). */}
|
||||
<WorkspaceConnectionTitle
|
||||
grow
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
size="pageTitle"
|
||||
brand={
|
||||
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
Threads
|
||||
</Text>
|
||||
}
|
||||
/>
|
||||
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
Threads
|
||||
</Text>
|
||||
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
|
||||
<ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
|
||||
<SidebarFilterButton
|
||||
@@ -1378,6 +1335,16 @@ function ThreadNavigationSidebarPane(
|
||||
value={props.searchQuery}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{showsConnectionStatus ? (
|
||||
<View className="px-3.5 pt-2.5">
|
||||
<WorkspaceConnectionStatus
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
state={catalogState}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -8,12 +8,8 @@ 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 { Platform, Pressable, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { useEnvironmentQuery } from "../../state/query";
|
||||
@@ -21,6 +17,7 @@ import { dismissGitActionResult, useGitActionProgress } from "../../state/use-vc
|
||||
import { vcsEnvironment } from "../../state/vcs";
|
||||
|
||||
import { EmptyState } from "../../components/EmptyState";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import {
|
||||
AndroidScreenHeader,
|
||||
type AndroidHeaderAction,
|
||||
@@ -64,6 +61,10 @@ import { useSelectedThreadWorktree } from "../../state/use-selected-thread-workt
|
||||
import { useThreadComposerState } from "../../state/use-thread-composer-state";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { projectThreadContentPresentation } from "./threadContentPresentation";
|
||||
import {
|
||||
resolveThreadHeaderStatus,
|
||||
type ThreadHeaderStatusPresentation,
|
||||
} from "./threadHeaderPresentation";
|
||||
import {
|
||||
useAdaptiveWorkspaceLayout,
|
||||
useAdaptiveWorkspacePaneRole,
|
||||
@@ -83,6 +84,42 @@ interface ThreadInspectorSelection {
|
||||
|
||||
type NativeHeaderItems = ReadonlyArray<Record<string, unknown>>;
|
||||
|
||||
function isUnknownRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function ThreadHeaderStatus(props: {
|
||||
readonly status: ThreadHeaderStatusPresentation;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint="Opens git controls"
|
||||
accessibilityLabel={`Thread status: ${props.status.label}`}
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={props.onPress}
|
||||
className="min-h-11 flex-row items-center justify-center px-1"
|
||||
>
|
||||
<Text
|
||||
className={
|
||||
props.status.kind === "approval"
|
||||
? "font-t3-bold text-base text-amber-600 dark:text-amber-300"
|
||||
: props.status.kind === "input"
|
||||
? "font-t3-bold text-base text-indigo-600 dark:text-indigo-300"
|
||||
: props.status.kind === "working"
|
||||
? "font-t3-bold text-base tabular-nums text-sky-600 dark:text-sky-400"
|
||||
: props.status.kind === "failed"
|
||||
? "font-t3-bold text-base text-red-600 dark:text-red-400"
|
||||
: "font-t3-bold text-base text-green-600 dark:text-green-400"
|
||||
}
|
||||
>
|
||||
{props.status.nativeLabel}
|
||||
</Text>
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function InspectorPaneRoleActivation() {
|
||||
useAdaptiveWorkspacePaneRole("inspector");
|
||||
return null;
|
||||
@@ -194,20 +231,6 @@ 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();
|
||||
@@ -299,11 +322,37 @@ function ThreadRouteContent(
|
||||
/* ─── Native header theming ──────────────────────────────────────── */
|
||||
const usesNativeHeaderGlass = NATIVE_LIQUID_GLASS_SUPPORTED;
|
||||
const headerSubtitle = [
|
||||
selectedThreadProject?.title ?? null,
|
||||
selectedThread?.branch ? `⑂ ${selectedThread.branch}` : null,
|
||||
selectedEnvironmentConnection?.environmentLabel ?? null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
const headerHasPendingApproval = Boolean(
|
||||
requests.activePendingApproval ?? selectedThread?.hasPendingApprovals,
|
||||
);
|
||||
const headerHasPendingUserInput = Boolean(
|
||||
requests.activePendingUserInput ?? selectedThread?.hasPendingUserInput,
|
||||
);
|
||||
const headerTimerEnabled =
|
||||
composer.activeThreadBusy && !headerHasPendingApproval && !headerHasPendingUserInput;
|
||||
const [headerNowMs, setHeaderNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
if (!headerTimerEnabled) {
|
||||
return;
|
||||
}
|
||||
setHeaderNowMs(Date.now());
|
||||
const intervalId = setInterval(() => setHeaderNowMs(Date.now()), 1_000);
|
||||
return () => clearInterval(intervalId);
|
||||
}, [composer.activeWorkStartedAt, headerTimerEnabled]);
|
||||
const threadHeaderStatus = resolveThreadHeaderStatus({
|
||||
hasPendingApproval: headerHasPendingApproval,
|
||||
hasPendingUserInput: headerHasPendingUserInput,
|
||||
active: composer.activeThreadBusy,
|
||||
failed:
|
||||
selectedThread?.session?.status === "error" || selectedThread?.latestTurn?.state === "error",
|
||||
activeWorkStartedAt: composer.activeWorkStartedAt,
|
||||
nowMs: headerNowMs,
|
||||
});
|
||||
/* ─── Git status for native header trigger ───────────────────────── */
|
||||
const gitStatus = useEnvironmentQuery(
|
||||
selectedThread !== null && selectedThreadCwd !== null
|
||||
@@ -703,11 +752,6 @@ function ThreadRouteContent(
|
||||
onPress: () => handleOpenTerminal(null),
|
||||
});
|
||||
}
|
||||
actions.push({
|
||||
accessibilityLabel: "Open git controls",
|
||||
icon: "point.topleft.down.curvedto.point.bottomright.up",
|
||||
onPress: handleOpenGitInspector,
|
||||
});
|
||||
if (fileInspector.supported && selectedThreadCwd !== null) {
|
||||
actions.push({
|
||||
accessibilityLabel: "Toggle inspector",
|
||||
@@ -743,6 +787,92 @@ function ThreadRouteContent(
|
||||
],
|
||||
[navigation],
|
||||
);
|
||||
const compactThreadActionItem = useMemo(() => {
|
||||
const gitItem = compactRightHeaderItems.find((item) => item.identifier === "thread-right-git");
|
||||
if (!gitItem) {
|
||||
return null;
|
||||
}
|
||||
const existingMenu = isUnknownRecord(gitItem.menu) ? gitItem.menu : null;
|
||||
const existingMenuItems =
|
||||
existingMenu && Array.isArray(existingMenu.items) ? existingMenu.items : [];
|
||||
return {
|
||||
...gitItem,
|
||||
accessibilityLabel: "Thread actions",
|
||||
icon: { name: "ellipsis", type: "sfSymbol" as const },
|
||||
identifier: "thread-right-actions",
|
||||
label: undefined,
|
||||
menu: {
|
||||
...existingMenu,
|
||||
items: [
|
||||
...existingMenuItems,
|
||||
{
|
||||
description: "Browse this thread's worktree",
|
||||
disabled: selectedThreadCwd === null,
|
||||
icon: { name: "folder", type: "sfSymbol" as const },
|
||||
label: "Files",
|
||||
onPress: handleOpenFilesInspector,
|
||||
type: "action" as const,
|
||||
},
|
||||
{
|
||||
description: "Open this thread's shell",
|
||||
disabled: !selectedThreadProject?.workspaceRoot,
|
||||
icon: { name: "terminal", type: "sfSymbol" as const },
|
||||
label: "Terminal",
|
||||
onPress: () => handleOpenTerminal(null),
|
||||
type: "action" as const,
|
||||
},
|
||||
],
|
||||
title: "Thread actions",
|
||||
},
|
||||
sharesBackground: false,
|
||||
tintColor: undefined,
|
||||
width: 44,
|
||||
};
|
||||
}, [
|
||||
compactRightHeaderItems,
|
||||
handleOpenFilesInspector,
|
||||
handleOpenTerminal,
|
||||
selectedThreadCwd,
|
||||
selectedThreadProject?.workspaceRoot,
|
||||
]);
|
||||
const compactThreadStatusItem = useMemo(
|
||||
() => ({
|
||||
accessibilityLabel: `Thread status: ${threadHeaderStatus.label}`,
|
||||
icon: {
|
||||
name:
|
||||
threadHeaderStatus.kind === "done"
|
||||
? "checkmark.circle"
|
||||
: threadHeaderStatus.kind === "working"
|
||||
? "timer"
|
||||
: threadHeaderStatus.kind === "approval"
|
||||
? "exclamationmark.circle"
|
||||
: threadHeaderStatus.kind === "input"
|
||||
? "questionmark.circle"
|
||||
: "xmark.circle",
|
||||
type: "sfSymbol" as const,
|
||||
},
|
||||
identifier: "thread-right-status",
|
||||
label: threadHeaderStatus.nativeLabel,
|
||||
onPress: handleOpenGitInspector,
|
||||
sharesBackground: false,
|
||||
tintColor: threadHeaderStatus.tintColor,
|
||||
type: "button" as const,
|
||||
}),
|
||||
[handleOpenGitInspector, threadHeaderStatus],
|
||||
);
|
||||
const nativeThreadRightHeaderItems = useMemo<NativeHeaderItems>(() => {
|
||||
if (layout.usesSplitView) {
|
||||
return threadCenterHeaderItems;
|
||||
}
|
||||
return compactThreadActionItem
|
||||
? [compactThreadStatusItem, compactThreadActionItem]
|
||||
: [compactThreadStatusItem];
|
||||
}, [
|
||||
compactThreadActionItem,
|
||||
compactThreadStatusItem,
|
||||
layout.usesSplitView,
|
||||
threadCenterHeaderItems,
|
||||
]);
|
||||
|
||||
if (!environmentId || !threadId) {
|
||||
return <OpeningThreadLoadingScreen />;
|
||||
@@ -775,6 +905,7 @@ function ThreadRouteContent(
|
||||
selectedThreadFeed={composer.selectedThreadFeed}
|
||||
activeWorkStartedAt={composer.activeWorkStartedAt}
|
||||
activePendingApproval={requests.activePendingApproval}
|
||||
activePendingApprovalCount={requests.activePendingApprovalCount}
|
||||
respondingApprovalId={requests.respondingApprovalId}
|
||||
activePendingUserInput={requests.activePendingUserInput}
|
||||
activePendingUserInputDrafts={requests.activePendingUserInputDrafts}
|
||||
@@ -784,7 +915,6 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
@@ -817,17 +947,16 @@ function ThreadRouteContent(
|
||||
<>
|
||||
{activeInspectorRenderer ? <InspectorPaneRoleActivation /> : null}
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={nativeThreadRightHeaderItems}
|
||||
options={{
|
||||
// Android draws its own in-flow header (AndroidScreenHeader below);
|
||||
// the native stack header stays iOS-only.
|
||||
headerShown: Platform.OS !== "android",
|
||||
headerTitle: selectedThread.title,
|
||||
headerTitleStyle: usesNativeHeaderGlass
|
||||
? {
|
||||
fontSize: 17,
|
||||
fontWeight: "800",
|
||||
}
|
||||
: undefined,
|
||||
headerTitleStyle: {
|
||||
fontSize: 19,
|
||||
fontWeight: "800",
|
||||
},
|
||||
title: selectedThread.title,
|
||||
headerBackVisible: !layout.usesSplitView,
|
||||
// Compact uses the NATIVE back button when a previous route exists;
|
||||
@@ -845,10 +974,8 @@ function ThreadRouteContent(
|
||||
// the git controls on the RIGHT (no center items — center space is
|
||||
// reserved for future breadcrumbs/status).
|
||||
unstable_headerRightItems:
|
||||
Platform.OS === "ios"
|
||||
? () => (layout.usesSplitView ? threadCenterHeaderItems : compactRightHeaderItems)
|
||||
: undefined,
|
||||
unstable_headerSubtitle: usesNativeHeaderGlass ? headerSubtitle : undefined,
|
||||
Platform.OS === "ios" ? () => nativeThreadRightHeaderItems : undefined,
|
||||
unstable_headerSubtitle: headerSubtitle.length > 0 ? headerSubtitle : undefined,
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -858,6 +985,9 @@ function ThreadRouteContent(
|
||||
subtitle={headerSubtitle}
|
||||
onBack={layout.usesSplitView ? undefined : () => navigation.goBack()}
|
||||
actions={androidHeaderActions}
|
||||
trailing={
|
||||
<ThreadHeaderStatus status={threadHeaderStatus} onPress={handleOpenGitInspector} />
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "../../lib/modelOptions";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import {
|
||||
@@ -58,12 +59,6 @@ import {
|
||||
} from "../../state/use-remote-environment-registry";
|
||||
import { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
|
||||
import {
|
||||
buildHomeProjectScopes,
|
||||
sortHomeProjectScopes,
|
||||
type HomeProjectScope,
|
||||
} from "../home/homeThreadList";
|
||||
import { useMobileProjectGroupingSettings } from "../../state/project-grouping";
|
||||
|
||||
type WorkspaceMode = "local" | "worktree";
|
||||
|
||||
@@ -114,7 +109,10 @@ export function branchBadgeLabel(input: {
|
||||
}
|
||||
|
||||
type NewTaskFlowContextValue = {
|
||||
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly logicalProjects: ReadonlyArray<{
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
}>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly selectedModelKey: string | null;
|
||||
@@ -177,20 +175,32 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
const groupingSettings = useMobileProjectGroupingSettings();
|
||||
const projectScopes = useMemo(
|
||||
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
const logicalProjects = useMemo(
|
||||
() =>
|
||||
sortHomeProjectScopes({
|
||||
scopes: buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
|
||||
pipe(
|
||||
repositoryGroups,
|
||||
Arr.map((group) => {
|
||||
const primaryProject = group.projects[0]?.project;
|
||||
if (!primaryProject) {
|
||||
return null;
|
||||
}
|
||||
return { key: group.key, project: primaryProject };
|
||||
}),
|
||||
threads,
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}),
|
||||
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
|
||||
Arr.filter(
|
||||
(
|
||||
entry,
|
||||
): entry is {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
} => entry !== null,
|
||||
),
|
||||
),
|
||||
[repositoryGroups],
|
||||
);
|
||||
|
||||
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
|
||||
@@ -836,7 +846,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
projectScopes,
|
||||
logicalProjects,
|
||||
selectedEnvironmentId,
|
||||
selectedProjectKey,
|
||||
selectedModelKey,
|
||||
@@ -902,7 +912,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
finishEditingPendingTask,
|
||||
interactionMode,
|
||||
loadBranches,
|
||||
projectScopes,
|
||||
logicalProjects,
|
||||
modelOptions,
|
||||
prompt,
|
||||
providerGroups,
|
||||
|
||||
@@ -1,82 +0,0 @@
|
||||
import { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
import {
|
||||
getOnlySelectableProject,
|
||||
resolveDraftProjectSelection,
|
||||
} from "./new-task-project-selection";
|
||||
|
||||
function makeProject(id: string): EnvironmentProject {
|
||||
return {
|
||||
environmentId: EnvironmentId.make("environment"),
|
||||
id: ProjectId.make(id),
|
||||
title: id,
|
||||
workspaceRoot: `/work/${id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-07-01T00:00:00.000Z",
|
||||
updatedAt: "2026-07-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function makeScope(projects: ReadonlyArray<EnvironmentProject>): HomeProjectScope {
|
||||
return {
|
||||
key: "github.com/t3tools/t3code",
|
||||
title: "T3 Code",
|
||||
representative: projects[0]!,
|
||||
projects,
|
||||
projectRefs: projects.map((project) => ({
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
describe("getOnlySelectableProject", () => {
|
||||
it("auto-selects when there is exactly one physical project", () => {
|
||||
const project = makeProject("t3code");
|
||||
expect(getOnlySelectableProject([makeScope([project])])).toBe(project);
|
||||
});
|
||||
|
||||
it("does not auto-select a representative when one group has multiple clones", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(getOnlySelectableProject([makeScope(projects)])).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDraftProjectSelection", () => {
|
||||
it("preserves an explicit project selection", () => {
|
||||
const project = makeProject("t3code");
|
||||
expect(
|
||||
resolveDraftProjectSelection("environment:t3code", [project], [makeScope([project])]),
|
||||
).toEqual({ kind: "preserve" });
|
||||
});
|
||||
|
||||
it("selects the only physical project when no project was explicitly selected", () => {
|
||||
const project = makeProject("t3code");
|
||||
expect(resolveDraftProjectSelection(null, [project], [makeScope([project])])).toEqual({
|
||||
kind: "select",
|
||||
project,
|
||||
});
|
||||
});
|
||||
|
||||
it("opens the picker for multiple physical projects in one logical group", () => {
|
||||
const projects = [makeProject("t3code"), makeProject("t3code-2"), makeProject("t3code-3")];
|
||||
expect(resolveDraftProjectSelection(null, projects, [makeScope(projects)])).toEqual({
|
||||
kind: "pick",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not preserve a project key that is missing from the catalog", () => {
|
||||
const project = makeProject("t3code");
|
||||
expect(
|
||||
resolveDraftProjectSelection("environment:removed", [project], [makeScope([project])]),
|
||||
).toEqual({
|
||||
kind: "select",
|
||||
project,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import type { HomeProjectScope } from "../home/homeThreadList";
|
||||
|
||||
export type DraftProjectSelectionResolution =
|
||||
| { readonly kind: "preserve" }
|
||||
| { readonly kind: "select"; readonly project: EnvironmentProject }
|
||||
| { readonly kind: "pick" };
|
||||
|
||||
export function getOnlySelectableProject(
|
||||
projectScopes: ReadonlyArray<HomeProjectScope>,
|
||||
): EnvironmentProject | null {
|
||||
const onlyScope = projectScopes.length === 1 ? projectScopes[0] : null;
|
||||
return onlyScope?.projects.length === 1 ? (onlyScope.projects[0] ?? null) : null;
|
||||
}
|
||||
|
||||
export function resolveDraftProjectSelection(
|
||||
selectedProjectKey: string | null,
|
||||
projects: ReadonlyArray<EnvironmentProject>,
|
||||
projectScopes: ReadonlyArray<HomeProjectScope>,
|
||||
): DraftProjectSelectionResolution {
|
||||
const hasExplicitProjectSelection =
|
||||
selectedProjectKey !== null &&
|
||||
projects.some(
|
||||
(project) => scopedProjectKey(project.environmentId, project.id) === selectedProjectKey,
|
||||
);
|
||||
if (hasExplicitProjectSelection) {
|
||||
return { kind: "preserve" };
|
||||
}
|
||||
|
||||
const onlyProject = getOnlySelectableProject(projectScopes);
|
||||
return onlyProject ? { kind: "select", project: onlyProject } : { kind: "pick" };
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type {
|
||||
EnvironmentProject,
|
||||
EnvironmentThreadShell,
|
||||
} from "@t3tools/client-runtime/state/shell";
|
||||
import type { EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
|
||||
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
@@ -53,12 +54,28 @@ const MONO_FONT = Platform.select({
|
||||
// Live Activity/widgets (amber approval, indigo input, sky working) so a
|
||||
// thread reads the same color everywhere it surfaces.
|
||||
const STATUS_LABEL_BY_STATUS: Partial<
|
||||
Record<ThreadListV2Status, { label: string; className: string }>
|
||||
Record<ThreadListV2Status, { label: string; className: string; screenColor: string }>
|
||||
> = {
|
||||
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" },
|
||||
failed: { label: "Failed", className: "text-red-700 dark:text-red-300" },
|
||||
approval: {
|
||||
label: "Approval",
|
||||
className: "text-amber-700 dark:text-amber-300",
|
||||
screenColor: "#fbbf24",
|
||||
},
|
||||
input: {
|
||||
label: "Input",
|
||||
className: "text-indigo-600 dark:text-indigo-300",
|
||||
screenColor: "#a5b4fc",
|
||||
},
|
||||
working: {
|
||||
label: "Working",
|
||||
className: "text-sky-600 dark:text-sky-400",
|
||||
screenColor: "#38bdf8",
|
||||
},
|
||||
failed: {
|
||||
label: "Failed",
|
||||
className: "text-red-700 dark:text-red-300",
|
||||
screenColor: "#f87171",
|
||||
},
|
||||
};
|
||||
|
||||
function threadTimeLabel(thread: EnvironmentThreadShell): string {
|
||||
@@ -104,7 +121,14 @@ export const ThreadListV2SectionDivider = memo(function ThreadListV2SectionDivid
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
)}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">{props.label}</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium text-foreground-tertiary",
|
||||
props.pane === "sidebar" ? "text-xs" : "text-sm",
|
||||
)}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
<View className="h-px flex-1" style={{ backgroundColor: borderColor }} />
|
||||
</View>
|
||||
);
|
||||
@@ -129,14 +153,21 @@ export const ThreadListV2SnoozedShelfHeader = memo(function ThreadListV2SnoozedS
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
"flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "mb-1.5 mt-4 px-3" : "h-[42px] px-4",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-blue-600 dark:text-blue-400">
|
||||
{props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs font-t3-medium",
|
||||
props.pane === "sidebar"
|
||||
? "text-xs text-blue-600 dark:text-blue-400"
|
||||
: "text-sm text-[#60a5fa]",
|
||||
)}
|
||||
>
|
||||
{props.pane === "sidebar" && props.expanded ? "Snoozed" : `Snoozed (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-blue-500/20 dark:bg-blue-400/15" />
|
||||
<SymbolView
|
||||
@@ -165,13 +196,18 @@ export const ThreadListV2SettledShelfHeader = memo(function ThreadListV2SettledS
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
className={cn(
|
||||
"mb-1.5 mt-4 flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "px-3" : "px-5",
|
||||
"flex-row items-center gap-2.5",
|
||||
props.pane === "sidebar" ? "mb-1.5 mt-4 px-3" : "h-[42px] px-4",
|
||||
)}
|
||||
onPress={props.onToggle}
|
||||
style={({ pressed }) => ({ opacity: pressed ? 0.6 : 1 })}
|
||||
>
|
||||
<Text className="text-xs font-t3-medium text-foreground-tertiary">
|
||||
<Text
|
||||
className={cn(
|
||||
"font-t3-medium",
|
||||
props.pane === "sidebar" ? "text-xs text-foreground-tertiary" : "text-sm text-[#74757b]",
|
||||
)}
|
||||
>
|
||||
{props.expanded ? "Settled" : `Settled (${props.count})`}
|
||||
</Text>
|
||||
<View className="h-px flex-1 bg-border" />
|
||||
@@ -201,11 +237,10 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly environmentLabel: string | null;
|
||||
readonly environmentConnectionState?: EnvironmentConnectionPhase;
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
/** Draws the "Pending" divider above the first queued row. */
|
||||
readonly showPendingDivider: boolean;
|
||||
/** Keeps row hairlines inside a section; section headers draw their own rule. */
|
||||
readonly showTrailingDivider?: boolean;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
}) {
|
||||
@@ -216,6 +251,9 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
const projectTitle =
|
||||
props.projectTitle ?? props.project?.title ?? pendingTask.creation.projectTitle ?? "";
|
||||
const branch = pendingTask.creation.branch;
|
||||
const staleEnvironment =
|
||||
props.environmentConnectionState !== undefined &&
|
||||
props.environmentConnectionState !== "connected";
|
||||
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
@@ -230,34 +268,90 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={pendingTask.message.environmentId}
|
||||
size={15}
|
||||
size={sidebarPane ? 15 : 18}
|
||||
projectTitle={projectTitle}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text className="flex-1 text-sm font-t3-medium text-foreground-muted" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 font-t3-medium",
|
||||
sidebarPane ? "text-sm text-foreground-muted" : "text-sm text-[#9a9ba1]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{projectTitle}
|
||||
</Text>
|
||||
<Text className="text-xs text-foreground-tertiary">Queued</Text>
|
||||
<Text
|
||||
className={cn(
|
||||
sidebarPane ? "text-xs text-foreground-tertiary" : "text-xs text-[#818289]",
|
||||
)}
|
||||
>
|
||||
Queued
|
||||
</Text>
|
||||
</View>
|
||||
{/* One line, unlike the two an active row allows: a queued title is
|
||||
derived from the whole prompt rather than written as a title, so the
|
||||
second line is usually a stray word or emoji rather than meaning. */}
|
||||
<Text className="mt-1 text-base font-t3-medium text-foreground" numberOfLines={1}>
|
||||
<Text
|
||||
className={cn(
|
||||
"mt-1 font-t3-medium",
|
||||
sidebarPane ? "text-base text-foreground" : "text-[17px] leading-[22px] text-[#f5f5f5]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{pendingTask.title}
|
||||
</Text>
|
||||
{branch || props.environmentLabel ? (
|
||||
<Text className="mt-1 text-xs text-foreground-muted" numberOfLines={1}>
|
||||
<View className="mt-1 flex-row items-center gap-1.5">
|
||||
{branch ? (
|
||||
<Text className="text-xs text-foreground-muted" style={{ fontFamily: MONO_FONT }}>
|
||||
{branch}
|
||||
</Text>
|
||||
<>
|
||||
{!sidebarPane ? (
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={13}
|
||||
tintColor="#696a70"
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"min-w-0 shrink",
|
||||
sidebarPane ? "text-xs text-foreground-muted" : "text-sm text-[#77787f]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{branch}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
{branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text className="text-xs text-foreground-tertiary">{props.environmentLabel}</Text>
|
||||
<View className="ml-auto flex-row items-center gap-1">
|
||||
{!sidebarPane ? (
|
||||
<SymbolView
|
||||
name={staleEnvironment ? "wifi.slash" : "desktopcomputer"}
|
||||
size={13}
|
||||
tintColor={staleEnvironment ? "#f87171" : "#696a70"}
|
||||
type="monochrome"
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
sidebarPane ? "text-xs" : "text-[13px]",
|
||||
sidebarPane
|
||||
? "text-foreground-tertiary"
|
||||
: staleEnvironment
|
||||
? "text-[#f87171]"
|
||||
: "text-[#696a70]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
@@ -291,11 +385,8 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
{sidebarPane ? (
|
||||
rowContent
|
||||
) : (
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{rowContent}</View>
|
||||
{props.showTrailingDivider !== false ? (
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
) : null}
|
||||
<View style={{ backgroundColor: "#000" }}>
|
||||
<View className="min-h-[92px] px-4 py-2.5">{rowContent}</View>
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
@@ -320,19 +411,16 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly project: EnvironmentProject | null;
|
||||
readonly projectTitle?: string;
|
||||
readonly providerDriver: string | null;
|
||||
/** Which machine hosts the thread. Null when only one environment is
|
||||
connected — repeating the same label on every row is noise. Mirrors
|
||||
the web sidebar's remote-environment cloud icon, but as text since
|
||||
phones have no hover tooltips. */
|
||||
/** Which machine hosts the thread. Compact Home always passes this so the
|
||||
merged multi-environment list keeps attribution visible. */
|
||||
readonly environmentLabel: string | null;
|
||||
readonly environmentConnectionState?: EnvironmentConnectionPhase;
|
||||
/** Hosting surface. "screen" (default) renders the compact Home idiom:
|
||||
flat edge-to-edge rows on the screen background with inset hairlines.
|
||||
flat edge-to-edge rows on a true-black background.
|
||||
"sidebar" renders the iPad split-view idiom: rounded rows blending
|
||||
into the drawer surface, selection filled with the accent color —
|
||||
matching the v1 sidebar rows. */
|
||||
readonly pane?: "screen" | "sidebar";
|
||||
/** Keeps row hairlines inside a section; section headers draw their own rule. */
|
||||
readonly showTrailingDivider?: boolean;
|
||||
/** Highlights the thread open in the detail pane (iPad split view). The
|
||||
compact Home list never sets it — phones navigate away on select. */
|
||||
readonly selected?: boolean;
|
||||
@@ -354,14 +442,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
readonly onMovePinnedThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
|
||||
/** Position flags for the pinned block so the menu disables the move that
|
||||
would fall off the end of the list. */
|
||||
readonly canMovePinnedUp?: boolean;
|
||||
readonly canMovePinnedDown?: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
@@ -390,7 +470,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onArchiveThread,
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onMovePinnedThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
@@ -403,7 +482,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onChangeRequestState?.(threadKey, prState);
|
||||
}, [onChangeRequestState, prState, threadKey]);
|
||||
|
||||
const screenColor = useThemeColor("--color-screen");
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
@@ -412,8 +490,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
// Quiescent is the absence of an actionable state, not a persistent
|
||||
// "Done" badge. A stopped session often just means the user opened this
|
||||
// thread before, so using session presence made read rows look completed.
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
const staleEnvironment =
|
||||
props.environmentConnectionState !== undefined &&
|
||||
props.environmentConnectionState !== "connected";
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
|
||||
@@ -425,14 +509,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
|
||||
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
|
||||
const handleMovePinnedUp = useCallback(
|
||||
() => onMovePinnedThread?.(thread, "up"),
|
||||
[onMovePinnedThread, thread],
|
||||
);
|
||||
const handleMovePinnedDown = useCallback(
|
||||
() => onMovePinnedThread?.(thread, "down"),
|
||||
[onMovePinnedThread, thread],
|
||||
);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
@@ -476,34 +552,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
() =>
|
||||
props.pinningSupported
|
||||
? [
|
||||
...(pinnedRow && props.pinReorderSupported === true
|
||||
? [
|
||||
{
|
||||
id: "move-pin-up",
|
||||
title: "Move up",
|
||||
image: "arrow.up",
|
||||
attributes: { disabled: props.canMovePinnedUp !== true },
|
||||
} satisfies MenuAction,
|
||||
{
|
||||
id: "move-pin-down",
|
||||
title: "Move down",
|
||||
image: "arrow.down",
|
||||
attributes: { disabled: props.canMovePinnedDown !== true },
|
||||
} satisfies MenuAction,
|
||||
]
|
||||
: []),
|
||||
pinnedRow
|
||||
? { id: "unpin", title: "Unpin", image: "pin.slash" }
|
||||
: { id: "pin", title: "Pin", image: "pin" },
|
||||
]
|
||||
: [],
|
||||
[
|
||||
pinnedRow,
|
||||
props.canMovePinnedDown,
|
||||
props.canMovePinnedUp,
|
||||
props.pinReorderSupported,
|
||||
props.pinningSupported,
|
||||
],
|
||||
[pinnedRow, props.pinningSupported],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
@@ -530,8 +584,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
@@ -548,8 +600,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
@@ -630,15 +680,19 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{props.project ? (
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
size={sidebarPane ? 15 : 18}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-sm font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
"flex-1 font-t3-medium",
|
||||
selected
|
||||
? "text-sm text-user-bubble-foreground-muted"
|
||||
: sidebarPane
|
||||
? "text-sm text-foreground-muted"
|
||||
: "text-sm text-[#9a9ba1]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -649,19 +703,30 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
selected ? "text-white" : (statusLabel?.className ?? "text-foreground-tertiary"),
|
||||
"tabular-nums",
|
||||
selected
|
||||
? "text-xs text-white"
|
||||
: sidebarPane
|
||||
? cn("text-xs", statusLabel?.className ?? "text-foreground-tertiary")
|
||||
: "text-xs",
|
||||
)}
|
||||
style={
|
||||
selected || sidebarPane ? undefined : { color: statusLabel?.screenColor ?? "#71717a" }
|
||||
}
|
||||
>
|
||||
{statusLabel?.label ?? timeLabel}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
className={cn(
|
||||
"mt-1 text-base font-t3-medium",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground",
|
||||
"mt-1 font-t3-medium",
|
||||
selected
|
||||
? "text-base text-user-bubble-foreground"
|
||||
: sidebarPane
|
||||
? "text-base text-foreground"
|
||||
: "text-[17px] leading-[22px] text-[#f5f5f5]",
|
||||
)}
|
||||
numberOfLines={2}
|
||||
numberOfLines={sidebarPane ? 2 : 1}
|
||||
>
|
||||
{thread.title}
|
||||
</Text>
|
||||
@@ -675,67 +740,112 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
) : null}
|
||||
<View className="mt-1 flex-row items-center gap-2">
|
||||
{status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: "text-red-600/80 dark:text-red-400/80",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{sidebarPane ? (
|
||||
status === "failed" && thread.session?.lastError ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: "text-red-600/80 dark:text-red-400/80",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.branch ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
{thread.branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
)
|
||||
) : status === "failed" && thread.session?.lastError ? (
|
||||
<Text className="flex-1 text-sm text-[#f87171]" numberOfLines={1}>
|
||||
{thread.session.lastError}
|
||||
</Text>
|
||||
) : thread.branch || props.environmentLabel ? (
|
||||
/* "branch · machine" share one truncating line. The machine sits
|
||||
last so a tight fit cuts the repetitive label, not the branch —
|
||||
and machine-only fills the row for non-git projects. */
|
||||
<Text
|
||||
className={cn(
|
||||
"flex-1 text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{thread.branch ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-muted",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
) : null}
|
||||
{thread.branch && props.environmentLabel ? " · " : null}
|
||||
{props.environmentLabel ? (
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-user-bubble-foreground-muted" : "text-foreground-tertiary",
|
||||
)}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
) : null}
|
||||
</Text>
|
||||
) : (
|
||||
<View className="flex-1" />
|
||||
<View className="min-w-0 flex-1 flex-row items-center gap-1.5">
|
||||
{thread.branch ? (
|
||||
<>
|
||||
<SymbolView
|
||||
name="arrow.triangle.branch"
|
||||
size={13}
|
||||
tintColor="#696a70"
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className="min-w-0 shrink text-sm text-[#77787f]"
|
||||
numberOfLines={1}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
{thread.branch}
|
||||
</Text>
|
||||
</>
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
{pr ? (
|
||||
<Text
|
||||
accessibilityLabel={pr.accessibilityLabel}
|
||||
className={cn("text-xs", selected ? "text-white" : pr.textClassName)}
|
||||
className={cn(
|
||||
"text-xs",
|
||||
selected ? "text-white" : sidebarPane ? pr.textClassName : "text-[#71717a]",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
#{pr.label}
|
||||
</Text>
|
||||
) : null}
|
||||
{!sidebarPane && props.environmentLabel ? (
|
||||
<View className="flex-row items-center gap-1">
|
||||
<SymbolView
|
||||
name={staleEnvironment ? "wifi.slash" : "desktopcomputer"}
|
||||
size={13}
|
||||
tintColor={staleEnvironment ? "#f87171" : "#696a70"}
|
||||
type="monochrome"
|
||||
/>
|
||||
<Text
|
||||
className={cn(
|
||||
"max-w-28 text-[13px]",
|
||||
staleEnvironment ? "text-[#f87171]" : "text-[#696a70]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.environmentLabel}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{props.providerDriver ? (
|
||||
<View className="opacity-60">
|
||||
<ProviderIcon provider={props.providerDriver} size={14} />
|
||||
<ProviderIcon provider={props.providerDriver} size={16} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
@@ -771,15 +881,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
{sidebarPane ? (
|
||||
cardContent
|
||||
) : (
|
||||
/* Flat native list rows: no tonal containers — colored status
|
||||
labels and text hierarchy carry state, an inset hairline
|
||||
separates rows. The opaque screen background stays so swipe
|
||||
actions reveal behind the row. */
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{cardContent}</View>
|
||||
{props.showTrailingDivider !== false ? (
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
) : null}
|
||||
<View style={{ backgroundColor: "#000" }}>
|
||||
<View className="min-h-[92px] px-4 py-2.5">{cardContent}</View>
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
@@ -789,7 +892,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
accessibilityLabel={thread.title}
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected }}
|
||||
className={sidebarPane ? undefined : "bg-screen"}
|
||||
onPress={() => {
|
||||
close();
|
||||
onSelectThread(thread);
|
||||
@@ -804,21 +906,21 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
: drawerColor,
|
||||
borderRadius: SIDEBAR_V2_ROW_RADIUS,
|
||||
})
|
||||
: ({ pressed }) => ({ opacity: pressed ? 0.7 : 1 })
|
||||
: ({ pressed }) => ({ backgroundColor: "#000", opacity: pressed ? 0.7 : 1 })
|
||||
}
|
||||
>
|
||||
{/* Settled history recedes: dimmed favicon + muted title. */}
|
||||
<View
|
||||
className={cn(
|
||||
"min-h-[44px] flex-row items-center gap-2.5 py-2",
|
||||
sidebarPane ? "px-3" : "px-5",
|
||||
"min-h-[54px] flex-row items-center gap-2.5 py-2.5",
|
||||
sidebarPane ? "px-3" : "px-4",
|
||||
)}
|
||||
>
|
||||
{props.project ? (
|
||||
<View className="opacity-40">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
size={15}
|
||||
size={sidebarPane ? 15 : 17}
|
||||
projectTitle={props.projectTitle ?? props.project.title}
|
||||
workspaceRoot={props.project.workspaceRoot}
|
||||
/>
|
||||
@@ -827,8 +929,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text
|
||||
className={cn(
|
||||
"text-base",
|
||||
selected ? "text-user-bubble-foreground" : "text-foreground-muted",
|
||||
sidebarPane ? "text-base" : "text-sm",
|
||||
selected
|
||||
? "text-user-bubble-foreground"
|
||||
: sidebarPane
|
||||
? "text-foreground-muted"
|
||||
: "text-[#7d7e84]",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
@@ -844,12 +950,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
</View>
|
||||
<Text
|
||||
className={cn(
|
||||
"text-sm tabular-nums",
|
||||
sidebarPane ? "text-sm tabular-nums" : "text-xs tabular-nums",
|
||||
selected
|
||||
? "text-user-bubble-foreground-muted"
|
||||
: snoozedRow
|
||||
? "text-blue-600 dark:text-blue-400"
|
||||
: "text-foreground-tertiary",
|
||||
: sidebarPane
|
||||
? "text-foreground-tertiary"
|
||||
: "text-[#55565b]",
|
||||
)}
|
||||
style={{ fontFamily: MONO_FONT }}
|
||||
>
|
||||
@@ -864,7 +972,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
return (
|
||||
<>
|
||||
<ThreadSwipeable
|
||||
backgroundColor={sidebarPane ? drawerColor : screenColor}
|
||||
backgroundColor={sidebarPane ? drawerColor : "#000"}
|
||||
compactActions={variant === "slim"}
|
||||
containerStyle={
|
||||
sidebarPane ? { borderRadius: SIDEBAR_V2_ROW_RADIUS, overflow: "hidden" } : undefined
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { formatThreadHeaderElapsed, resolveThreadHeaderStatus } from "./threadHeaderPresentation";
|
||||
|
||||
describe("thread header presentation", () => {
|
||||
it("formats the working timer as compact minutes and seconds", () => {
|
||||
expect(
|
||||
formatThreadHeaderElapsed("2026-07-31T12:00:00.000Z", Date.parse("2026-07-31T12:02:14.000Z")),
|
||||
).toBe("2:14");
|
||||
expect(formatThreadHeaderElapsed("invalid", Date.now())).toBeNull();
|
||||
});
|
||||
|
||||
it("prioritizes actionable states over active work", () => {
|
||||
expect(
|
||||
resolveThreadHeaderStatus({
|
||||
hasPendingApproval: true,
|
||||
hasPendingUserInput: true,
|
||||
active: true,
|
||||
failed: false,
|
||||
activeWorkStartedAt: "2026-07-31T12:00:00.000Z",
|
||||
nowMs: Date.parse("2026-07-31T12:02:14.000Z"),
|
||||
}).kind,
|
||||
).toBe("approval");
|
||||
expect(
|
||||
resolveThreadHeaderStatus({
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: true,
|
||||
active: true,
|
||||
failed: false,
|
||||
activeWorkStartedAt: null,
|
||||
nowMs: 0,
|
||||
}).kind,
|
||||
).toBe("input");
|
||||
});
|
||||
|
||||
it("shows a timed working state and a green done state", () => {
|
||||
expect(
|
||||
resolveThreadHeaderStatus({
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
active: true,
|
||||
failed: false,
|
||||
activeWorkStartedAt: "2026-07-31T12:00:00.000Z",
|
||||
nowMs: Date.parse("2026-07-31T12:02:14.000Z"),
|
||||
}),
|
||||
).toMatchObject({ kind: "working", label: "2:14", nativeLabel: "2:14" });
|
||||
expect(
|
||||
resolveThreadHeaderStatus({
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
active: false,
|
||||
failed: false,
|
||||
activeWorkStartedAt: null,
|
||||
nowMs: 0,
|
||||
}),
|
||||
).toMatchObject({ kind: "done", label: "Done", nativeLabel: "Done" });
|
||||
});
|
||||
|
||||
it("does not label failed work as done", () => {
|
||||
expect(
|
||||
resolveThreadHeaderStatus({
|
||||
hasPendingApproval: false,
|
||||
hasPendingUserInput: false,
|
||||
active: false,
|
||||
failed: true,
|
||||
activeWorkStartedAt: null,
|
||||
nowMs: 0,
|
||||
}),
|
||||
).toMatchObject({ kind: "failed", label: "Failed" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
export type ThreadHeaderStatusKind = "approval" | "input" | "working" | "failed" | "done";
|
||||
|
||||
export interface ThreadHeaderStatusPresentation {
|
||||
readonly kind: ThreadHeaderStatusKind;
|
||||
readonly label: string;
|
||||
readonly nativeLabel: string;
|
||||
readonly tintColor: string;
|
||||
}
|
||||
|
||||
export function formatThreadHeaderElapsed(startedAt: string | null, nowMs: number): string | null {
|
||||
if (!startedAt) {
|
||||
return null;
|
||||
}
|
||||
const startedAtMs = Date.parse(startedAt);
|
||||
if (Number.isNaN(startedAtMs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const totalSeconds = Math.max(0, Math.floor((nowMs - startedAtMs) / 1_000));
|
||||
const minutes = Math.floor(totalSeconds / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
return `${minutes}:${String(seconds).padStart(2, "0")}`;
|
||||
}
|
||||
|
||||
export function resolveThreadHeaderStatus(input: {
|
||||
readonly hasPendingApproval: boolean;
|
||||
readonly hasPendingUserInput: boolean;
|
||||
readonly active: boolean;
|
||||
readonly failed: boolean;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly nowMs: number;
|
||||
}): ThreadHeaderStatusPresentation {
|
||||
if (input.hasPendingApproval) {
|
||||
return {
|
||||
kind: "approval",
|
||||
label: "Approval",
|
||||
nativeLabel: "Approval",
|
||||
tintColor: "#ffd60a",
|
||||
};
|
||||
}
|
||||
if (input.hasPendingUserInput) {
|
||||
return {
|
||||
kind: "input",
|
||||
label: "Input",
|
||||
nativeLabel: "Input",
|
||||
tintColor: "#7d7aff",
|
||||
};
|
||||
}
|
||||
if (input.active) {
|
||||
const elapsed = formatThreadHeaderElapsed(input.activeWorkStartedAt, input.nowMs);
|
||||
return {
|
||||
kind: "working",
|
||||
label: elapsed ?? "Working",
|
||||
nativeLabel: elapsed ?? "Working",
|
||||
tintColor: "#0a84ff",
|
||||
};
|
||||
}
|
||||
if (input.failed) {
|
||||
return {
|
||||
kind: "failed",
|
||||
label: "Failed",
|
||||
nativeLabel: "Failed",
|
||||
tintColor: "#f87171",
|
||||
};
|
||||
}
|
||||
return {
|
||||
kind: "done",
|
||||
label: "Done",
|
||||
nativeLabel: "Done",
|
||||
tintColor: "#30d158",
|
||||
};
|
||||
}
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
@@ -384,8 +383,8 @@ export function buildThreadListV2Items(input: {
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: snooze outranks everything, including a
|
||||
// pin — a snoozed thread leaves the list until it wakes (or raises its
|
||||
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
|
||||
// thread reappears at its exact spot in the pinned block.
|
||||
// hand). The pin survives underneath, so a woken thread reappears at
|
||||
// its original spot in the creation-ordered pinned block.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
@@ -445,7 +444,7 @@ export function buildThreadListV2Items(input: {
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of sortPinnedThreadsByOrderKey(pinned)) {
|
||||
for (const thread of sortThreadsForListV2(pinned)) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useAtomSet, useAtomValue } from "@effect/atom-react";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import type { ModelOption } from "../../lib/modelOptions";
|
||||
import type { Preferences } from "../../persistence/mobile-preferences";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
|
||||
/** Persists model favorites on this device without inventing a server setting. */
|
||||
export function useModelFavorites(environmentId: EnvironmentId | null) {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const favoritesReady = AsyncResult.isSuccess(preferencesResult);
|
||||
const storedKeys = favoritesReady ? (preferencesResult.value.favoriteModelKeys ?? []) : [];
|
||||
const environmentPrefix = environmentId === null ? null : `${environmentId}:`;
|
||||
|
||||
const favoriteModelKeys = useMemo(() => {
|
||||
if (environmentPrefix === null) return new Set<string>();
|
||||
return new Set(
|
||||
storedKeys.flatMap((key) =>
|
||||
key.startsWith(environmentPrefix) ? [key.slice(environmentPrefix.length)] : [],
|
||||
),
|
||||
);
|
||||
}, [environmentPrefix, storedKeys]);
|
||||
|
||||
const toggleFavorite = useCallback(
|
||||
(option: ModelOption) => {
|
||||
if (environmentPrefix === null || !favoritesReady) return;
|
||||
const scopedKey = `${environmentPrefix}${option.key}`;
|
||||
savePreferences((current: Preferences) => {
|
||||
const currentKeys = current.favoriteModelKeys ?? [];
|
||||
return {
|
||||
favoriteModelKeys: currentKeys.includes(scopedKey)
|
||||
? currentKeys.filter((key) => key !== scopedKey)
|
||||
: [...currentKeys, scopedKey],
|
||||
};
|
||||
});
|
||||
},
|
||||
[environmentPrefix, favoritesReady, savePreferences],
|
||||
);
|
||||
|
||||
return { favoriteModelKeys, favoritesReady, toggleFavorite };
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
|
||||
import {
|
||||
buildModelMenuActions,
|
||||
buildModelOptions,
|
||||
buildModelPickerProviderGroups,
|
||||
groupByProvider,
|
||||
resolveSelectableModelSelection,
|
||||
} from "./modelOptions";
|
||||
@@ -88,6 +89,46 @@ describe("mobile model options", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps legacy models folded into their provider while search can reveal them", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
{
|
||||
instanceId: "codex",
|
||||
driver: "codex",
|
||||
displayName: "Codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
auth: { status: "authenticated" },
|
||||
models: [
|
||||
{
|
||||
slug: "gpt-current",
|
||||
name: "GPT Current",
|
||||
isCustom: false,
|
||||
capabilities: null,
|
||||
},
|
||||
{
|
||||
slug: "gpt-legacy",
|
||||
name: "GPT Legacy",
|
||||
isCustom: false,
|
||||
isLegacy: true,
|
||||
capabilities: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} as unknown as ServerConfig;
|
||||
|
||||
const groups = groupByProvider(buildModelOptions(config, null));
|
||||
expect(buildModelPickerProviderGroups(groups, "")[0]).toMatchObject({
|
||||
currentModels: [{ label: "GPT Current" }],
|
||||
legacyModels: [{ label: "GPT Legacy" }],
|
||||
});
|
||||
expect(buildModelPickerProviderGroups(groups, "legacy")[0]).toMatchObject({
|
||||
currentModels: [],
|
||||
legacyModels: [{ label: "GPT Legacy" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes a legacy fallback selection against current capabilities", () => {
|
||||
const config = {
|
||||
providers: [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
ModelSelection,
|
||||
ProviderInstanceId,
|
||||
ServerConfig as T3ServerConfig,
|
||||
} from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
@@ -13,7 +14,7 @@ export type ModelOption = {
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly subtitle: string;
|
||||
readonly providerKey: string;
|
||||
readonly providerKey: ProviderInstanceId;
|
||||
readonly providerLabel: string;
|
||||
readonly providerDriver: string;
|
||||
readonly isDefault: boolean;
|
||||
@@ -23,11 +24,16 @@ export type ModelOption = {
|
||||
};
|
||||
|
||||
export type ProviderGroup = {
|
||||
readonly providerKey: string;
|
||||
readonly providerKey: ProviderInstanceId;
|
||||
readonly providerLabel: string;
|
||||
readonly models: ReadonlyArray<ModelOption>;
|
||||
};
|
||||
|
||||
export type ModelPickerProviderGroup = ProviderGroup & {
|
||||
readonly currentModels: ReadonlyArray<ModelOption>;
|
||||
readonly legacyModels: ReadonlyArray<ModelOption>;
|
||||
};
|
||||
|
||||
function providerDisplayLabel(provider: {
|
||||
readonly displayName?: string | undefined;
|
||||
readonly driver: string;
|
||||
@@ -149,7 +155,7 @@ export function buildModelOptions(
|
||||
}
|
||||
|
||||
export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyArray<ProviderGroup> {
|
||||
const groups = new Map<string, { providerLabel: string; models: ModelOption[] }>();
|
||||
const groups = new Map<ProviderInstanceId, { providerLabel: string; models: ModelOption[] }>();
|
||||
for (const option of options) {
|
||||
const existing = groups.get(option.providerKey);
|
||||
if (existing) {
|
||||
@@ -169,6 +175,37 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the provider sections used by the full-screen mobile picker. Legacy
|
||||
* models stay separate so the UI can keep them folded until requested while
|
||||
* search can still reveal a matching legacy model immediately.
|
||||
*/
|
||||
export function buildModelPickerProviderGroups(
|
||||
groups: ReadonlyArray<ProviderGroup>,
|
||||
query: string,
|
||||
): ReadonlyArray<ModelPickerProviderGroup> {
|
||||
const tokens = query.trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean);
|
||||
const matches = (option: ModelOption) => {
|
||||
if (tokens.length === 0) return true;
|
||||
const searchable = [
|
||||
option.label,
|
||||
option.selection.model,
|
||||
option.providerLabel,
|
||||
option.providerDriver,
|
||||
]
|
||||
.join(" ")
|
||||
.toLocaleLowerCase();
|
||||
return tokens.every((token) => searchable.includes(token));
|
||||
};
|
||||
|
||||
return groups.flatMap((group) => {
|
||||
const currentModels = group.models.filter((model) => !model.isLegacy && matches(model));
|
||||
const legacyModels = group.models.filter((model) => model.isLegacy && matches(model));
|
||||
if (currentModels.length === 0 && legacyModels.length === 0) return [];
|
||||
return [{ ...group, currentModels, legacyModels }];
|
||||
});
|
||||
}
|
||||
|
||||
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
|
||||
return {
|
||||
id: `model:${option.key}`,
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import { groupProjectsByRepository } from "./repositoryGroups";
|
||||
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
function makeProject(
|
||||
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
|
||||
): EnvironmentProject {
|
||||
return {
|
||||
workspaceRoot: `/workspaces/${input.id}`,
|
||||
repositoryIdentity: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-04-01T00:00:00.000Z",
|
||||
updatedAt: "2026-04-01T00:00:00.000Z",
|
||||
...input,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(
|
||||
input: Partial<EnvironmentThreadShell> &
|
||||
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title" | "modelSelection">,
|
||||
): EnvironmentThreadShell {
|
||||
return {
|
||||
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,
|
||||
session: null,
|
||||
latestUserMessageAt: null,
|
||||
hasPendingApprovals: false,
|
||||
hasPendingUserInput: false,
|
||||
hasActionableProposedPlan: false,
|
||||
...input,
|
||||
settledOverride: input.settledOverride ?? null,
|
||||
settledAt: input.settledAt ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
describe("groupProjectsByRepository", () => {
|
||||
it("groups projects across environments by repository identity", () => {
|
||||
const repoIdentity = {
|
||||
canonicalKey: "github.com/t3tools/t3code",
|
||||
locator: {
|
||||
source: "git-remote" as const,
|
||||
remoteName: "origin",
|
||||
remoteUrl: "[email protected]:t3tools/t3code.git",
|
||||
},
|
||||
provider: "github",
|
||||
owner: "t3tools",
|
||||
name: "t3code",
|
||||
displayName: "T3 Code",
|
||||
};
|
||||
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "T3 Code",
|
||||
repositoryIdentity: repoIdentity,
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: EnvironmentId.make("env-staging"),
|
||||
id: ProjectId.make("project-staging"),
|
||||
title: "T3 Code",
|
||||
repositoryIdentity: repoIdentity,
|
||||
}),
|
||||
];
|
||||
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId: EnvironmentId.make("env-staging"),
|
||||
id: ThreadId.make("thread-2"),
|
||||
projectId: ProjectId.make("project-staging"),
|
||||
title: "Fix reconnect flow",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
updatedAt: "2026-04-02T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-local"),
|
||||
title: "Polish mobile shell",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
updatedAt: "2026-04-03T12:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const groups = groupProjectsByRepository({ projects, threads });
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]).toMatchObject({
|
||||
key: "github.com/t3tools/t3code",
|
||||
title: "T3 Code",
|
||||
subtitle: "t3tools/t3code",
|
||||
projectCount: 2,
|
||||
threadCount: 2,
|
||||
});
|
||||
expect(
|
||||
groups[0]?.projects.map((entry) => ({
|
||||
environmentId: entry.project.environmentId,
|
||||
latestActivityAt: entry.latestActivityAt,
|
||||
threads: entry.threads.map((thread) => thread.id),
|
||||
})),
|
||||
).toEqual([
|
||||
{
|
||||
environmentId: "env-local",
|
||||
latestActivityAt: "2026-04-03T12:00:00.000Z",
|
||||
threads: ["thread-1"],
|
||||
},
|
||||
{
|
||||
environmentId: "env-staging",
|
||||
latestActivityAt: "2026-04-02T12:00:00.000Z",
|
||||
threads: ["thread-2"],
|
||||
},
|
||||
]);
|
||||
expect(groups[0]?.latestActivityAt).toBe("2026-04-03T12:00:00.000Z");
|
||||
});
|
||||
|
||||
it("orders threads, projects, and repository groups by latest activity", () => {
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ProjectId.make("older-project"),
|
||||
title: "Older",
|
||||
}),
|
||||
makeProject({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ProjectId.make("newer-project"),
|
||||
title: "Newer",
|
||||
}),
|
||||
];
|
||||
|
||||
const threads = [
|
||||
makeThread({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ThreadId.make("older-thread"),
|
||||
projectId: ProjectId.make("older-project"),
|
||||
title: "Older thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
updatedAt: "2026-04-02T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ThreadId.make("newer-thread"),
|
||||
projectId: ProjectId.make("older-project"),
|
||||
title: "Newer thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
updatedAt: "2026-04-04T12:00:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ThreadId.make("newest-thread"),
|
||||
projectId: ProjectId.make("newer-project"),
|
||||
title: "Newest thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
updatedAt: "2026-04-05T12:00:00.000Z",
|
||||
}),
|
||||
];
|
||||
|
||||
const groups = groupProjectsByRepository({ projects, threads });
|
||||
|
||||
expect(groups.map((group) => group.title)).toEqual(["Newer", "Older"]);
|
||||
expect(groups[1]?.projects[0]?.threads.map((thread) => thread.id)).toEqual([
|
||||
"newer-thread",
|
||||
"older-thread",
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to a scoped project key when repository identity is unavailable", () => {
|
||||
const projects = [
|
||||
makeProject({
|
||||
environmentId: EnvironmentId.make("env-local"),
|
||||
id: ProjectId.make("project-local"),
|
||||
title: "Scratchpad",
|
||||
}),
|
||||
];
|
||||
|
||||
const groups = groupProjectsByRepository({ projects, threads: [] });
|
||||
|
||||
expect(groups).toHaveLength(1);
|
||||
expect(groups[0]?.key).toBe("env-local:project-local");
|
||||
expect(groups[0]?.title).toBe("Scratchpad");
|
||||
expect(groups[0]?.subtitle).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import * as Order from "effect/Order";
|
||||
import * as Arr from "effect/Array";
|
||||
import type { RepositoryIdentity } from "@t3tools/contracts";
|
||||
|
||||
import { scopedProjectKey } from "./scopedEntities";
|
||||
import { EnvironmentProject, EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
|
||||
const DateDescending = Order.flip(Order.Date);
|
||||
|
||||
export interface RepositoryProjectGroup {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
readonly latestActivityAt: string;
|
||||
}
|
||||
|
||||
export interface RepositoryGroup {
|
||||
readonly key: string;
|
||||
readonly title: string;
|
||||
readonly subtitle: string | null;
|
||||
readonly repositoryIdentity: RepositoryIdentity | null;
|
||||
readonly projectCount: number;
|
||||
readonly threadCount: number;
|
||||
readonly latestActivityAt: string;
|
||||
readonly projects: ReadonlyArray<RepositoryProjectGroup>;
|
||||
}
|
||||
|
||||
function compareIsoDateDescending(left: string, right: string): number {
|
||||
return new Date(right).getTime() - new Date(left).getTime();
|
||||
}
|
||||
|
||||
function deriveRepositoryGroupKey(project: EnvironmentProject): string {
|
||||
return (
|
||||
project.repositoryIdentity?.canonicalKey ?? scopedProjectKey(project.environmentId, project.id)
|
||||
);
|
||||
}
|
||||
|
||||
function deriveRepositoryTitle(project: EnvironmentProject): string {
|
||||
const identity = project.repositoryIdentity;
|
||||
return identity?.displayName ?? identity?.name ?? project.title;
|
||||
}
|
||||
|
||||
function deriveRepositorySubtitle(identity: RepositoryIdentity | null | undefined): string | null {
|
||||
if (!identity) {
|
||||
return null;
|
||||
}
|
||||
if (identity.owner && identity.name) {
|
||||
return `${identity.owner}/${identity.name}`;
|
||||
}
|
||||
return identity.canonicalKey;
|
||||
}
|
||||
|
||||
function deriveProjectLatestActivity(
|
||||
project: EnvironmentProject,
|
||||
threads: ReadonlyArray<EnvironmentThreadShell>,
|
||||
): string {
|
||||
const latestThread = threads[0];
|
||||
return latestThread?.updatedAt ?? latestThread?.createdAt ?? project.updatedAt;
|
||||
}
|
||||
|
||||
export function groupProjectsByRepository(input: {
|
||||
readonly projects: ReadonlyArray<EnvironmentProject>;
|
||||
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
|
||||
}): ReadonlyArray<RepositoryGroup> {
|
||||
const threadsByProjectKey = new Map<string, EnvironmentThreadShell[]>();
|
||||
|
||||
for (const thread of input.threads) {
|
||||
const key = scopedProjectKey(thread.environmentId, thread.projectId);
|
||||
const existing = threadsByProjectKey.get(key);
|
||||
if (existing) {
|
||||
existing.push(thread);
|
||||
} else {
|
||||
threadsByProjectKey.set(key, [thread]);
|
||||
}
|
||||
}
|
||||
|
||||
const grouped = new Map<string, RepositoryGroup>();
|
||||
|
||||
for (const project of input.projects) {
|
||||
const key = deriveRepositoryGroupKey(project);
|
||||
const projectKey = scopedProjectKey(project.environmentId, project.id);
|
||||
const threads = Arr.sortWith(
|
||||
threadsByProjectKey.get(projectKey) ?? [],
|
||||
(s) => new Date(s.updatedAt ?? s.createdAt),
|
||||
DateDescending,
|
||||
);
|
||||
|
||||
const latestActivityAt = deriveProjectLatestActivity(project, threads);
|
||||
const projectGroup: RepositoryProjectGroup = {
|
||||
key: projectKey,
|
||||
project,
|
||||
threads,
|
||||
latestActivityAt,
|
||||
};
|
||||
|
||||
const existing = grouped.get(key);
|
||||
if (!existing) {
|
||||
grouped.set(key, {
|
||||
key,
|
||||
title: deriveRepositoryTitle(project),
|
||||
subtitle: deriveRepositorySubtitle(project.repositoryIdentity),
|
||||
repositoryIdentity: project.repositoryIdentity ?? null,
|
||||
projectCount: 1,
|
||||
threadCount: threads.length,
|
||||
latestActivityAt,
|
||||
projects: [projectGroup],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
grouped.set(key, {
|
||||
...existing,
|
||||
title: existing.repositoryIdentity ? existing.title : deriveRepositoryTitle(project),
|
||||
subtitle: existing.subtitle ?? deriveRepositorySubtitle(project.repositoryIdentity),
|
||||
repositoryIdentity: existing.repositoryIdentity ?? project.repositoryIdentity ?? null,
|
||||
projectCount: existing.projectCount + 1,
|
||||
threadCount: existing.threadCount + threads.length,
|
||||
latestActivityAt:
|
||||
compareIsoDateDescending(existing.latestActivityAt, latestActivityAt) > 0
|
||||
? latestActivityAt
|
||||
: existing.latestActivityAt,
|
||||
projects: Arr.sortWith(
|
||||
[...existing.projects, projectGroup],
|
||||
(s) => new Date(s.latestActivityAt),
|
||||
DateDescending,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return Arr.sortWith(grouped.values(), (s) => new Date(s.latestActivityAt), DateDescending);
|
||||
}
|
||||
@@ -532,39 +532,3 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -80,8 +80,6 @@ interface WorkLogEntry {
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
activityKind: OrchestrationThreadActivity["kind"];
|
||||
collapseKey?: string;
|
||||
/** Grouping key for subagent lifecycle rows (one row per agent). */
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
type RawThreadFeedEntry =
|
||||
@@ -237,63 +235,6 @@ function resolvePendingUserInputAnswer(
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
* task.completed — these rows are mobile's only terminal signal for them. */
|
||||
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
|
||||
"idle",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
]);
|
||||
|
||||
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
|
||||
if (activity.kind !== "task.updated") {
|
||||
return false;
|
||||
}
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
return (
|
||||
payload?.timelineBypass === true &&
|
||||
typeof payload.status === "string" &&
|
||||
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
|
||||
* activity lives in the Agents sheet, not the work log. Terminal rows are
|
||||
* kept — with no Agents surface on mobile they are the terminal signal
|
||||
* (a surface that hides rows must keep its own terminal signal). That means
|
||||
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
|
||||
* children never emit task.completed — review finding).
|
||||
*/
|
||||
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
if (!payload) {
|
||||
return false;
|
||||
}
|
||||
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
|
||||
if (payload.timelineBypass === true && !isTerminalTaskRow) {
|
||||
return true;
|
||||
}
|
||||
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
|
||||
// the only signal mobile gets (no Agents sheet), so it stays. Only an
|
||||
// agent's own background work (stamped "background") is internal — same
|
||||
// rule as web (review finding: hiding on agentId alone dropped nested
|
||||
// completions with no replacement UI).
|
||||
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
|
||||
if (!ownedByAgent) {
|
||||
return false;
|
||||
}
|
||||
return !(isTerminalTaskRow && payload.agentKind === "agent");
|
||||
}
|
||||
|
||||
function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
@@ -302,13 +243,9 @@ function deriveWorkLogEntries(
|
||||
for (const activity of ordered) {
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started") continue;
|
||||
// Terminal bypassed updates pass: Codex children's only terminal signal.
|
||||
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
|
||||
if (activity.kind === "tool.progress") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
if (activity.summary === "Checkpoint captured") continue;
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
if (isAgentInternalActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries);
|
||||
@@ -334,13 +271,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
// task.updated included: terminal bypassed updates (Codex children's only
|
||||
// terminal signal) must carry task identity so they collapse per child
|
||||
// instead of stacking anonymous "Task idle" rows.
|
||||
const isTaskActivity =
|
||||
activity.kind === "task.progress" ||
|
||||
activity.kind === "task.completed" ||
|
||||
activity.kind === "task.updated";
|
||||
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
|
||||
const taskSummary =
|
||||
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
|
||||
? payload.summary
|
||||
@@ -353,15 +284,10 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
? payload.detail
|
||||
: null;
|
||||
const taskLabel = taskSummary || taskDetailAsLabel;
|
||||
const taskId =
|
||||
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
|
||||
? payload.taskId
|
||||
: undefined;
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
...(taskId ? { taskId } : {}),
|
||||
label: taskLabel || activity.summary,
|
||||
tone:
|
||||
activity.kind === "task.progress"
|
||||
@@ -426,25 +352,7 @@ function collapseDerivedWorkLogEntries(
|
||||
entries: ReadonlyArray<DerivedWorkLogEntry>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
const collapsed: DerivedWorkLogEntry[] = [];
|
||||
// Subagent rows collapse by identity, not adjacency (quiet-timeline
|
||||
// guarantee; mirrors web's session-logic).
|
||||
const taskRowIndex = new Map<string, number>();
|
||||
for (const entry of entries) {
|
||||
const isTaskRow =
|
||||
entry.taskId !== undefined &&
|
||||
(entry.activityKind === "task.progress" ||
|
||||
entry.activityKind === "task.completed" ||
|
||||
entry.activityKind === "task.updated");
|
||||
if (isTaskRow && entry.taskId !== undefined) {
|
||||
const existingIndex = taskRowIndex.get(entry.taskId);
|
||||
if (existingIndex !== undefined) {
|
||||
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
|
||||
continue;
|
||||
}
|
||||
taskRowIndex.set(entry.taskId, collapsed.length);
|
||||
collapsed.push(entry);
|
||||
continue;
|
||||
}
|
||||
const previous = collapsed.at(-1);
|
||||
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
|
||||
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
|
||||
|
||||
@@ -5,7 +5,6 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
|
||||
import * as MobileDatabase from "./mobile-database";
|
||||
import * as MobileSecureStorage from "./mobile-secure-storage";
|
||||
@@ -23,9 +22,9 @@ export interface Preferences {
|
||||
readonly codeWordBreak?: boolean;
|
||||
readonly connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
readonly collapsedProjectGroups?: readonly string[];
|
||||
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
|
||||
/** Device-local model favorites, scoped as environment:model-option keys. */
|
||||
readonly favoriteModelKeys?: readonly string[];
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
readonly projectGroupingMode?: SidebarProjectGroupingMode;
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted out of per
|
||||
@@ -82,8 +81,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
codeWordBreak?: boolean;
|
||||
connectOnboardingOptOutAccounts?: ReadonlyArray<string>;
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
favoriteModelKeys?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
projectGroupingMode?: SidebarProjectGroupingMode;
|
||||
threadListV2Enabled?: boolean;
|
||||
} = {};
|
||||
|
||||
@@ -111,16 +110,14 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (Array.isArray(parsed.favoriteModelKeys)) {
|
||||
preferences.favoriteModelKeys = parsed.favoriteModelKeys.filter(
|
||||
(key): key is string => typeof key === "string",
|
||||
);
|
||||
}
|
||||
if (typeof parsed.projectGroupingEnabled === "boolean") {
|
||||
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
|
||||
}
|
||||
if (
|
||||
parsed.projectGroupingMode === "repository" ||
|
||||
parsed.projectGroupingMode === "repository_path" ||
|
||||
parsed.projectGroupingMode === "separate"
|
||||
) {
|
||||
preferences.projectGroupingMode = parsed.projectGroupingMode;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
}
|
||||
|
||||
@@ -124,6 +124,36 @@ describe("mobile preferences state", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("applies functional preference updates against the latest optimistic value", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = makePreferencesState({
|
||||
load: Effect.succeed({ favoriteModelKeys: ["env:codex:gpt-5"] }),
|
||||
savePatch: (patch) => Effect.succeed(patch),
|
||||
});
|
||||
const registry = AtomRegistry.make();
|
||||
const unmountPreferences = registry.mount(state.preferencesAtom);
|
||||
const unmountUpdate = registry.mount(state.updatePreferencesAtom);
|
||||
|
||||
yield* AtomRegistry.getResult(registry, state.preferencesAtom, {
|
||||
suspendOnWaiting: true,
|
||||
});
|
||||
registry.set(state.updatePreferencesAtom, (current) => ({
|
||||
favoriteModelKeys: [...(current.favoriteModelKeys ?? []), "env:claude:opus"],
|
||||
}));
|
||||
registry.set(state.updatePreferencesAtom, (current) => ({
|
||||
favoriteModelKeys: [...(current.favoriteModelKeys ?? []), "other:codex:gpt-6"],
|
||||
}));
|
||||
|
||||
expect(Option.getOrThrow(AsyncResult.value(registry.get(state.preferencesAtom)))).toEqual({
|
||||
favoriteModelKeys: ["env:codex:gpt-5", "env:claude:opus", "other:codex:gpt-6"],
|
||||
});
|
||||
|
||||
unmountUpdate();
|
||||
unmountPreferences();
|
||||
registry.dispose();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to empty preferences when secure storage cannot be read", () =>
|
||||
Effect.gen(function* () {
|
||||
const state = makePreferencesState({
|
||||
|
||||
@@ -15,6 +15,10 @@ interface OptimisticPreferences {
|
||||
readonly versions: Partial<Record<keyof Preferences, number>>;
|
||||
}
|
||||
|
||||
export type PreferencesUpdate =
|
||||
| Partial<Preferences>
|
||||
| ((current: Preferences) => Partial<Preferences>);
|
||||
|
||||
/**
|
||||
* Owns the device preference blob for the lifetime of the app registry.
|
||||
* Optimistic patches are kept separately so writes made while persistence is
|
||||
@@ -57,7 +61,15 @@ export function createMobilePreferencesState(runtime: Atom.AtomRuntime<MobilePre
|
||||
|
||||
const updatePreferencesAtom = runtime
|
||||
.fn(
|
||||
(patch: Partial<Preferences>, get) => {
|
||||
(update: PreferencesUpdate, get) => {
|
||||
const preferences = get(preferencesAtom);
|
||||
let patch: Partial<Preferences>;
|
||||
if (typeof update === "function") {
|
||||
if (!AsyncResult.isSuccess(preferences)) return Effect.void;
|
||||
patch = update(preferences.value);
|
||||
} else {
|
||||
patch = update;
|
||||
}
|
||||
const version = ++nextPatchVersion;
|
||||
const current = get(optimisticPatchAtom);
|
||||
const versions = { ...current.versions };
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
import type { ProjectGroupingSettings } from "@t3tools/client-runtime/state/project-grouping";
|
||||
import type { SidebarProjectGroupingMode } from "@t3tools/contracts";
|
||||
|
||||
import type { Preferences } from "../persistence/mobile-preferences";
|
||||
|
||||
export const DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS: ProjectGroupingSettings = {
|
||||
sidebarProjectGroupingMode: "repository",
|
||||
sidebarProjectGroupingOverrides: {},
|
||||
};
|
||||
|
||||
export function resolveMobileProjectGroupingSettings(
|
||||
preferences: Preferences,
|
||||
): ProjectGroupingSettings {
|
||||
return {
|
||||
sidebarProjectGroupingMode:
|
||||
preferences.projectGroupingMode ??
|
||||
(preferences.projectGroupingEnabled === false ? "separate" : "repository"),
|
||||
sidebarProjectGroupingOverrides: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Dual-writes the legacy boolean for one release so an OTA rollback to an
|
||||
* older mobile bundle preserves the user's grouping choice.
|
||||
*/
|
||||
export function mobileProjectGroupingModePatch(
|
||||
mode: SidebarProjectGroupingMode,
|
||||
): Partial<Preferences> {
|
||||
return {
|
||||
projectGroupingMode: mode,
|
||||
projectGroupingEnabled: mode !== "separate",
|
||||
};
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
mobileProjectGroupingModePatch,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "./project-grouping.logic";
|
||||
|
||||
describe("mobile project grouping preferences", () => {
|
||||
it("maps the legacy boolean while preferring the new mode", () => {
|
||||
expect(resolveMobileProjectGroupingSettings({}).sidebarProjectGroupingMode).toBe("repository");
|
||||
expect(
|
||||
resolveMobileProjectGroupingSettings({ projectGroupingEnabled: false })
|
||||
.sidebarProjectGroupingMode,
|
||||
).toBe("separate");
|
||||
expect(
|
||||
resolveMobileProjectGroupingSettings({
|
||||
projectGroupingEnabled: false,
|
||||
projectGroupingMode: "repository_path",
|
||||
}).sidebarProjectGroupingMode,
|
||||
).toBe("repository_path");
|
||||
});
|
||||
|
||||
it("dual-writes the legacy boolean for rollback compatibility", () => {
|
||||
expect(mobileProjectGroupingModePatch("separate")).toEqual({
|
||||
projectGroupingMode: "separate",
|
||||
projectGroupingEnabled: false,
|
||||
});
|
||||
expect(mobileProjectGroupingModePatch("repository_path")).toEqual({
|
||||
projectGroupingMode: "repository_path",
|
||||
projectGroupingEnabled: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
|
||||
import { mobilePreferencesAtom } from "./preferences";
|
||||
import {
|
||||
DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS,
|
||||
resolveMobileProjectGroupingSettings,
|
||||
} from "./project-grouping.logic";
|
||||
|
||||
export * from "./project-grouping.logic";
|
||||
|
||||
export function useMobileProjectGroupingSettings() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
return AsyncResult.isSuccess(preferencesResult)
|
||||
? resolveMobileProjectGroupingSettings(preferencesResult.value)
|
||||
: DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS;
|
||||
}
|
||||
@@ -168,6 +168,7 @@ export function useSelectedThreadRequests() {
|
||||
|
||||
return {
|
||||
activePendingApproval,
|
||||
activePendingApprovalCount: activePendingApprovals.length,
|
||||
activePendingUserInput,
|
||||
activePendingUserInputDrafts,
|
||||
activePendingUserInputAnswers,
|
||||
|
||||
@@ -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>;
|
||||
@@ -50,14 +50,10 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityRe
|
||||
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,
|
||||
@@ -221,8 +217,6 @@ export interface OrchestrationIntegrationHarness {
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
};
|
||||
readonly drainProviderRuntime: Effect.Effect<void>;
|
||||
readonly drainCheckpointReactor: Effect.Effect<void>;
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
@@ -311,9 +305,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusTest,
|
||||
).pipe(
|
||||
Layer.provideMerge(ThreadBackgroundLiveness.layer),
|
||||
Layer.provideMerge(ThreadPlanProgress.layer),
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -400,13 +391,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerRuntimeIngestion = yield* tryRuntimePromise(
|
||||
"load ProviderRuntimeIngestion service",
|
||||
() => runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointReactor = yield* tryRuntimePromise("load CheckpointReactor service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
@@ -571,8 +555,6 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
waitForReceipt,
|
||||
drainProviderRuntime: providerRuntimeIngestion.drain,
|
||||
drainCheckpointReactor: checkpointReactor.drain,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -225,9 +226,9 @@ function missingSessionEffect(
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
let eventCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
@@ -241,10 +242,18 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
const nextEventId = (threadId: ThreadId) => {
|
||||
eventCount += 1;
|
||||
return EventId.make(`test-provider:${provider}:${threadId}:${eventCount}`);
|
||||
};
|
||||
const randomUUIDv4 = (threadId: ThreadId) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "crypto/randomUUIDv4",
|
||||
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -313,7 +322,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: nextEventId(input.threadId),
|
||||
eventId: yield* randomUUIDv4(input.threadId),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
};
|
||||
@@ -370,7 +379,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: nextEventId(input.threadId),
|
||||
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -1,212 +0,0 @@
|
||||
import type { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
HttpTransferMeasurement,
|
||||
WebSocketTransferTotals,
|
||||
} from "./NetworkTransferMeasurement.integration.ts";
|
||||
import {
|
||||
TRANSFER_HISTORY_MCP_RESULT_BYTES,
|
||||
TRANSFER_HISTORY_TOOLS_PER_TURN,
|
||||
TRANSFER_HISTORY_TURN_COUNT,
|
||||
TRANSFER_MEASURED_MCP_RESULT_BYTES,
|
||||
TRANSFER_MEASURED_TOOLS,
|
||||
} from "./fixtures/transferBudget.ts";
|
||||
|
||||
export interface TransferBudgetRun {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadSnapshot: HttpTransferMeasurement;
|
||||
readonly measuredTurnWebSocket: WebSocketTransferTotals;
|
||||
}
|
||||
|
||||
interface ProviderTransferBudget {
|
||||
readonly totalWireBytes: number;
|
||||
readonly threadSnapshotWireBytes: number;
|
||||
readonly measuredTurnWebSocketWireBytes: number;
|
||||
readonly measuredTurnWebSocketDecodedBytes: number;
|
||||
readonly measuredTurnWebSocketMessages: number;
|
||||
}
|
||||
|
||||
// These caps leave roughly 30% headroom above the client projection of the
|
||||
// deterministic 9 MB retained-result fixture. Full MCP results stay in
|
||||
// persistence, so accidentally shipping them again exceeds these caps by
|
||||
// orders of magnitude. The CI report preserves exact values for review.
|
||||
const TRANSFER_BUDGET = {
|
||||
totalWireBytes: 15_500,
|
||||
threadSnapshotWireBytes: 7_500,
|
||||
measuredTurnWebSocketWireBytes: 8_000,
|
||||
measuredTurnWebSocketDecodedBytes: 68_000,
|
||||
measuredTurnWebSocketMessages: 21,
|
||||
} satisfies ProviderTransferBudget;
|
||||
|
||||
export const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
|
||||
codex: TRANSFER_BUDGET,
|
||||
claudeAgent: TRANSFER_BUDGET,
|
||||
};
|
||||
|
||||
function totalWireBytes(run: TransferBudgetRun): number {
|
||||
return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
|
||||
}
|
||||
|
||||
function observedTransfer(run: TransferBudgetRun) {
|
||||
return {
|
||||
totalWireBytes: totalWireBytes(run),
|
||||
threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
|
||||
threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
|
||||
measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
|
||||
measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
|
||||
measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
|
||||
};
|
||||
}
|
||||
|
||||
/** Machine-readable input for the trusted PR comment publisher. */
|
||||
export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
|
||||
const providers = Object.fromEntries(
|
||||
runs.flatMap((run) => {
|
||||
const ceiling = TRANSFER_BUDGETS[run.provider];
|
||||
return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
|
||||
}),
|
||||
);
|
||||
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: TRANSFER_HISTORY_TURN_COUNT,
|
||||
historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
|
||||
historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
|
||||
measuredCommandTools: TRANSFER_MEASURED_TOOLS,
|
||||
measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
|
||||
},
|
||||
providers,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1_024) return `${bytes} B`;
|
||||
if (bytes >= 1_024 * 1_024) {
|
||||
return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
|
||||
}
|
||||
return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
|
||||
}
|
||||
|
||||
function row(
|
||||
provider: ProviderDriverKind,
|
||||
phase: string,
|
||||
metric: string,
|
||||
observed: number,
|
||||
maximum: number,
|
||||
format: (value: number) => string = formatBytes,
|
||||
): string {
|
||||
const status = observed <= maximum ? "PASS" : "FAIL";
|
||||
return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
|
||||
}
|
||||
|
||||
export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
|
||||
const violations: string[] = [];
|
||||
for (const run of runs) {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) {
|
||||
violations.push(`${run.provider}: no transfer budget is configured`);
|
||||
continue;
|
||||
}
|
||||
const checks = [
|
||||
["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
|
||||
["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
|
||||
[
|
||||
"measured-turn WebSocket wire bytes",
|
||||
run.measuredTurnWebSocket.wireBytes,
|
||||
budget.measuredTurnWebSocketWireBytes,
|
||||
],
|
||||
[
|
||||
"measured-turn WebSocket decoded bytes",
|
||||
run.measuredTurnWebSocket.decodedBytes,
|
||||
budget.measuredTurnWebSocketDecodedBytes,
|
||||
],
|
||||
[
|
||||
"measured-turn WebSocket messages",
|
||||
run.measuredTurnWebSocket.messages,
|
||||
budget.measuredTurnWebSocketMessages,
|
||||
],
|
||||
] as const;
|
||||
for (const [metric, observed, maximum] of checks) {
|
||||
if (observed > maximum) {
|
||||
violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
|
||||
const lines = [
|
||||
"# T3 Code thread transfer budget",
|
||||
"",
|
||||
"Wire values are thread data bytes read from local HTTP and WebSocket sockets. HTTP includes response headers; WebSocket measurement starts after the resumed thread subscription synchronizes. TCP/IP, TLS framing, and the WebSocket upgrade are excluded. WebSocket permessage-deflate is negotiated.",
|
||||
`Scenario: ${TRANSFER_HISTORY_TURN_COUNT} historical turns with ${TRANSFER_HISTORY_TOOLS_PER_TURN} command tools and one retained ${formatBytes(TRANSFER_HISTORY_MCP_RESULT_BYTES)} MCP result each, followed by one measured turn with ${TRANSFER_MEASURED_TOOLS} command tools and a retained ${formatBytes(TRANSFER_MEASURED_MCP_RESULT_BYTES)} MCP result. Payload sizes are calibrated from heavy local Codex and Claude histories and contain no user data.`,
|
||||
"",
|
||||
"| Provider | Total thread wire | Budget | Result |",
|
||||
"| --- | ---: | ---: | --- |",
|
||||
...runs.flatMap((run) => {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) return [];
|
||||
const observed = observedTransfer(run).totalWireBytes;
|
||||
return [
|
||||
`| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
|
||||
];
|
||||
}),
|
||||
"",
|
||||
"## Detailed measurements",
|
||||
"",
|
||||
"| Provider | Phase | Metric | Observed | Budget | Result |",
|
||||
"| --- | --- | --- | ---: | ---: | --- |",
|
||||
];
|
||||
|
||||
for (const run of runs) {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) continue;
|
||||
lines.push(
|
||||
row(
|
||||
run.provider,
|
||||
"thread snapshot",
|
||||
"HTTP wire",
|
||||
run.threadSnapshot.wireBytes,
|
||||
budget.threadSnapshotWireBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket wire",
|
||||
run.measuredTurnWebSocket.wireBytes,
|
||||
budget.measuredTurnWebSocketWireBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket decoded",
|
||||
run.measuredTurnWebSocket.decodedBytes,
|
||||
budget.measuredTurnWebSocketDecodedBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket messages",
|
||||
run.measuredTurnWebSocket.messages,
|
||||
budget.measuredTurnWebSocketMessages,
|
||||
String,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
lines.push("", "## Compression diagnostics", "");
|
||||
for (const run of runs) {
|
||||
lines.push(
|
||||
`- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
|
||||
);
|
||||
}
|
||||
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
defaultInstanceIdForDriver,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type { TurnProcessingQuiescedReceipt } from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import type { OrchestrationIntegrationHarness } from "./OrchestrationEngineHarness.integration.ts";
|
||||
import {
|
||||
expectedRecordedAssistantText,
|
||||
makeRecordedTransferTurn,
|
||||
TRANSFER_HISTORY_TURN_COUNT,
|
||||
} from "./fixtures/transferBudget.ts";
|
||||
|
||||
export const TRANSFER_PROJECT_ID = ProjectId.make("transfer-budget-project");
|
||||
export const TRANSFER_THREAD_ID = ThreadId.make("transfer-budget-thread");
|
||||
export const TRANSFER_MEASURED_TURN_INDEX = TRANSFER_HISTORY_TURN_COUNT;
|
||||
|
||||
export function transferModelSelection(provider: ProviderDriverKind) {
|
||||
return {
|
||||
instanceId: defaultInstanceIdForDriver(provider),
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL,
|
||||
};
|
||||
}
|
||||
|
||||
function turnTimestamp(turnIndex: number): string {
|
||||
return `2026-06-01T00:${String(turnIndex).padStart(2, "0")}:00.000Z`;
|
||||
}
|
||||
|
||||
export const TRANSFER_MEASURED_TURN_CREATED_AT = turnTimestamp(TRANSFER_MEASURED_TURN_INDEX);
|
||||
|
||||
const waitForTurnQuiesced = Effect.fn("TransferBudget.waitForTurnQuiesced")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
checkpointTurnCount: number,
|
||||
) {
|
||||
const receipt = yield* harness.waitForReceipt(
|
||||
(receipt): receipt is TurnProcessingQuiescedReceipt =>
|
||||
receipt.type === "turn.processing.quiesced" &&
|
||||
receipt.threadId === TRANSFER_THREAD_ID &&
|
||||
receipt.checkpointTurnCount === checkpointTurnCount,
|
||||
);
|
||||
yield* harness.drainProviderRuntime;
|
||||
yield* harness.drainCheckpointReactor;
|
||||
return receipt;
|
||||
});
|
||||
|
||||
export const seedTransferBudgetHistory = Effect.fn("TransferBudget.seedHistory")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
provider: ProviderDriverKind,
|
||||
) {
|
||||
if (!harness.adapterHarness) {
|
||||
return yield* Effect.die(new Error("Transfer budget history requires the replay adapter."));
|
||||
}
|
||||
|
||||
const modelSelection = transferModelSelection(provider);
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(`transfer:${provider}:project-create`),
|
||||
projectId: TRANSFER_PROJECT_ID,
|
||||
title: "Transfer Budget Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: turnTimestamp(0),
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(`transfer:${provider}:thread-create`),
|
||||
threadId: TRANSFER_THREAD_ID,
|
||||
projectId: TRANSFER_PROJECT_ID,
|
||||
title: `${provider} transfer history`,
|
||||
modelSelection,
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
branch: "main",
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt: turnTimestamp(0),
|
||||
});
|
||||
|
||||
for (let turnIndex = 0; turnIndex < TRANSFER_HISTORY_TURN_COUNT; turnIndex += 1) {
|
||||
const response = makeRecordedTransferTurn(provider, turnIndex);
|
||||
if (turnIndex === 0) {
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession(response);
|
||||
} else {
|
||||
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
|
||||
}
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(`transfer:${provider}:turn:${turnIndex + 1}`),
|
||||
threadId: TRANSFER_THREAD_ID,
|
||||
message: {
|
||||
messageId: MessageId.make(`transfer-user-${turnIndex + 1}`),
|
||||
role: "user",
|
||||
text: `Inspect transfer behavior for historical turn ${turnIndex + 1}.`,
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection,
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: turnTimestamp(turnIndex),
|
||||
});
|
||||
yield* waitForTurnQuiesced(harness, turnIndex + 1);
|
||||
}
|
||||
});
|
||||
|
||||
export const queueMeasuredTransferTurn = Effect.fn("TransferBudget.queueMeasuredTurn")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
provider: ProviderDriverKind,
|
||||
) {
|
||||
if (!harness.adapterHarness) {
|
||||
return yield* Effect.die(new Error("Transfer budget measurement requires the replay adapter."));
|
||||
}
|
||||
const response = makeRecordedTransferTurn(provider, TRANSFER_MEASURED_TURN_INDEX);
|
||||
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
|
||||
});
|
||||
|
||||
export function expectedMeasuredAssistantText(provider: ProviderDriverKind): string {
|
||||
return expectedRecordedAssistantText(provider, TRANSFER_MEASURED_TURN_INDEX);
|
||||
}
|
||||
|
||||
export { TRANSFER_HISTORY_TURN_COUNT, waitForTurnQuiesced };
|
||||
@@ -1,372 +0,0 @@
|
||||
import { EventId, ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
FixtureProviderRuntimeEvent,
|
||||
TestTurnResponse,
|
||||
} from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const FIXTURE_THREAD_ID = "transfer-budget-thread";
|
||||
const FIXTURE_TURN_ID = "transfer-budget-turn";
|
||||
|
||||
export const TRANSFER_HISTORY_TURN_COUNT = 10;
|
||||
export const TRANSFER_HISTORY_TOOLS_PER_TURN = 5;
|
||||
export const TRANSFER_MEASURED_TOOLS = 20;
|
||||
export const TRANSFER_HISTORY_MCP_RESULT_BYTES = 900_000;
|
||||
export const TRANSFER_MEASURED_MCP_RESULT_BYTES = 1_100_000;
|
||||
|
||||
const sourceModules = [
|
||||
"connection/session.ts",
|
||||
"connection/supervisor.ts",
|
||||
"rpc/client.ts",
|
||||
"rpc/protocol.ts",
|
||||
"state/threads.ts",
|
||||
"state/threadReducer.ts",
|
||||
"state/threadSnapshotHttp.ts",
|
||||
"orchestration/http.ts",
|
||||
"orchestration/Normalizer.ts",
|
||||
"orchestration/ActivityPayloadProjection.ts",
|
||||
"provider/ProviderService.ts",
|
||||
"provider/ProviderRuntimeIngestion.ts",
|
||||
"persistence/ProjectionSnapshotQuery.ts",
|
||||
"persistence/OrchestrationEventStore.ts",
|
||||
"checkpointing/CheckpointStore.ts",
|
||||
"checkpointing/CheckpointDiffQuery.ts",
|
||||
"server.ts",
|
||||
] as const;
|
||||
|
||||
function fixtureTimestamp(turnIndex: number, eventIndex: number): string {
|
||||
const minute = String(turnIndex).padStart(2, "0");
|
||||
const second = String(Math.floor(eventIndex / 1_000)).padStart(2, "0");
|
||||
const millisecond = String(eventIndex % 1_000).padStart(3, "0");
|
||||
return `2026-06-01T00:${minute}:${second}.${millisecond}Z`;
|
||||
}
|
||||
|
||||
function mix(value: number): number {
|
||||
let mixed = value | 0;
|
||||
mixed ^= mixed >>> 16;
|
||||
mixed = Math.imul(mixed, 0x7feb352d);
|
||||
mixed ^= mixed >>> 15;
|
||||
mixed = Math.imul(mixed, 0x846ca68b);
|
||||
mixed ^= mixed >>> 16;
|
||||
return mixed >>> 0;
|
||||
}
|
||||
|
||||
function digest(seed: number): string {
|
||||
return [0, 1, 2, 3]
|
||||
.map((offset) =>
|
||||
mix(seed + offset * 0x9e3779b9)
|
||||
.toString(16)
|
||||
.padStart(8, "0"),
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Produces safe, deterministic output with enough entropy to exercise gzip. */
|
||||
function diagnosticOutput(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly turnIndex: number;
|
||||
readonly toolIndex: number;
|
||||
readonly targetBytes: number;
|
||||
}): string {
|
||||
const chunks: string[] = [];
|
||||
const providerSeed = input.provider === "codex" ? 0x43_4f_44_45 : 0x43_4c_41_55;
|
||||
let length = 0;
|
||||
let lineIndex = 0;
|
||||
|
||||
while (length < input.targetBytes) {
|
||||
const modulePath = sourceModules[(input.toolIndex + lineIndex) % sourceModules.length];
|
||||
const seed =
|
||||
providerSeed + input.turnIndex * 100_003 + input.toolIndex * 10_007 + lineIndex * 101;
|
||||
const line =
|
||||
`${String(lineIndex + 1).padStart(6, "0")} ${modulePath} ` +
|
||||
`operation=project-transfer-${input.turnIndex + 1}-${input.toolIndex + 1} ` +
|
||||
`cursor=${mix(seed)} digest=${digest(seed)} status=completed\n`;
|
||||
chunks.push(line);
|
||||
length += line.length;
|
||||
lineIndex += 1;
|
||||
}
|
||||
|
||||
return chunks.join("").slice(0, input.targetBytes);
|
||||
}
|
||||
|
||||
function assistantChunks(provider: ProviderDriverKind, turnIndex: number): ReadonlyArray<string> {
|
||||
const providerName = provider === "codex" ? "Codex" : "Claude";
|
||||
const paragraphs: string[] = [
|
||||
`I traced the ${providerName} request through the environment connection and orchestration layers. `,
|
||||
];
|
||||
let paragraphIndex = 0;
|
||||
while (paragraphs.join("").length < 4_096) {
|
||||
const modulePath = sourceModules[paragraphIndex % sourceModules.length];
|
||||
paragraphs.push(
|
||||
`Pass ${paragraphIndex + 1} reviewed ${modulePath} for turn ${turnIndex + 1}. ` +
|
||||
"The shell cursor stayed monotonic, the thread snapshot remained resumable, and the client received only incremental events. ",
|
||||
);
|
||||
paragraphIndex += 1;
|
||||
}
|
||||
const text = paragraphs.join("").slice(0, 4_096);
|
||||
return Array.from({ length: Math.ceil(text.length / 256) }, (_, index) =>
|
||||
text.slice(index * 256, (index + 1) * 256),
|
||||
);
|
||||
}
|
||||
|
||||
export function expectedRecordedAssistantText(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
): string {
|
||||
return assistantChunks(provider, turnIndex).join("");
|
||||
}
|
||||
|
||||
function unifiedDiff(provider: ProviderDriverKind, turnIndex: number): string {
|
||||
const lines = sourceModules
|
||||
.slice(0, 8)
|
||||
.flatMap((modulePath, index) => [
|
||||
`diff --git a/${modulePath} b/${modulePath}`,
|
||||
`--- a/${modulePath}`,
|
||||
`+++ b/${modulePath}`,
|
||||
`@@ -${index + 1},2 +${index + 1},3 @@`,
|
||||
` const provider = "${provider}";`,
|
||||
`+const transferTurn = ${turnIndex + 1};`,
|
||||
`+const transferSample = ${1_500 + index * 97};`,
|
||||
]);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function baseEvent(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
eventIndex: number,
|
||||
): Pick<FixtureProviderRuntimeEvent, "eventId" | "provider" | "createdAt" | "threadId"> {
|
||||
return {
|
||||
eventId: EventId.make(`recorded:${provider}:${turnIndex}:${eventIndex}`),
|
||||
provider,
|
||||
createdAt: fixtureTimestamp(turnIndex, eventIndex),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthetic canonical events calibrated from heavy local Codex and Claude
|
||||
* threads. Ten historical turns produce 9 MB of retained MCP results without
|
||||
* committing user content. Command output is intentionally modest because the
|
||||
* client projection strips it.
|
||||
*/
|
||||
export function makeRecordedTransferTurn(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
): TestTurnResponse {
|
||||
const measuredTurn = turnIndex >= TRANSFER_HISTORY_TURN_COUNT;
|
||||
const toolCount = measuredTurn ? TRANSFER_MEASURED_TOOLS : TRANSFER_HISTORY_TOOLS_PER_TURN;
|
||||
const turnId = `${FIXTURE_TURN_ID}-${turnIndex + 1}`;
|
||||
const events: FixtureProviderRuntimeEvent[] = [];
|
||||
let eventIndex = 0;
|
||||
|
||||
events.push({
|
||||
type: "turn.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
model: provider === "codex" ? "gpt-5.4" : "claude-opus-4-1",
|
||||
effort: provider === "codex" ? "high" : "default",
|
||||
},
|
||||
});
|
||||
|
||||
for (let toolIndex = 0; toolIndex < toolCount; toolIndex += 1) {
|
||||
const itemId = `tool-${turnIndex + 1}-${toolIndex + 1}`;
|
||||
const command =
|
||||
provider === "codex"
|
||||
? `vp test transfer-budget-${toolIndex + 1}`
|
||||
: `review transfer budget ${toolIndex + 1}`;
|
||||
events.push(
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "inProgress",
|
||||
title: `Inspect transfer path ${toolIndex + 1}`,
|
||||
detail: "Inspecting the HTTP snapshot and WebSocket projection boundaries.",
|
||||
data: {
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
startedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
item: {
|
||||
id: itemId,
|
||||
type: "commandExecution",
|
||||
command,
|
||||
cwd: "/workspace/transfer-budget",
|
||||
processId: String(toolIndex + 1),
|
||||
status: "inProgress",
|
||||
commandActions: [],
|
||||
aggregatedOutput: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: `Inspected transfer path ${toolIndex + 1}`,
|
||||
detail: "Collected a deterministic multi-module transfer diagnostic.",
|
||||
data: {
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
completedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
item: {
|
||||
id: itemId,
|
||||
type: "commandExecution",
|
||||
command,
|
||||
cwd: "/workspace/transfer-budget",
|
||||
processId: String(toolIndex + 1),
|
||||
status: "completed",
|
||||
commandActions: [],
|
||||
aggregatedOutput: diagnosticOutput({
|
||||
provider,
|
||||
turnIndex,
|
||||
toolIndex,
|
||||
targetBytes: 1_000,
|
||||
}),
|
||||
exitCode: 0,
|
||||
durationMs: 500 + toolIndex,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const mcpItemId = `mcp-${turnIndex + 1}`;
|
||||
const mcpResultBytes = measuredTurn
|
||||
? TRANSFER_MEASURED_MCP_RESULT_BYTES
|
||||
: TRANSFER_HISTORY_MCP_RESULT_BYTES;
|
||||
events.push(
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: mcpItemId,
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
status: "inProgress",
|
||||
title: "fixture-history · inspect_transfer_log",
|
||||
detail: "Reading a retained diagnostic result from the provider history.",
|
||||
data: {
|
||||
startedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: mcpItemId,
|
||||
server: "fixture-history",
|
||||
tool: "inspect_transfer_log",
|
||||
arguments: { turn: turnIndex + 1 },
|
||||
status: "inProgress",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: mcpItemId,
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
title: "fixture-history · inspect_transfer_log",
|
||||
detail: "Retained a deterministic diagnostic result in the thread history.",
|
||||
data: {
|
||||
completedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: mcpItemId,
|
||||
server: "fixture-history",
|
||||
tool: "inspect_transfer_log",
|
||||
arguments: { turn: turnIndex + 1 },
|
||||
durationMs: 1_000 + turnIndex,
|
||||
error: null,
|
||||
result: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: diagnosticOutput({
|
||||
provider,
|
||||
turnIndex,
|
||||
toolIndex: toolCount,
|
||||
targetBytes: mcpResultBytes,
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const chunks = assistantChunks(provider, turnIndex);
|
||||
for (const [contentIndex, delta] of chunks.entries()) {
|
||||
events.push({
|
||||
type: "content.delta",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: `assistant-${turnIndex + 1}`,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta,
|
||||
contentIndex,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
events.push(
|
||||
{
|
||||
type: "thread.token-usage.updated",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 18_000 + turnIndex * 1_900,
|
||||
maxTokens: 200_000,
|
||||
inputTokens: 15_000 + turnIndex * 1_700,
|
||||
cachedInputTokens: 9_000 + turnIndex * 1_100,
|
||||
outputTokens: 3_000 + turnIndex * 200,
|
||||
toolUses: toolCount,
|
||||
durationMs: 4_000 + turnIndex * 250,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.diff.updated",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
unifiedDiff: unifiedDiff(provider, turnIndex),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex),
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
stopReason: "end_turn",
|
||||
usage: {
|
||||
inputTokens: 15_000 + turnIndex * 1_700,
|
||||
outputTokens: 3_000 + turnIndex * 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return { events };
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
@@ -55,58 +54,35 @@ interface IntegrationFixture {
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
interface RecordedAnalyticsEvent {
|
||||
readonly event: string;
|
||||
readonly properties: Readonly<Record<string, unknown>> | undefined;
|
||||
}
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
/**
|
||||
* Analytics layer that keeps captured events in memory so tests can assert on
|
||||
* telemetry payloads. `AnalyticsService.layerTest` discards them.
|
||||
*/
|
||||
const makeRecordingAnalytics = Effect.gen(function* () {
|
||||
const recorded = yield* Ref.make<ReadonlyArray<RecordedAnalyticsEvent>>([]);
|
||||
const layer = Layer.succeed(
|
||||
AnalyticsService,
|
||||
AnalyticsService.of({
|
||||
record: (event, properties) =>
|
||||
Ref.update(recorded, (current) => [...current, { event, properties }]),
|
||||
flush: Effect.void,
|
||||
}),
|
||||
);
|
||||
return { layer, get: Ref.get(recorded) } as const;
|
||||
});
|
||||
|
||||
const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<AnalyticsService> }) =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
options?.analytics ?? AnalyticsService.layerTest,
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
harness,
|
||||
layer,
|
||||
} satisfies IntegrationFixture;
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
harness,
|
||||
layer,
|
||||
} satisfies IntegrationFixture;
|
||||
});
|
||||
|
||||
const collectEventsDuring = <A, E, R>(
|
||||
stream: Stream.Stream<ProviderRuntimeEvent>,
|
||||
count: number,
|
||||
@@ -150,7 +126,7 @@ const runTurn = (input: {
|
||||
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -185,7 +161,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -222,7 +198,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -274,7 +250,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -326,59 +302,3 @@ it.live("rolls back provider conversation state only", () =>
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("reports runtime mode per turn and on mode transitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const analytics = yield* makeRecordingAnalytics;
|
||||
const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer });
|
||||
const threadId = ThreadId.make("thread-integration-runtime-mode");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const startSession = (runtimeMode: "approval-required" | "full-access") =>
|
||||
provider.startSession(threadId, {
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode,
|
||||
});
|
||||
|
||||
yield* startSession("approval-required");
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId,
|
||||
userText: "supervised turn",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
// Toggling the mode restarts the session, which is the only place the
|
||||
// transition is observable.
|
||||
yield* startSession("full-access");
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId,
|
||||
userText: "full access turn",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
const recorded = yield* analytics.get;
|
||||
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter((entry) => entry.event === "provider.turn.sent")
|
||||
.map((entry) => entry.properties?.runtimeMode),
|
||||
["approval-required", "full-access"],
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter((entry) => entry.event === "provider.runtime_mode.changed")
|
||||
.map((entry) => [entry.properties?.from, entry.properties?.to]),
|
||||
[["approval-required", "full-access"]],
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.32",
|
||||
"version": "0.0.31",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -22,7 +22,6 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
||||
*/
|
||||
export const RPC_REQUIRED_SCOPES = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
|
||||
|
||||
@@ -31,7 +31,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
|
||||
});
|
||||
|
||||
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
|
||||
expect(unit).toContain("KillMode=mixed");
|
||||
expect(unit).toContain("KillMode=control-group");
|
||||
expect(unit).not.toContain("versions/1.2.3");
|
||||
});
|
||||
|
||||
|
||||
@@ -64,9 +64,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
|
||||
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
|
||||
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
|
||||
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
|
||||
// Let the launcher mark an explicit stop before it signals the server.
|
||||
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
|
||||
"KillMode=mixed",
|
||||
"KillMode=control-group",
|
||||
"Restart=always",
|
||||
"RestartSec=5",
|
||||
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Tracer from "effect/Tracer";
|
||||
import {
|
||||
@@ -18,14 +15,6 @@ import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import * as ServerConfigModule from "../config.ts";
|
||||
import { writeServiceState } from "../serviceLauncher.ts";
|
||||
import {
|
||||
SERVICE_LAUNCHER_PROTOCOL,
|
||||
SERVICE_STATE_FILE,
|
||||
SERVICE_STOP_MARKER_FILE,
|
||||
type ServiceUpdateRecord,
|
||||
} from "./serviceProtocol.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
|
||||
import * as CliTokenManager from "./CliTokenManager.ts";
|
||||
@@ -35,7 +24,6 @@ import {
|
||||
consumeCloudReplayGuards,
|
||||
isSupportedLinkProviderKind,
|
||||
linkProofScopes,
|
||||
pendingServiceUpdateExists,
|
||||
reconcileDesiredCloudLink,
|
||||
releaseManagedTunnelOnShutdown,
|
||||
} from "./http.ts";
|
||||
@@ -268,23 +256,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
readonly respond?: () => Response;
|
||||
}
|
||||
|
||||
// Writes the launcher's durable state file into this test's baseDir with
|
||||
// the launcher's own writer; the release reads it to detect an in-flight
|
||||
// update handoff.
|
||||
const writeLauncherState = (update: ServiceUpdateRecord) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfigModule.ServerConfig;
|
||||
const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
|
||||
yield* Effect.promise(() =>
|
||||
writeServiceState(statePath, {
|
||||
protocol: SERVICE_LAUNCHER_PROTOCOL,
|
||||
activeVersion: "0.0.30",
|
||||
update,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const provideReleaseHarness =
|
||||
(harness: ReleaseHarness) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
@@ -335,14 +306,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
}),
|
||||
),
|
||||
),
|
||||
// The release consults the launcher state file under the configured
|
||||
// baseDir, so every harness run gets a scoped temp baseDir.
|
||||
Effect.provide(
|
||||
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
);
|
||||
|
||||
// The persisted state of a CLI-managed link whose tunnel is releasable.
|
||||
@@ -427,84 +390,6 @@ describe("releaseManagedTunnelOnShutdown", () => {
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending",
|
||||
});
|
||||
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
// The launcher restarts a server immediately, so the tunnel is not
|
||||
// orphaned; keeping it avoids the hostname route re-propagation that
|
||||
// dominates update downtime. The stored config must survive so the
|
||||
// next boot respawns the connector against the same tunnel.
|
||||
expect(released).toBe(false);
|
||||
expect(applyConfigCalls).toEqual([]);
|
||||
expect(requests).toEqual([]);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("still releases a pending update when the launcher is stopping", () => {
|
||||
// `t3 service uninstall` or `systemctl stop` during the pending window:
|
||||
// the launcher writes its stop marker before signalling the child, so no
|
||||
// replacement server is coming and the tunnel must not be kept.
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
dbPath: "/tmp/state.sqlite",
|
||||
status: "pending",
|
||||
});
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const config = yield* ServerConfigModule.ServerConfig;
|
||||
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
|
||||
|
||||
expect(yield* pendingServiceUpdateExists).toBe(true);
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
expect(released).toBe(true);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("still releases when the recorded update already settled", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* writeLauncherState({
|
||||
id: "update-1",
|
||||
fromVersion: "0.0.30",
|
||||
targetVersion: "0.0.31",
|
||||
status: "committed",
|
||||
});
|
||||
|
||||
const released = yield* releaseManagedTunnelOnShutdown();
|
||||
|
||||
expect(released).toBe(true);
|
||||
expect(requests).toHaveLength(1);
|
||||
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
|
||||
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
|
||||
});
|
||||
|
||||
it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
|
||||
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
|
||||
const applyConfigCalls: Array<unknown> = [];
|
||||
|
||||
@@ -46,9 +46,7 @@ import * as DateTime from "effect/DateTime";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as HttpEffect from "effect/unstable/http/HttpEffect";
|
||||
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
|
||||
@@ -58,14 +56,8 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
|
||||
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
|
||||
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
|
||||
import { requireEnvironmentScope } from "../auth/http.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
|
||||
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
|
||||
import {
|
||||
SERVICE_STATE_FILE,
|
||||
SERVICE_STOP_MARKER_FILE,
|
||||
serviceStateHasPendingUpdate,
|
||||
} from "./serviceProtocol.ts";
|
||||
import {
|
||||
CLOUD_ENDPOINT_RUNTIME_CONFIG,
|
||||
CLOUD_LINKED_USER_ID,
|
||||
@@ -635,37 +627,6 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
|
||||
},
|
||||
);
|
||||
|
||||
// The launcher owns this durable state, so read it directly both when a trial
|
||||
// decides whether it owns pre-activation cleanup and while a server tears down.
|
||||
export const pendingServiceUpdateExists = Effect.gen(function* () {
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runtimeDir = path.join(config.baseDir, "runtime");
|
||||
const stateText = yield* fs
|
||||
.readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
|
||||
.pipe(Effect.option);
|
||||
return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
|
||||
});
|
||||
|
||||
// A pending update alone is not proof a replacement server is coming: an
|
||||
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
|
||||
// the pending window also tears this server down. The launcher marks that case
|
||||
// just before it signals the child, so pending + no marker is the handoff.
|
||||
const pendingUpdateHandoffExists = Effect.gen(function* () {
|
||||
if (!(yield* pendingServiceUpdateExists)) {
|
||||
return false;
|
||||
}
|
||||
const config = yield* ServerConfig.ServerConfig;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const runtimeDir = path.join(config.baseDir, "runtime");
|
||||
const stopping = yield* fs
|
||||
.exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
return !stopping;
|
||||
});
|
||||
|
||||
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
|
||||
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
|
||||
// relay keeps the link and its hostname reservation, and the next startup's
|
||||
@@ -688,19 +649,6 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
|
||||
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
|
||||
return false;
|
||||
}
|
||||
// A shutdown that hands off to a pending remote update is not the
|
||||
// environment going offline: the launcher immediately brings a server back
|
||||
// (the new version, or the old one after a rollback). Deleting the tunnel
|
||||
// here forces that server to provision a replacement UUID, and the public
|
||||
// hostname's route to the new tunnel takes 1-2 minutes to propagate — the
|
||||
// dominant cost of an update restart. Keep the tunnel instead: the next
|
||||
// boot respawns the connector from the stored config and is reachable as
|
||||
// soon as it connects, and the reconcile confirms the still-live tunnel
|
||||
// without replacing it.
|
||||
if (yield* pendingUpdateHandoffExists) {
|
||||
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
|
||||
return false;
|
||||
}
|
||||
const token = yield* dependencies.cliTokenManager.getExisting;
|
||||
if (Option.isNone(token)) {
|
||||
return false;
|
||||
|
||||
@@ -5,10 +5,6 @@ export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
|
||||
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
|
||||
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
|
||||
export const SERVICE_STATE_FILE = "service-state.json";
|
||||
/** Written by the launcher just before an explicit stop kills its child, so
|
||||
the child can tell "the service is going away" from "the launcher is about
|
||||
to start my replacement" while a pending update is recorded. */
|
||||
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
|
||||
|
||||
export interface PendingServiceUpdate {
|
||||
readonly id: string;
|
||||
|
||||
@@ -146,7 +146,6 @@ export const make = Effect.gen(function* () {
|
||||
threadSettlement: true,
|
||||
threadSnooze: true,
|
||||
threadPinning: true,
|
||||
threadPinReorder: true,
|
||||
threadTitleRegeneration: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
|
||||
|
||||
@@ -69,10 +69,6 @@ export class GitWorkflowService extends Context.Service<
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<void, GitCommandError>;
|
||||
readonly remoteExists: (input: {
|
||||
readonly cwd: string;
|
||||
readonly remoteName: string;
|
||||
}) => Effect.Effect<boolean, GitCommandError>;
|
||||
readonly resolveRemoteTrackingCommit: (input: {
|
||||
readonly cwd: string;
|
||||
readonly refName: string;
|
||||
@@ -307,10 +303,6 @@ export const make = Effect.gen(function* () {
|
||||
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
|
||||
Effect.andThen(git.fetchRemote(input)),
|
||||
),
|
||||
remoteExists: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
|
||||
Effect.andThen(git.remoteExists(input)),
|
||||
),
|
||||
resolveRemoteTrackingCommit: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
|
||||
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
|
||||
|
||||
@@ -198,7 +198,6 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
|
||||
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
|
||||
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
|
||||
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
|
||||
assert.equal(defaultsByCommand.get("themeEditor.toggle"), "mod+alt+shift+t");
|
||||
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
|
||||
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
|
||||
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
|
||||
|
||||
function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: "activity-1",
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: "Tool",
|
||||
payload,
|
||||
turnId: null,
|
||||
createdAt: "2026-08-01T10:00:00.000Z",
|
||||
} as unknown as OrchestrationThreadActivity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wire-survival regression: the slimming pass rewrites payload.data but must
|
||||
* never strip the top-level per-agent fields the subagent fold depends on.
|
||||
* If slimming ever moves to an allowlist over the whole payload, these
|
||||
* assertions are the tripwire.
|
||||
*/
|
||||
describe("projectActivityPayload agent-field survival", () => {
|
||||
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "command_execution",
|
||||
agentId: "task-123",
|
||||
parentToolUseId: "toolu_abc",
|
||||
data: {
|
||||
toolName: "Bash",
|
||||
input: { command: "ls" },
|
||||
command: "ls",
|
||||
rawOutput: { content: "x".repeat(10) },
|
||||
somethingClientNeverReads: { big: "blob" },
|
||||
},
|
||||
}),
|
||||
);
|
||||
const payload = projected.payload as Record<string, unknown>;
|
||||
expect(payload.agentId).toBe("task-123");
|
||||
expect(payload.parentToolUseId).toBe("toolu_abc");
|
||||
// Slimming itself still applies to data.
|
||||
const data = payload.data as Record<string, unknown>;
|
||||
expect(data.somethingClientNeverReads).toBeUndefined();
|
||||
});
|
||||
|
||||
it("slims Codex-shaped mcp_tool_call items to rendered fields plus a result summary", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "mcp_tool_call",
|
||||
data: {
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: "item-1",
|
||||
tool: "fetch_pr",
|
||||
server: "github",
|
||||
status: "completed",
|
||||
arguments: { pr: 42 },
|
||||
durationMs: 1200,
|
||||
result: {
|
||||
content: [{ type: "text", text: `PR body line one\n${"x".repeat(5000)}` }],
|
||||
structuredContent: { huge: "y".repeat(5000) },
|
||||
},
|
||||
_meta: { internal: true },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
|
||||
const item = data.item as Record<string, unknown>;
|
||||
expect(item.tool).toBe("fetch_pr");
|
||||
expect(item.server).toBe("github");
|
||||
expect(item.arguments).toEqual({ pr: 42 });
|
||||
expect(item._meta).toBeUndefined();
|
||||
expect(item.result).toEqual({ content: "PR body line one" });
|
||||
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it("slims Claude-shaped mcp_tool_call data (toolName/input/result block)", () => {
|
||||
const projected = projectActivityPayload(
|
||||
activity({
|
||||
itemType: "mcp_tool_call",
|
||||
data: {
|
||||
toolName: "mcp__github__fetch_pr",
|
||||
input: { pr: 42 },
|
||||
result: {
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_1",
|
||||
content: [{ type: "text", text: `first line of output\n${"z".repeat(5000)}` }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
|
||||
expect(data.toolName).toBe("mcp__github__fetch_pr");
|
||||
expect(data.input).toEqual({ pr: 42 });
|
||||
expect(data.result).toEqual({ content: "first line of output" });
|
||||
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
|
||||
});
|
||||
|
||||
it("passes task lifecycle payloads (no data field) through untouched", () => {
|
||||
const source = activity({
|
||||
taskId: "task-9",
|
||||
title: "Audit auth",
|
||||
role: "explorer",
|
||||
model: "opus",
|
||||
effort: "high",
|
||||
workflowName: "audit-flow",
|
||||
phases: [{ index: 0, title: "Audit" }],
|
||||
typedUsage: { totalTokens: 1200 },
|
||||
runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },
|
||||
timelineBypass: true,
|
||||
});
|
||||
const projected = projectActivityPayload(source);
|
||||
expect(projected.payload).toEqual(source.payload);
|
||||
});
|
||||
});
|
||||
@@ -123,114 +123,6 @@ function summarizeToolTextOutput(value: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fields of an MCP tool-call item both clients render in the expanded
|
||||
* work-log row. Everything else — notably `result`, which carries the full
|
||||
* tool output and dominates wire size on MCP-heavy threads — is summarized
|
||||
* or dropped. Full payloads remain in persistence.
|
||||
*/
|
||||
const MCP_ITEM_KEPT_FIELDS = [
|
||||
"type",
|
||||
"id",
|
||||
"tool",
|
||||
"server",
|
||||
"status",
|
||||
"arguments",
|
||||
"appContext",
|
||||
"error",
|
||||
"durationMs",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* Pulls renderable text out of an MCP tool result: either a Codex-style
|
||||
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
|
||||
* `tool_result` block whose `content` is a string or block array.
|
||||
*/
|
||||
function extractMcpResultText(result: unknown): string | null {
|
||||
const record = asRecord(result);
|
||||
if (!record) {
|
||||
return typeof result === "string" ? result : null;
|
||||
}
|
||||
if (typeof record.content === "string") {
|
||||
return record.content;
|
||||
}
|
||||
if (Array.isArray(record.content)) {
|
||||
const texts: string[] = [];
|
||||
for (const entry of record.content) {
|
||||
const text = asRecord(entry)?.text;
|
||||
if (typeof text === "string" && text.trim().length > 0) {
|
||||
texts.push(text);
|
||||
}
|
||||
}
|
||||
if (texts.length > 0) {
|
||||
return texts.join("\n");
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
|
||||
if (result === undefined || result === null) {
|
||||
return undefined;
|
||||
}
|
||||
const text = extractMcpResultText(result);
|
||||
const summary = text ? summarizeToolTextOutput(text) : null;
|
||||
return summary ? { content: summary } : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* MCP tool calls carry full tool results (`data.item.result` on Codex,
|
||||
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
|
||||
* keep the expanded-row UI working. Keep the fields the UI actually renders
|
||||
* and summarize the result like regular tool output.
|
||||
*/
|
||||
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
|
||||
const item = asRecord(data.item);
|
||||
if (item) {
|
||||
const projectedItem: Record<string, unknown> = {};
|
||||
for (const key of MCP_ITEM_KEPT_FIELDS) {
|
||||
if (key in item) {
|
||||
projectedItem[key] = item[key];
|
||||
}
|
||||
}
|
||||
const result = summarizeMcpResult(item.result);
|
||||
if (result) {
|
||||
projectedItem.result = result;
|
||||
}
|
||||
projectedData.item = projectedItem;
|
||||
}
|
||||
|
||||
if ("toolName" in data) {
|
||||
projectedData.toolName = data.toolName;
|
||||
}
|
||||
if ("input" in data) {
|
||||
projectedData.input = data.input;
|
||||
}
|
||||
if (!item) {
|
||||
const result = summarizeMcpResult(data.result);
|
||||
if (result) {
|
||||
projectedData.result = result;
|
||||
}
|
||||
}
|
||||
|
||||
if ("toolCallId" in data) {
|
||||
projectedData.toolCallId = data.toolCallId;
|
||||
}
|
||||
if ("kind" in data) {
|
||||
projectedData.kind = data.kind;
|
||||
}
|
||||
|
||||
const changedFiles: string[] = [];
|
||||
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
|
||||
if (changedFiles.length > 0) {
|
||||
projectedData.files = changedFiles.map((path) => ({ path }));
|
||||
}
|
||||
|
||||
return projectedData;
|
||||
}
|
||||
|
||||
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
|
||||
const rawOutput = asRecord(value);
|
||||
if (!rawOutput) {
|
||||
@@ -268,20 +160,10 @@ export function projectActivityPayload(
|
||||
): OrchestrationThreadActivity {
|
||||
const payload = asRecord(activity.payload);
|
||||
const data = asRecord(payload?.data);
|
||||
if (!payload || !data) {
|
||||
if (!payload || !data || payload.itemType === "mcp_tool_call") {
|
||||
return activity;
|
||||
}
|
||||
|
||||
if (payload.itemType === "mcp_tool_call") {
|
||||
return {
|
||||
...activity,
|
||||
payload: {
|
||||
...payload,
|
||||
data: projectMcpToolCallData(data),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const projectedData: Record<string, unknown> = {};
|
||||
const item = projectCommandData(data);
|
||||
if (item) {
|
||||
@@ -365,107 +247,6 @@ function dropStaleContextWindowActivities(
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Identity both clients use to fold a tool lifecycle row into the call it
|
||||
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
|
||||
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
|
||||
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
|
||||
* with no identity at all — those never collapse on the client either, so they
|
||||
* must not be dropped here.
|
||||
*/
|
||||
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
|
||||
const payload = asRecord(activity.payload);
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
|
||||
if (toolCallId) {
|
||||
return `id:${toolCallId}`;
|
||||
}
|
||||
|
||||
const itemType = asTrimmedString(payload.itemType) ?? "";
|
||||
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
|
||||
// gain a trailing "complete"/"completed" the in-flight updates lack.
|
||||
const label = (asTrimmedString(payload.title) ?? activity.summary)
|
||||
.replace(/\s+(?:complete|completed)\s*$/iu, "")
|
||||
.trim();
|
||||
const detail = asTrimmedString(payload.detail) ?? "";
|
||||
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return [itemType, label, detail].join("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
|
||||
* update is the in-flight snapshot of a call; once the call completes, the
|
||||
* completion carries the final state and the clients fold every matching
|
||||
* update into it, so shipping the updates buys nothing — 47k such rows exist
|
||||
* in one real database, and a single thread carries 2,291 of them totalling
|
||||
* ~1MB post-slimming.
|
||||
*
|
||||
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
|
||||
* retains per turn: a live `thread.reverted` makes the client discard whole
|
||||
* turns, so a completion in a different turn could vanish and leave the
|
||||
* dropped update unrepresented. The completion must also come *after* the
|
||||
* update within the turn — a later update belongs to a subsequent call that
|
||||
* reuses the same identity and is still in flight. Rows without a lifecycle
|
||||
* identity pass through, matching the clients, which never collapse them.
|
||||
* Live `thread.activity-appended` events are untouched: updates still stream
|
||||
* in real time and the completion supersedes them on the client as before.
|
||||
*
|
||||
* Deliberate divergence from client collapse: clients fold only *adjacent*
|
||||
* lifecycle rows, so a superseded update separated from its completion by an
|
||||
* interleaved parallel call renders as its own row today, and this drop
|
||||
* removes it. Measured against a real database, that affects 1.5% of dropped
|
||||
* rows (553 of 36,581), all pure in-flight state whose final result the
|
||||
* retained completion still shows. Dropping them is intentional; matching
|
||||
* adjacency server-side would forfeit most of the win for parallel-heavy
|
||||
* threads, which are exactly the heavy ones. Superseding completions always
|
||||
* carry a payload superset of their updates (verified across all 49,515
|
||||
* update rows: zero dropped rows held a client-merged field — detail, title,
|
||||
* command, item, kind, files — their completion lacked), so no expanded-row
|
||||
* content is lost.
|
||||
*/
|
||||
function dropSupersededToolUpdatedActivities(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
const completionIndicesByKey = new Map<string, number[]>();
|
||||
for (let index = 0; index < activities.length; index += 1) {
|
||||
const activity = activities[index]!;
|
||||
if (activity.kind !== "tool.completed") {
|
||||
continue;
|
||||
}
|
||||
const identity = toolLifecycleIdentity(activity);
|
||||
if (!identity) {
|
||||
continue;
|
||||
}
|
||||
const key = `${activity.turnId ?? ""} | ||||