Compare commits

..
691 changed files with 16788 additions and 94382 deletions

No files matched your search

+15 -4
View File
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
## Authenticate the browser on the first navigation
@@ -50,13 +50,24 @@ Treat the overall testing or implementation loop—not an assistant turn or one
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
## Recover a consumed or expired pairing token
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
Create another token against the same database and web URL as the running dev server:
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
+9 -12
View File
@@ -1,14 +1,12 @@
# Optional: T3 Connect source builds
# `cp .env.example .env` enables T3 Connect against the production deployment.
# These are the same public identifiers baked into official release builds, not
# secrets. Remove or comment them out to build with cloud features disabled.
# Do not add server-side secrets to this file.
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
# under API keys, JWT templates, and OAuth applications.
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
@@ -17,9 +15,8 @@ T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
# automatically.
T3CODE_RELAY_URL=https://relay.t3.codes
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
-5
View File
@@ -11,11 +11,9 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:gfsaaser24
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
@@ -27,9 +25,7 @@ github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:saphid
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
@@ -37,4 +33,3 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
-429
View File
@@ -1,429 +0,0 @@
const fs = require("node:fs");
const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"threadSnapshotDecodedBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const CEILING_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const SCENARIO_KEYS = [
"id",
"historyTurns",
"historyCommandToolsPerTurn",
"historyMcpResultBytes",
"measuredCommandTools",
"measuredMcpResultBytes",
];
function resultShaMarker(sha) {
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function assertExactKeys(value, expected, label) {
assertObject(value, label);
const actual = Object.keys(value).sort();
const wanted = [...expected].sort();
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
throw new Error(`${label} has unexpected fields`);
}
}
function assertMetric(value, label) {
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
}
}
function validateResult(value) {
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
if (value.schemaVersion !== 1) {
throw new Error("result.schemaVersion must be 1");
}
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
if (value.scenario.id !== "thread-transfer-v1") {
throw new Error("result.scenario.id is not supported");
}
for (const key of SCENARIO_KEYS.slice(1)) {
assertMetric(value.scenario[key], `result.scenario.${key}`);
}
assertExactKeys(value.providers, PROVIDERS, "result.providers");
for (const provider of PROVIDERS) {
const entry = value.providers[provider];
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
for (const key of OBSERVED_KEYS) {
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
}
for (const key of CEILING_KEYS) {
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
}
}
return value;
}
function readResult(directory) {
if (!directory) return undefined;
const file = path.join(directory, RESULT_FILE);
if (!fs.existsSync(file)) return undefined;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.size > 64 * 1_024) {
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
}
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
}
function formatBytes(bytes) {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
return `${(bytes / 1_024).toFixed(1)} KiB`;
}
function formatValue(value, kind) {
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
}
function formatImpact(current, baseline, kind) {
if (baseline === undefined) return "—";
const delta = current - baseline;
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
const magnitude = formatValue(Math.abs(delta), kind);
const percent =
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
return `${prefix}${magnitude}${percent}`;
}
function sameScenario(left, right) {
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
}
const METRICS = [
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
{
key: "measuredTurnWebSocketWireBytes",
label: "Live turn WebSocket wire",
kind: "bytes",
},
{
key: "measuredTurnWebSocketDecodedBytes",
label: "Live turn WebSocket decoded",
kind: "bytes",
},
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
const rows = [];
const ceilingChanges = [];
let failed = false;
for (const provider of PROVIDERS) {
for (const metric of METRICS) {
const observed = current.providers[provider].observed[metric.key];
const ceiling = current.providers[provider].ceiling[metric.key];
const baselineObserved = comparable
? baseline.providers[provider].observed[metric.key]
: undefined;
const pass = observed <= ceiling;
failed ||= !pass;
rows.push(
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
ceilingChanges.push(
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
: "unavailable";
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
const notices = [];
if (!baseline) {
notices.push(
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
);
} else if (!comparable) {
notices.push(
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
);
} else if (!input.baselineRun.matchesBase) {
notices.push(
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
);
}
if (ceilingChanges.length > 0) {
notices.push(
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
);
}
return [
COMMENT_MARKER,
resultShaMarker(input.currentRun.sha),
"## Thread transfer impact",
"",
failed
? "❌ One or more thread transfer ceilings were exceeded."
: "✅ Thread transfer remains within every enforced ceiling.",
...(notices.length > 0 ? ["", ...notices] : []),
"",
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"<details>",
"<summary>Scenario and decoded snapshot size</summary>",
"",
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
"",
...PROVIDERS.map(
(provider) =>
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
"</details>",
"",
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
].join("\n");
}
async function artifactsForRun(github, owner, repo, runId) {
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
owner,
repo,
run_id: runId,
per_page: 100,
});
}
function findResultArtifact(artifacts) {
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
}
async function resolve({ github, context, core }) {
const source = context.payload.workflow_run;
const { owner, repo } = context.repo;
if (source.event !== "pull_request") {
core.setOutput("publish", "false");
return;
}
let pullNumber = source.pull_requests?.[0]?.number;
if (!pullNumber) {
const associated = await github.paginate(
github.rest.repos.listPullRequestsAssociatedWithCommit,
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
);
const matchingPulls = associated.filter(
(pull) =>
pull.state === "open" &&
pull.head.sha === source.head_sha &&
pull.head.ref === source.head_branch,
);
if (matchingPulls.length !== 1) {
core.info(
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
);
core.setOutput("publish", "false");
return;
}
pullNumber = matchingPulls[0].number;
}
if (!pullNumber) {
core.info("No open pull request is associated with the completed CI run.");
core.setOutput("publish", "false");
return;
}
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
if (pull.head.sha !== source.head_sha) {
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
core.setOutput("publish", "false");
return;
}
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
const sourceArtifact = findResultArtifact(sourceArtifacts);
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: source.workflow_id,
branch: pull.base.ref,
event: "push",
status: "success",
per_page: 100,
});
const orderedRuns = [
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
].slice(0, 20);
let baselineRun;
for (const run of orderedRuns) {
const artifacts = await artifactsForRun(github, owner, repo, run.id);
if (findResultArtifact(artifacts)) {
baselineRun = run;
break;
}
}
core.setOutput("publish", "true");
core.setOutput("pull_number", String(pullNumber));
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
core.setOutput("pr_run_id", String(source.id));
core.setOutput("pr_sha", source.head_sha);
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
core.setOutput(
"baseline_matches_base",
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
);
}
async function upsertComment(github, context, pullNumber, body, options = {}) {
const { owner, repo } = context.repo;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(
(comment) =>
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
);
if (
options.preserveResultSha &&
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
) {
return;
}
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
}
}
async function upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
expectedSha,
body,
options,
) {
const { owner, repo } = context.repo;
const { data: pull } = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (pull.head.sha !== expectedSha) {
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
return false;
}
await upsertComment(github, context, pullNumber, body, options);
return true;
}
async function publish({ github, context, core }) {
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
throw new Error("PR_NUMBER is invalid");
}
const current = readResult(process.env.PR_RESULT_DIR);
const currentRun = {
sha: process.env.PR_SHA,
conclusion: process.env.PR_CONCLUSION,
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
};
if (!current) {
await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
[
COMMENT_MARKER,
"## Thread transfer impact",
"",
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
"",
"_This comment will update automatically after the next completed run._",
].join("\n"),
{ preserveResultSha: currentRun.sha },
);
return;
}
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
const baselineRun = baseline
? {
sha: process.env.BASELINE_SHA,
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
}
: undefined;
const body = renderComment({ current, baseline, currentRun, baselineRun });
const published = await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
body,
);
if (published) {
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
}
}
module.exports = {
publish,
readResult,
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
};
@@ -1,292 +0,0 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const {
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
const observed = {
totalWireBytes: 2_200_000,
threadSnapshotWireBytes: 1_950_000,
threadSnapshotDecodedBytes: 9_100_000,
measuredTurnWebSocketWireBytes: 250_000,
measuredTurnWebSocketDecodedBytes: 1_150_000,
measuredTurnWebSocketMessages: 15,
};
const ceiling = {
totalWireBytes: 2_900_000,
threadSnapshotWireBytes: 2_600_000,
measuredTurnWebSocketWireBytes: 320_000,
measuredTurnWebSocketDecodedBytes: 1_550_000,
measuredTurnWebSocketMessages: 20,
};
return {
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: 10,
historyCommandToolsPerTurn: 5,
historyMcpResultBytes: 900_000,
measuredCommandTools: 20,
measuredMcpResultBytes: 1_100_000,
},
providers: {
codex: { observed: { ...observed, ...overrides }, ceiling },
claudeAgent: { observed, ceiling },
},
};
}
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
/unexpected fields/,
);
assert.throws(
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
});
test("renders baseline, impact, ceiling, and ceiling changes", () => {
const baseline = result();
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
current.providers.codex.ceiling = {
...current.providers.codex.ceiling,
measuredTurnWebSocketWireBytes: 330_000,
};
const comment = renderComment({
current,
baseline,
currentRun: {
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
conclusion: "success",
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
},
baselineRun: {
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
matchesBase: true,
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
},
});
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
assert.match(comment, /This PR changes transfer ceilings/);
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
assert.match(
comment,
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
const outputs = {};
const listWorkflowRunArtifacts = () => {};
const listWorkflowRuns = () => {};
const listPullRequestsAssociatedWithCommit = () => {};
const github = {
paginate: async (method, input) => {
if (method === listPullRequestsAssociatedWithCommit) {
return [
{
number: 5350,
state: "open",
head: { sha: "head-sha", ref: "feature-branch", repo: null },
},
];
}
if (method === listWorkflowRunArtifacts) {
return [
{
name: "thread-transfer-results",
expired: false,
runId: input.run_id,
},
];
}
if (method === listWorkflowRuns) {
return [{ id: 1, head_sha: "base-sha" }];
}
throw new Error("unexpected pagination call");
},
rest: {
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
pulls: {
get: async () => ({
data: {
head: { sha: "head-sha" },
base: { sha: "base-sha", ref: "main" },
},
}),
},
repos: { listPullRequestsAssociatedWithCommit },
},
};
await resolve({
github,
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "true");
assert.equal(outputs.pull_number, "5350");
assert.equal(outputs.pr_artifact, "true");
assert.equal(outputs.baseline_run_id, "1");
assert.equal(outputs.baseline_matches_base, "true");
});
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
const outputs = {};
const listPullRequestsAssociatedWithCommit = () => {};
let fetchedPull = false;
await resolve({
github: {
paginate: async (method) => {
assert.equal(method, listPullRequestsAssociatedWithCommit);
return [5350, 5351].map((number) => ({
number,
state: "open",
head: {
sha: "head-sha",
ref: "feature-branch",
repo: { full_name: "pingdotgg/t3code" },
},
}));
},
rest: {
actions: {},
pulls: {
get: async () => {
fetchedPull = true;
},
},
repos: { listPullRequestsAssociatedWithCommit },
},
},
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "false");
assert.equal(fetchedPull, false);
});
test("does not publish a stale result after the PR head advances", async () => {
let listedComments = false;
const info = [];
const published = await upsertCommentForCurrentHead(
{
paginate: async () => {
listedComments = true;
return [];
},
rest: {
issues: {
listComments: () => {},
createComment: () => {
throw new Error("must not create a stale comment");
},
updateComment: () => {
throw new Error("must not update a stale comment");
},
},
pulls: {
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: (message) => info.push(message) },
5350,
"old-head-sha",
"stale body",
);
assert.equal(published, false);
assert.equal(listedComments, false);
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
});
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
let updatedComment = false;
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const published = await upsertCommentForCurrentHead(
{
paginate: async () => [
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
},
],
rest: {
issues: {
listComments: () => {},
createComment: () => {
updatedComment = true;
},
updateComment: () => {
updatedComment = true;
},
},
pulls: {
get: async () => ({ data: { head: { sha } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: () => {} },
5350,
sha,
"missing artifact warning",
{ preserveResultSha: sha },
);
assert.equal(published, true);
assert.equal(updatedComment, false);
});
-21
View File
@@ -84,29 +84,8 @@ jobs:
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
env:
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
run: vp run test
- name: Publish transfer budget report
if: always()
run: |
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
else
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
fi
- name: Upload thread transfer result
if: always()
uses: actions/upload-artifact@v7
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer-result.json
if-no-files-found: ignore
retention-days: 30
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
+5 -176
View File
@@ -5,25 +5,6 @@ name: Mobile EAS Production
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
#
# Every merge to main that touches the mobile app reconciles, per platform:
# 1. Store builds: if the latest production build's version differs from
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
# track). Bumping `version` is therefore all it takes to
# start the next release train — the first build of a version enters
# external-TestFlight beta review immediately, and later builds of the
# same version auto-approve until that version is released. After App
# Store approval, Apple closes the release train and `version` must be
# bumped before another iOS build can be submitted. Releasing to the App
# Store stays a manual App Store Connect step.
# 2. OTA: publish a production-channel update for each platform where at
# least one finished production build matches the current native
# fingerprint. Old-version binaries with a matching fingerprint receive
# it too. When native drift means no binary could install the update,
# it is skipped and flagged in the job summary instead of published
# into the void.
# workflow_dispatch remains as a manual override for both modes (e.g. to
# retry an errored build or force an OTA).
on:
workflow_dispatch:
inputs:
@@ -44,38 +25,14 @@ on:
- ios
- android
- all
version:
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
required: false
type: string
message:
description: "OTA update message (mode=update only)"
required: false
type: string
push:
branches: [main]
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-eas-production.yml
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
# queued run per group, so a burst of merges collapses into one run of the
# newest commit — intermediate commits don't need their own OTA.
concurrency:
group: mobile-eas-production
cancel-in-progress: false
jobs:
production:
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
name: EAS Production ${{ inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
@@ -95,21 +52,11 @@ jobs:
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- id: version_app_token
name: Mint release app token for version override
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
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
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
token: ${{ steps.version_app_token.outputs.token || github.token }}
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
@@ -151,74 +98,15 @@ jobs:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Apply manual version override
if: steps.version_app_token.outcome == 'success'
env:
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
RELEASE_VERSION: ${{ inputs.version }}
run: |
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
exit 1
fi
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
exit 1
fi
node --input-type=module -e '
import fs from "node:fs";
const path = "apps/mobile/app.config.ts";
const source = fs.readFileSync(path, "utf8");
const next = source.replace(
/^( version: ")[^"]+(".*)$/m,
`$1${process.env.RELEASE_VERSION}$2`,
);
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
throw new Error("Could not update app version");
}
fs.writeFileSync(path, next);
'
vp fmt apps/mobile/app.config.ts
if git diff --quiet -- apps/mobile/app.config.ts; then
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
exit 0
fi
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
git config user.name "${APP_SLUG}[bot]"
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
git add apps/mobile/app.config.ts
git commit \
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
-m "Co-authored-by: codex <[email protected]>"
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
- name: Summarize manual build version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
run: |
version="$(npx expo config --json --type public | jq -r '.version')"
{
echo "## Manual production build"
echo
echo "- App version: \`$version\`"
echo "- Platform: \`${{ inputs.platform }}\`"
echo
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build and submit (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
@@ -229,62 +117,3 @@ jobs:
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
# No --status filter on build:list: an in-queue/in-progress build must
# count as existing, or every merge during the build window would cut a
# duplicate. After an errored build, retry via workflow_dispatch
# mode=build — pushes won't re-trigger it until the app version changes.
- id: store_builds
name: Ensure store builds exist for the current app version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
continue-on-error: true
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
failed=0
version="$(npx expo config --json --type public | jq -r '.version')"
for platform in ios android; do
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
if [ "$latest" = "$version" ]; then
echo "$platform: production build for $version already exists (or is in progress)"
continue
fi
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
else
failed=1
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
fi
done
exit "$failed"
- name: Publish fingerprint-gated OTA
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
for platform in ios android; do
# eas-cli prints an environment-loaded notice to stdout before the
# JSON even with --json, so discard everything before the document.
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
if [ "$matching" -gt 0 ]; then
eas update \
--channel production \
--environment production \
--platform "$platform" \
--message "$message" \
--non-interactive
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
else
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
fi
done
- name: Propagate store build failure
if: steps.store_builds.outcome == 'failure'
run: exit 1
@@ -1,205 +0,0 @@
name: Mobile Fingerprint Check
# Detects whether a PR changes the native fingerprint — i.e. whether merging
# it would leave main un-OTA-able until a new store build ships. Native-change
# PRs get the "📱 Native Change" label so they can be held and merged as a
# batch right before the next store submission, keeping main OTA-able for
# everything else in between. (Once one native PR merges, every later merge
# inherits the drifted fingerprint and loses OTA reach too — that is why the
# signal has to fire before merge, not after.)
#
# The check is advisory: it always passes, the label is the signal. Both
# fingerprints are computed in this one job (same OS, same corepack-pinned
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
on:
pull_request:
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-fingerprint-check.yml
concurrency:
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
fingerprint:
name: Native fingerprint diff
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
issues: write
pull-requests: write
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# Default pull_request checkout is the merge commit (PR applied on
# top of base), so the "head" fingerprint is the state main would
# actually be in after merging — stale branches compare cleanly.
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Fingerprint merge result
working-directory: apps/mobile
run: |
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
done
- name: Fingerprint base
run: |
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
# Re-sync node_modules to the base commit's lockfile before
# fingerprinting — a dep-changing PR must not fingerprint the base
# against head's installed packages.
pnpm install --filter=@t3tools/mobile...
cd apps/mobile
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
done
- id: compare
name: Compare fingerprints
run: |
changed=""
{
echo "## Native fingerprint diff"
echo
for platform in ios android; do
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
if [ "$head_hash" = "$base_hash" ]; then
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
continue
fi
changed="$changed $platform"
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
jq -r -n \
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
| $h[0].sources[]
| select($bm[(.filePath // .id)] != .hash)
| " - \(.type): `\(.filePath // .id)`"'
done
} >> "$GITHUB_STEP_SUMMARY"
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
- name: Sync native change label
# Fork PRs get a read-only token under pull_request; the check stays
# advisory there (summary only). This workflow must not move to
# pull_request_target — it installs and runs PR code.
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v8
env:
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
with:
script: |
const managedLabel = {
name: "📱 Native Change",
color: "d93f0b",
description:
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
};
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
const issueNumber = context.payload.pull_request.number;
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
});
if (
existing.color !== managedLabel.color ||
(existing.description ?? "") !== managedLabel.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
if (nativeChanged && !hasLabel) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [managedLabel.name],
});
} else if (!nativeChanged && hasLabel) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: managedLabel.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
core.info(
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
);
+13 -7
View File
@@ -746,10 +746,16 @@ jobs:
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 30
permissions:
contents: write
timeout-minutes: 10
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 });
-132
View File
@@ -1,132 +0,0 @@
name: Web Preview
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
# that push and every subsequent push. The deployment is a plain (non-prod,
# non-aliased) deploy into the existing hosted-web Vercel project, so the
# latest/nightly channel aliases are never touched.
#
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
# backend) and open the pairing URL against the preview origin.
#
# The preview must be opened at the exact deployment URL from the PR comment.
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
# self-identify as the hosted app.
on:
pull_request:
types: [labeled, synchronize, reopened]
permissions:
contents: read
pull-requests: write
concurrency:
group: web-preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
deploy:
name: Deploy web preview
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
# workflow should skip rather than fail for them. On `labeled` events, only
# the preview label itself triggers a deploy.
if: >-
github.event.pull_request.head.repo.full_name == github.repository &&
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- id: deploy
name: Deploy preview
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
deployment_url="$(
vp dlx [email protected] deploy \
--archive=tgz \
--yes \
--token "$VERCEL_TOKEN" \
--scope "$vercel_scope"
)"
echo "Deployed $deployment_url"
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
- name: Comment deployment URL
uses: actions/github-script@v8
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
with:
script: |
const marker = "<!-- web-preview-deploy -->";
const body = [
marker,
"### Web preview",
"",
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
"",
"Open this exact URL — the hosted-app origin is baked in at build time.",
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
"code under Settings → Connections.",
].join("\n");
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
per_page: 100,
});
const existing = comments.find((comment) => comment.body?.includes(marker));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body,
});
}
+2 -2
View File
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
-1
View File
@@ -68,7 +68,6 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.33",
"version": "0.0.31",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -78,7 +78,6 @@ describe("DesktopLifecycle", () => {
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -91,7 +91,6 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -28,6 +28,70 @@ describe("ElectronDialog", () => {
showErrorBoxMock.mockReset();
});
it.effect("returns false without opening a confirm dialog for empty messages", () =>
Effect.gen(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: " ",
owner: Option.none(),
});
assert.isFalse(result);
assert.equal(showMessageBoxMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens a confirm dialog for the owner window", () =>
Effect.gen(function* () {
const owner = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.some(owner),
});
assert.isTrue(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
owner,
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
Effect.gen(function* () {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.none(),
});
assert.isFalse(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
@@ -53,6 +117,31 @@ describe("ElectronDialog", () => {
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
+31 -24
View File
@@ -6,6 +6,8 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
@@ -21,18 +23,17 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
}
}
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
"ElectronDialogPickFilesError",
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
defaultPath: Schema.NullOr(Schema.String),
promptLength: Schema.Number,
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}.`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
@@ -68,7 +69,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogPickFilesError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
@@ -80,10 +81,9 @@ export interface ElectronDialogPickFolderInput {
readonly defaultPath: Option.Option<string>;
}
export interface ElectronDialogPickFilesInput {
export interface ElectronDialogConfirmInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly defaultPath: Option.Option<string>;
readonly filters: readonly Electron.FileFilter[];
readonly message: string;
}
export class ElectronDialog extends Context.Service<
@@ -92,9 +92,9 @@ 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>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
@@ -137,31 +137,38 @@ export const make = ElectronDialog.of({
}
return Option.fromNullishOr(result.filePaths[0]);
}),
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
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),
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogPickFilesError({
new ElectronDialogConfirmError({
ownerWindowId,
defaultPath,
promptLength: normalizedMessage.length,
cause,
}),
});
return result.canceled ? [] : result.filePaths;
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) =>
Effect.tryPromise({
+2 -2
View File
@@ -31,13 +31,13 @@ import {
setUpdateChannel,
} from "./methods/updates.ts";
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getWindowFullscreenState,
openExternal,
pickFolder,
pickThemeFiles,
setTheme,
showContextMenu,
} from "./methods/window.ts";
@@ -79,7 +79,7 @@ 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);
yield* ipc.handle(openExternal);
+1 -1
View File
@@ -1,5 +1,5 @@
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";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
+13 -51
View File
@@ -3,15 +3,10 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -220,6 +215,19 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
}),
});
export const confirm = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
return yield* electronWindow.focusedMainOrFirst.pipe(
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
);
}),
});
export const setTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
@@ -260,49 +268,3 @@ export const openExternal = DesktopIpc.makeIpcMethod({
return yield* shell.openExternal(url);
}),
});
/** Theme files are a few KB; anything larger returns empty text and lets the
* renderer reject it by size without the contents ever crossing the bridge. */
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
payload: Schema.Undefined,
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// The VS Code extensions directory is the same dotfolder on Windows,
// macOS, and Linux; when it is missing the picker opens wherever the
// platform would by default.
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
const defaultPath = yield* fileSystem
.exists(extensionsDir)
.pipe(Effect.orElseSucceed(() => false));
const paths = yield* dialog.pickFiles({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
filters: [{ name: "JSON", extensions: ["json"] }],
});
if (paths.length === 0) {
return null;
}
return yield* Effect.forEach(paths, (filePath) => {
const name = path.basename(filePath);
return Effect.gen(function* () {
const info = yield* fileSystem.stat(filePath);
const size = Number(info.size);
if (size > PICKED_THEME_FILE_MAX_BYTES) {
return { name, size, text: "" } satisfies PickedThemeFile;
}
const text = yield* fileSystem.readFileString(filePath);
return { name, size, text } satisfies PickedThemeFile;
}).pipe(
// An unreadable file degrades to an entry the renderer reports.
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
);
});
}),
});
+1 -1
View File
@@ -97,7 +97,7 @@ 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) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
@@ -13,6 +13,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
@@ -29,7 +30,6 @@ const clientSettings: ClientSettings = {
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarProjectGroupingMode: "repository_path",
@@ -39,7 +39,8 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
legacySidebarEnabled: false,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -231,7 +231,6 @@ describe("DesktopShellEnvironment", () => {
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.local\\bin",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
@@ -207,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
...trimNonEmpty(env.USERPROFILE).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
}),
),
];
@@ -379,18 +379,10 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
// Concurrent, not sequential: these two probes are independent (only their
// results are combined below) and each spawns its own PowerShell. Run in
// series they sit at offset 0 of desktop.startup, before anything else, and
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
// startup span, of which desktop.bootstrap is ~30ms.
const [noProfile, profile] = yield* Effect.all(
[
readWindowsEnvironment(["PATH"], { loadProfile: false }),
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
],
{ concurrency: 2 },
);
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
@@ -52,7 +52,7 @@ 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,
} satisfies ElectronDialog.ElectronDialog["Service"]);
@@ -80,8 +80,6 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -95,30 +93,6 @@ const makeElectronMenuLayer = (
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -126,7 +100,25 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -145,38 +137,4 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
// zoom roles: the roles zoom whichever webContents has focus, which breaks
// app zoom while an embedded preview WebContentsView holds focus.
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const viewMenu = template.find((item) => item.label === "View");
assert.isDefined(viewMenu);
if (!Array.isArray(viewMenu.submenu)) {
throw new Error("Expected View menu submenu to be an array.");
}
assert.isUndefined(
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
);
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
assert.isDefined(zoomIn);
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
if (typeof zoomIn.click !== "function") {
throw new Error("Expected Zoom In menu item to have a click handler.");
}
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
}),
);
});
@@ -49,13 +49,6 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
direction: DesktopWindow.MainWindowZoomDirection,
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.zoomMain(direction);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -134,9 +127,6 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -191,21 +181,10 @@ export const make = Effect.gen(function* () {
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
/*
Not the zoom roles: those act on the focused webContents, so with
an embedded preview WebContentsView focused they zoom the guest
page and the app UI appears stuck. These always zoom the main
window (see DesktopWindow.zoomMain).
*/
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
{
label: "Zoom In",
accelerator: "CmdOrCtrl+Plus",
visible: false,
click: zoomClick("in"),
},
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
-20
View File
@@ -61,8 +61,6 @@ export type DesktopWindowError =
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export type MainWindowZoomDirection = "in" | "out" | "reset";
export class DesktopWindow extends Context.Service<
DesktopWindow,
{
@@ -89,12 +87,6 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
// Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
// menu roles act on whichever webContents has keyboard focus, so with an
// embedded preview WebContentsView (or DevTools) focused they zoom the
// guest page instead of the app UI. The menu routes here to always target
// the main window.
readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -844,18 +836,6 @@ export const make = Effect.gen(function* () {
send();
}),
zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
yield* Effect.annotateCurrentSpan({ direction });
const window = yield* focusedMainWindow;
if (Option.isNone(window) || window.value.isDestroyed()) {
return;
}
const webContents = window.value.webContents;
// Same step size as the Electron zoomIn/zoomOut menu roles.
webContents.setZoomLevel(
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
);
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
+1 -1
View File
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
</div>
<p class="releases-link">
Looking for older versions? Check the{" "}
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
+1 -2
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.3",
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.
@@ -338,7 +338,6 @@ const config: ExpoConfig = {
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
"./plugins/withAndroidTabletOrientation.cjs",
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
@@ -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))
+1 -6
View File
@@ -49,7 +49,7 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "catalog:",
"@legendapp/list": "3.3.3",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
@@ -138,10 +138,5 @@
"@react-native-menu/menu"
]
}
},
"reanimated": {
"staticFeatureFlags": {
"DISABLE_COMMIT_PAUSING_MECHANISM": true
}
}
}
@@ -1,80 +0,0 @@
const { withMainActivity } = require("expo/config-plugins");
// The top-level `orientation: "portrait"` writes android:screenOrientation="portrait"
// into the manifest, which locks every Android device — including tablets — to
// portrait. iOS doesn't have this problem: iPads must support all orientations
// because the app is multitasking-capable, so only iPhones end up portrait-only.
// Mirror that split on Android: keep the manifest lock for phones and lift it at
// runtime on tablets (smallest width >= 600dp, the standard tablet breakpoint),
// since requestedOrientation set at runtime overrides the manifest value.
// FULL_USER allows all four orientations while still respecting the user's
// auto-rotate lock, matching iPad behavior. Foldables change
// smallestScreenWidthDp on fold/unfold without recreating the activity
// (smallestScreenSize is in the manifest's configChanges), so the policy is
// re-evaluated in onConfigurationChanged: unfolding past the tablet breakpoint
// unlocks rotation, and folding back restores the portrait lock.
const ORIENTATION_METHODS = `
// Applied in onCreate and re-applied on fold/unfold; added by
// withAndroidTabletOrientation.
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
applyTabletOrientation()
}
private fun applyTabletOrientation() {
requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
ActivityInfo.SCREEN_ORIENTATION_FULL_USER
} else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
`;
const ORIENTATION_ON_CREATE_CALL = `
applyTabletOrientation()`;
function insertAfter(contents, anchor, insertion, description) {
const index = contents.indexOf(anchor);
if (index === -1) {
throw new Error(
`withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
);
}
const end = index + anchor.length;
return contents.slice(0, end) + insertion + contents.slice(end);
}
module.exports = function withAndroidTabletOrientation(config) {
return withMainActivity(config, (nextConfig) => {
let contents = nextConfig.modResults.contents;
if (nextConfig.modResults.language !== "kt") {
throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
}
if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
return nextConfig;
}
contents = insertAfter(
contents,
"import android.os.Bundle",
"\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
"the android.os.Bundle import",
);
contents = insertAfter(
contents,
"class MainActivity : ReactActivity() {",
ORIENTATION_METHODS,
"the MainActivity class declaration",
);
contents = insertAfter(
contents,
"super.onCreate(null)",
ORIENTATION_ON_CREATE_CALL,
"the super.onCreate call",
);
nextConfig.modResults.contents = contents;
return nextConfig;
});
};
+13 -36
View File
@@ -18,6 +18,7 @@ import { AppText as Text } from "./components/AppText";
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
@@ -46,8 +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 { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -133,7 +132,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
presentation: "fullScreenModal",
};
const SettingsContentStack = createNativeStackNavigator({
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
@@ -176,13 +175,6 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Appearance",
},
}),
SettingsProjectGrouping: createNativeStackScreen({
screen: SettingsProjectGroupingRouteScreen,
linking: "project-grouping",
options: {
title: "Project Grouping",
},
}),
SettingsClientStorage: createNativeStackScreen({
screen: SettingsClientStorageRouteScreen,
linking: "client-storage",
@@ -190,37 +182,20 @@ const SettingsContentStack = createNativeStackNavigator({
title: "Client Storage",
},
}),
SettingsUsage: createNativeStackScreen({
screen: UsageRouteScreen,
linking: "usage",
options: {
title: "Usage",
},
}),
},
});
// The outer stack never owns visible chrome. Settings routes render inside a
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "SettingsContent",
screenOptions: {
headerShown: false,
},
screens: {
SettingsContent: createNativeStackScreen({
screen: SettingsContentStack,
linking: "",
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
// Keep the old deep link working after the Connect GA launch.
screen: SettingsAuthRouteScreen,
linking: "waitlist",
options: {
title: "Sign in",
},
}),
},
});
@@ -356,9 +331,11 @@ function RootStackLayout(props: {
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
</HardwareKeyboardCommandProvider>
);
}
@@ -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"
-2
View File
@@ -14,7 +14,6 @@ import {
IconBellRinging,
IconBolt,
IconCamera,
IconChartBar,
IconCheck,
IconChevronDown,
IconCode,
@@ -98,7 +97,6 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"bolt.circle": IconBolt,
"bolt.horizontal.circle": IconBolt,
camera: IconCamera,
"chart.bar.xaxis": IconChartBar,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
@@ -16,18 +16,6 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
/**
* Horizontal correction applied to content rendered in the brand title slot,
* shared with the connection-status swap so both align identically.
*/
export function brandTitleOffset(nativeLeadingItem: boolean): number {
if (Platform.OS !== "ios") return 0;
if (nativeLeadingItem) {
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
}
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
}
/**
* Compact brand lockup sized for native navigation bars.
*/
@@ -40,7 +28,16 @@ export function CompactBrandTitle(
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
const titleOffset =
Platform.OS !== "ios"
? 0
: props.nativeLeadingItem
? Platform.isPad
? IPAD_NATIVE_LEADING_TITLE_OFFSET
: IOS_NATIVE_LEADING_TITLE_OFFSET
: Platform.isPad
? IPAD_HOME_TITLE_OFFSET
: 0;
return (
<View
+2 -43
View File
@@ -6,7 +6,6 @@ import {
type ComponentProps,
type ReactElement,
type ReactNode,
useRef,
} from "react";
import { Platform, Pressable, useColorScheme, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
@@ -22,31 +21,10 @@ export function ControlPill(props: {
readonly label?: string;
readonly accessibilityLabel?: string;
readonly onPress?: () => void;
readonly activateOnPressIn?: boolean;
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
readonly className?: string;
}) {
const variant = props.variant ?? "circle";
const activatedOnPressInRef = useRef(false);
const handlePressIn = () => {
activatedOnPressInRef.current = true;
props.onPress?.();
};
const handlePressOut = () => {
// Pressability invokes onPressOut immediately before onPress on release.
// Defer the reset so onPress can identify the same physical gesture.
setTimeout(() => {
activatedOnPressInRef.current = false;
}, 0);
};
const handlePress = () => {
if (activatedOnPressInRef.current) {
return;
}
props.onPress?.();
};
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
@@ -76,7 +54,6 @@ export function ControlPill(props: {
: variant === "danger"
? "bg-danger"
: "bg-subtle",
props.className,
);
const labelClassName = cn(
"text-center text-xs font-t3-bold",
@@ -91,9 +68,7 @@ export function ControlPill(props: {
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
onPress={props.activateOnPressIn ? handlePress : props.onPress}
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
onPress={props.onPress}
disabled={props.disabled}
className={containerClassName}
>
@@ -158,25 +133,9 @@ export function ControlPillMenu(
}
const { className: _className, ...menuProps } = props;
let children = menuProps.children;
// In long-press mode the wrapped pressable still receives the touch (the
// patched MenuView button is touch-transparent) and RN's Fabric touch
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
// bare onPress would fire on finger-up even after the menu opened — and
// also on a long press released just under the menu threshold. A dispatched
// onLongPress makes Pressability swallow the release, so holds past 350ms
// (below the ~500ms context-menu threshold) can only open the menu, never
// tap through.
if (props.shouldOpenOnLongPress && isValidElement(children)) {
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
children = cloneElement(child, {
onLongPress: child.props.onLongPress ?? (() => undefined),
delayLongPress: child.props.delayLongPress ?? 350,
});
}
return (
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
{children}
{menuProps.children}
</MenuView>
);
}
@@ -24,18 +24,13 @@ export function ProjectFavicon(props: {
readonly size?: number;
readonly projectTitle: string;
readonly workspaceRoot?: string | null;
readonly faviconPath?: string | null;
}) {
const size = props.size ?? 42;
const faviconUrl = useAssetUrl(
props.environmentId,
props.workspaceRoot === null || props.workspaceRoot === undefined
? null
: {
_tag: "project-favicon",
cwd: props.workspaceRoot,
...(props.faviconPath ? { path: props.faviconPath } : {}),
},
: { _tag: "project-favicon", cwd: props.workspaceRoot },
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
const cacheKey =
@@ -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;
@@ -5,6 +5,7 @@ import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { useArchivedThreadListActions } from "../home/useThreadListActions";
import {
ArchivedThreadsScreen,
@@ -17,6 +18,7 @@ import {
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
@@ -68,8 +70,9 @@ export function ArchivedThreadsRouteScreen() {
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [refresh]),
}, [expand, refresh]),
);
return (
@@ -368,7 +368,6 @@ function ProjectGroupLabel(props: {
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
projectTitle={props.project.title}
size={18}
workspaceRoot={props.project.workspaceRoot}
@@ -0,0 +1,44 @@
import {
createContext,
type PropsWithChildren,
useCallback,
useContext,
useMemo,
useState,
} from "react";
interface ClerkSettingsSheetDetentValue {
collapse: () => void;
expand: () => void;
isExpanded: boolean;
}
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
initiallyExpanded: boolean;
}
export function ClerkSettingsSheetDetentProvider({
children,
initiallyExpanded,
}: ClerkSettingsSheetDetentProviderProps) {
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
const collapse = useCallback(() => setIsExpanded(false), []);
const expand = useCallback(() => setIsExpanded(true), []);
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
return (
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
);
}
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
const value = useContext(ClerkSettingsSheetDetentContext);
if (!value) {
throw new Error(
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
);
}
return value;
}
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// Sign-in happens inside the Settings sheet; give its session-state transition
// a beat to settle before presenting another formSheet on top.
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
@@ -21,7 +21,6 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { useThemeColor } from "../../lib/useThemeColor";
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
import { ConnectionStatusDot } from "./ConnectionStatusDot";
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
@@ -43,11 +42,6 @@ interface CloudEnvironmentRowsProps {
* with connect switches, availability status, refresh, and loading/error
* states. Shared between the Settings environments screen and the T3 Connect
* onboarding sheet.
*
* Already-connected relay environments render even without cloud config or a
* signed-in account — they are registered on this device and must stay
* reachable and removable. Only discovery (the available list, refresh, and
* its errors) requires a signed-in session.
*/
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
@@ -56,33 +50,20 @@ export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
if (props.showcaseSignedIn !== undefined) {
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
}
// No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
if (!hasCloudPublicConfig()) {
return <ConnectedOnlyCloudEnvironmentRows {...props} />;
}
return <SignedInCloudEnvironmentRows {...props} />;
}
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
if (!isSignedIn) return null;
return <CloudEnvironmentRowsContent {...props} />;
}
function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
if (props.connectedCloudEnvironments.length === 0) return null;
return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
}
function CloudEnvironmentRowsContent(
props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
) {
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
const controller = useConnectionController();
const iconColor = useThemeColor("--color-icon");
const discoveryAvailable = props.discoveryAvailable ?? true;
const availableCloudEnvironments = discoveryAvailable
? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
: [];
const availableCloudEnvironments =
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
const hasCloudRows =
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
@@ -108,27 +89,25 @@ function CloudEnvironmentRowsContent(
{showHeader ? (
<View className="flex-row items-center justify-between px-1">
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
{discoveryAvailable ? (
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
) : null}
<Pressable
accessibilityRole="button"
disabled={controller.relayDiscovery.isRefreshing}
onPress={() => {
void controller.refreshRelayEnvironments();
}}
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
>
{controller.relayDiscovery.isRefreshing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="arrow.clockwise"
size={14}
tintColor={iconColor}
type="monochrome"
/>
)}
</Pressable>
</View>
) : null}
@@ -173,9 +152,7 @@ function CloudEnvironmentRowsContent(
{/* Rendered alongside any connected rows — a failed discovery must not
hide behind an otherwise-healthy list. */}
{discoveryAvailable &&
controller.relayDiscovery.error &&
!controller.relayDiscovery.isRefreshing ? (
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
<Text className="text-base font-t3-bold text-foreground">
Could not load T3 Connect environments
@@ -58,8 +58,8 @@ export function ConnectionsRouteScreen() {
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
contentContainerStyle={{
paddingBottom: Math.max(insets.bottom, 18) + 18,
paddingHorizontal: 20,
paddingTop: 16,
}}
+12 -23
View File
@@ -21,7 +21,6 @@ import {
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
} from "../layout/native-mail-search-toolbar";
import type { HomeProjectSortOrder } from "./homeThreadList";
import { WorkspaceConnectionTitle } from "./WorkspaceConnectionTitle";
import {
buildHomeListFilterMenu,
type HomeListFilterMenuEnvironment,
@@ -48,7 +47,6 @@ export function HomeHeader(props: {
readonly onProjectChange: (projectKey: string | null) => void;
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
}) {
@@ -209,27 +207,18 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
>
<View className="w-full max-w-[720px] self-center gap-3">
<View className="flex-row items-center gap-2.5">
{/* Brand slot doubles as the connection status surface: while an
environment reconnects, the lockup fades to a status label in
place (no layout shift in the list below). */}
<WorkspaceConnectionTitle
grow
onPress={props.onOpenEnvironments}
brand={
<View className="flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
}
/>
<View className="flex-1 flex-row items-center gap-2">
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
<T3Wordmark color={iconColor} height={15} />
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
Code
</RNText>
<View className="rounded-full bg-subtle px-2 py-0.75">
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
{stageLabel}
</RNText>
</View>
</View>
<ControlPillMenu
actions={menuActions}
@@ -3,6 +3,7 @@ import * as Order from "effect/Order";
import { useNavigation } from "@react-navigation/native";
import { useEffect, useMemo, useState } from "react";
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
@@ -19,7 +20,6 @@ import { useHomeListOptions } from "./home-list-options";
import { buildHomeProjectScopes } from "./homeThreadList";
import { usePendingTaskListActions } from "./usePendingTaskListActions";
import { useThreadListActions } from "./useThreadListActions";
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
/* ─── Route screen ───────────────────────────────────────────────────── */
@@ -44,8 +44,6 @@ export function HomeRouteScreen() {
unsnoozeThread,
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -128,19 +126,8 @@ export function HomeRouteScreen() {
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
>
<>
{/* Restore the compact title after the split branch blanks the detail
header. The brand slot doubles as the connection status surface:
while an environment reconnects, the lockup fades to a status label
in place (no layout shift in the list below). */}
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
}),
})}
/>
{/* Restore the compact title after the split branch blanks the detail header. */}
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
<HomeHeader
environments={environments}
projects={projectFilterOptions}
@@ -151,18 +138,7 @@ export function HomeRouteScreen() {
threadSortOrder={listOptions.threadSortOrder}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
})
}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
@@ -173,10 +149,7 @@ export function HomeRouteScreen() {
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
@@ -186,16 +159,12 @@ export function HomeRouteScreen() {
onUnsettleThread={unsettleThread}
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
+42 -81
View File
@@ -11,7 +11,6 @@ import {
threadSearchMatchKey,
type EnvironmentThreadSearchMatch,
} from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type {
EnvironmentId,
SidebarProjectGroupingMode,
@@ -72,6 +71,8 @@ import {
type HomeProjectSortOrder,
} from "./homeThreadList";
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
/* ─── Types ──────────────────────────────────────────────────────────── */
@@ -96,6 +97,7 @@ interface HomeScreenProps {
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
readonly onAddConnection: () => void;
readonly onOpenEnvironments: () => void;
readonly onOpenSettings: () => void;
readonly onStartNewTask: () => void;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
@@ -111,11 +113,6 @@ interface HomeScreenProps {
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onMovePinnedThread: (
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -527,24 +524,12 @@ 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);
},
[props.onUnpinThread],
);
const handleRegenerateThreadTitle = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onRegenerateThreadTitle(thread);
},
[props.onRegenerateThreadTitle],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -613,38 +598,6 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const pinReorderEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadPinReorder === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === 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 {
@@ -741,11 +694,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,
@@ -763,7 +712,6 @@ export function HomeScreen(props: HomeScreenProps) {
: null
}
showPendingDivider={item.showPendingDivider}
showTrailingDivider={showTrailingDivider}
onSelectPendingTask={props.onSelectPendingTask}
onDeletePendingTask={props.onDeletePendingTask}
/>
@@ -796,7 +744,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
}
@@ -827,24 +774,15 @@ export function HomeScreen(props: HomeScreenProps) {
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
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
@@ -857,10 +795,7 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleChangeRequestState,
handleDeleteThread,
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -869,7 +804,6 @@ export function HomeScreen(props: HomeScreenProps) {
handleSwipeableWillOpen,
handleUnsettleThread,
pinningEnvironmentIds,
pinReorderEnvironmentIds,
projectByKey,
projectCwdByKey,
props.onArchiveThread,
@@ -880,9 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
serverConfigs,
settlementEnvironmentIds,
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -987,8 +919,6 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1010,7 +940,6 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -1021,7 +950,6 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -1041,13 +969,20 @@ export function HomeScreen(props: HomeScreenProps) {
? null
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
"this environment");
// Connection state surfaces in the header title slot
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
// reconnects never shift the rows.
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
const emptyState = deriveEmptyState({
catalogState: props.catalogState,
projectCount: props.projects.length,
});
const connectionStatus =
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
<View
className="absolute left-0 right-0 items-center"
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
>
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
</View>
) : null;
if (!hasAnyThreads) {
return (
@@ -1066,17 +1001,41 @@ export function HomeScreen(props: HomeScreenProps) {
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
variant="plain"
/>
{emptyState.loading ? (
{emptyState.loading && !shouldShowConnectionStatus ? (
<View className="mt-4 items-center">
<ActivityIndicator color={accentColor} />
</View>
) : null}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="mt-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</View>
{connectionStatus}
</View>
);
}
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
const listHeader = (
<>
{Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
<View className="pb-4">
<WorkspaceConnectionStatus
state={props.catalogState}
onPress={props.onOpenEnvironments}
variant="sidebar"
/>
</View>
) : null}
</>
);
// Project scoping lives in the header filter menu (no inline chip row on
// mobile — the menu is the one filter surface).
@@ -1157,6 +1116,7 @@ export function HomeScreen(props: HomeScreenProps) {
}}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -1211,6 +1171,7 @@ export function HomeScreen(props: HomeScreenProps) {
}
/>
</SwipeableScrollGateProvider>
{connectionStatus}
</View>
);
}
@@ -4,7 +4,6 @@ import type { WorkspaceState } from "../../state/workspaceModel";
import {
shouldShowWorkspaceConnectionStatus,
workspaceConnectionStatusLabel,
workspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
@@ -85,36 +84,4 @@ describe("workspace connection status", () => {
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
});
it("presents nothing while connected", () => {
expect(workspaceConnectionStatusPresentation(workspaceState())).toBeNull();
});
it("presents progress while reconnecting but not while offline", () => {
const reconnecting = workspaceState({
hasConnectingEnvironment: true,
hasReadyEnvironment: false,
connectingEnvironments: [
{
environmentId: "environment-1" as never,
environmentLabel: "Julius’s Mac mini",
displayUrl: "",
isRelayManaged: false,
connectionState: "reconnecting",
connectionError: null,
connectionErrorTraceId: null,
},
],
});
expect(workspaceConnectionStatusPresentation(reconnecting)).toEqual({
label: "Reconnecting to Julius’s Mac mini",
showsProgress: true,
});
const offline = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
expect(workspaceConnectionStatusPresentation(offline)).toEqual({
label: "You are offline",
showsProgress: false,
});
});
});
@@ -0,0 +1,56 @@
import { SymbolView } from "../../components/AppSymbol";
import { ActivityIndicator, Pressable } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { useThemeColor } from "../../lib/useThemeColor";
import type { WorkspaceState } from "../../state/workspaceModel";
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
export function WorkspaceConnectionStatus(props: {
readonly state: WorkspaceState;
readonly onPress: () => void;
readonly variant?: "floating" | "sidebar";
}) {
const iconColor = useThemeColor("--color-icon-muted");
const isSynchronizing =
props.state.networkStatus !== "offline" &&
props.state.connectionError === null &&
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
const variant = props.variant ?? "floating";
return (
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
accessibilityRole="button"
onPress={props.onPress}
className={
variant === "sidebar"
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
}
style={
variant === "floating"
? {
shadowColor: "#000",
shadowOffset: { width: 0, height: 10 },
shadowOpacity: 0.12,
shadowRadius: 24,
}
: undefined
}
>
{isSynchronizing ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
)}
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
{workspaceConnectionStatusLabel(props.state)}
</Text>
{variant === "sidebar" ? (
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
) : null}
</Pressable>
);
}
@@ -1,194 +0,0 @@
import type {
NativeStackHeaderItem,
NativeStackNavigationOptions,
} from "@react-navigation/native-stack";
import { useEffect, useRef, useState, type ReactNode } from "react";
import { ActivityIndicator, Animated, Platform, Pressable, View } from "react-native";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { brandTitleOffset, CompactBrandTitle } from "../../components/CompactBrandTitle";
import { useThemeColor } from "../../lib/useThemeColor";
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
import { useWorkspaceState } from "../../state/workspace";
import {
workspaceConnectionStatusPresentation,
type WorkspaceConnectionStatusPresentation,
} from "./workspace-connection-status";
/**
* Delay before a connection interruption surfaces in the title slot. Sub-second
* blips (the common reconnect case) resolve without any UI at all.
*/
const STATUS_SHOW_DELAY_MS = 800;
const FADE_IN_MS = 250;
/**
* Connection status presentation, debounced for display: null until the
* workspace has been in a non-connected state for STATUS_SHOW_DELAY_MS,
* then live-updating until the workspace reconnects (null again immediately).
*/
function useDelayedConnectionStatus(): WorkspaceConnectionStatusPresentation | null {
const { state } = useWorkspaceState();
const presentation = workspaceConnectionStatusPresentation(state);
const hasStatus = presentation !== null;
const [visible, setVisible] = useState(false);
useEffect(() => {
if (!hasStatus) {
setVisible(false);
return;
}
const timer = setTimeout(() => setVisible(true), STATUS_SHOW_DELAY_MS);
return () => clearTimeout(timer);
}, [hasStatus]);
return visible ? presentation : null;
}
/**
* One-shot entrance fade for the status label. Deliberately JS-driven: this can
* mount inside a native header item (RNSScreenStackHeaderSubview), where
* native-driver animated nodes blank the re-hosted view entirely. The JS driver
* updates opacity through the ordinary style path, which those subviews handle.
*/
function StatusFadeIn(props: { readonly children: ReactNode; readonly grow?: boolean }) {
const opacity = useRef(new Animated.Value(0)).current;
useEffect(() => {
const animation = Animated.timing(opacity, {
duration: FADE_IN_MS,
toValue: 1,
useNativeDriver: false,
});
animation.start();
return () => animation.stop();
}, [opacity]);
return (
<Animated.View
style={[
{ alignItems: "center", flexDirection: "row", opacity },
props.grow ? { flex: 1, minWidth: 0 } : null,
]}
>
{props.children}
</Animated.View>
);
}
/**
* Renders the brand/title slot of a thread-list surface, swapping the brand
* for the workspace connection status while an environment is unavailable.
*
* Both states occupy the same slot, so connection changes never shift the
* layout below. While connected the brand renders untouched — no wrapper —
* keeping the native header item on the exact element tree that predates the
* status swap. Replaces the old WorkspaceConnectionStatus pill, which inserted
* a row above the thread list.
*/
export function WorkspaceConnectionTitle(props: {
/** Content shown while connected (brand lockup or a screen title). */
readonly brand: ReactNode;
/** Opens environment settings. Status is not pressable when omitted. */
readonly onPress?: () => void;
/** Fill the available row width (in-flow headers) instead of hugging content (native title slots). */
readonly grow?: boolean;
readonly size?: "navbar" | "pageTitle";
/** Horizontal correction so the status aligns with the brand in native title slots. */
readonly statusOffset?: number;
}) {
const iconColor = String(useThemeColor("--color-icon-muted"));
const status = useDelayedConnectionStatus();
const size = props.size ?? "navbar";
if (status === null) {
return props.grow ? (
<View style={{ alignItems: "center", flex: 1, flexDirection: "row", minWidth: 0 }}>
{props.brand}
</View>
) : (
<>{props.brand}</>
);
}
return (
<StatusFadeIn grow={props.grow}>
<Pressable
accessibilityHint="Opens environment settings"
accessibilityLabel={status.label}
accessibilityRole="button"
disabled={props.onPress === undefined}
hitSlop={8}
onPress={props.onPress}
className="flex-row items-center gap-2"
style={{ marginLeft: props.statusOffset ?? 0 }}
>
{status.showsProgress ? (
<ActivityIndicator color={iconColor} size="small" />
) : (
<SymbolView
name="wifi.slash"
size={size === "pageTitle" ? 17 : 15}
tintColor={iconColor}
type="monochrome"
/>
)}
<Text
className={
size === "pageTitle"
? "text-[20px] font-t3-bold text-foreground-muted"
: "text-[16px] font-t3-bold text-foreground-muted"
}
numberOfLines={1}
style={{ flexShrink: 1 }}
>
{status.label}
</Text>
</Pressable>
</StatusFadeIn>
);
}
/**
* getCompactBrandHeaderOptions with the brand slot upgraded to the
* connection-status swap. Screens with an environment-settings callback apply
* this over the static brand options at mount.
*/
export function getConnectionAwareBrandHeaderOptions(opts: {
readonly onOpenEnvironments: () => void;
readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"];
}): NativeStackNavigationOptions {
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
return {
headerTitle: "Threads",
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
title: "Threads",
unstable_headerLeftItems: (): NativeStackHeaderItem[] => [
{
element: (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle nativeLeadingItem />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(true)}
/>
),
hidesSharedBackground: true,
type: "custom",
},
],
};
}
return {
headerTitle: () => (
<WorkspaceConnectionTitle
brand={<CompactBrandTitle />}
onPress={opts.onOpenEnvironments}
statusOffset={brandTitleOffset(false)}
/>
),
headerTitleStyle: opts.fallbackTitleStyle,
title: "Threads",
};
}
@@ -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", () => {
+63 -18
View File
@@ -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,22 +36,6 @@ function environmentSupportsPinning(environmentId: EnvironmentThreadShell["envir
);
}
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadPinReorder === true
);
}
function environmentSupportsTitleRegeneration(
environmentId: EnvironmentThreadShell["environmentId"],
) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadTitleRegeneration === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -232,22 +211,13 @@ 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>;
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -361,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);
@@ -419,126 +377,6 @@ export function useThreadListActions(): {
},
[unpinMutation],
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
titleRegenerationInFlightThreadKeys.current.has(key)
) {
return false;
}
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
Alert.alert(
"Could not regenerate title",
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
);
return false;
}
titleRegenerationInFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not regenerate title",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread title could not be regenerated.",
);
return false;
}
return true;
} finally {
titleRegenerationInFlightThreadKeys.current.delete(key);
}
},
[updateThreadMetadata],
);
// 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);
@@ -551,8 +389,6 @@ export function useThreadListActions(): {
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -1,11 +1,5 @@
import type { WorkspaceState } from "../../state/workspaceModel";
export interface WorkspaceConnectionStatusPresentation {
readonly label: string;
/** True while actively working (connecting/syncing) — render a spinner. False for offline/error/idle states — render a wifi-slash icon. */
readonly showsProgress: boolean;
}
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
return (
state.networkStatus === "offline" ||
@@ -30,17 +24,3 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
}
return "Not connected";
}
/** Header-title presentation of the connection state, or null while connected. */
export function workspaceConnectionStatusPresentation(
state: WorkspaceState,
): WorkspaceConnectionStatusPresentation | null {
if (!shouldShowWorkspaceConnectionStatus(state)) return null;
return {
label: workspaceConnectionStatusLabel(state),
showsProgress:
state.networkStatus !== "offline" &&
state.connectionError === null &&
(state.connectingEnvironments.length > 0 || state.hasPendingShellSnapshot),
};
}
@@ -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,
)}
/>
);
}
@@ -429,19 +423,13 @@ function AdaptiveWorkspaceLayoutContent(
);
const handleOpenSettings = useCallback(() => {
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
});
navigation.navigate("SettingsSheet", { screen: "Settings" });
}, [navigation]);
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
const handleOpenEnvironmentSettings = useCallback(() => {
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
});
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
}, [navigation]);
const handleNewThreadInProject = useCallback(
@@ -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}
@@ -1,7 +1,8 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useLayoutEffect } from "react";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useEffect } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -9,9 +10,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
export function SettingsAuthRouteScreen() {
const navigation = useNavigation();
useLayoutEffect(() => {
useEffect(() => {
if (!hasCloudPublicConfig()) {
navigation.dispatch(StackActions.replace("SettingsContent"));
navigation.dispatch(StackActions.replace("Settings"));
}
}, [navigation]);
@@ -20,21 +21,19 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
const handleHostBack = useCallback(
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
[navigation],
);
return (
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
)
) : null}
</View>
<>
<NativeStackScreenOptions options={{ title: isSignedIn ? "Account" : "Sign in" }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} />
) : (
<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";
@@ -98,10 +99,7 @@ export function SettingsEnvironmentsRouteScreen() {
accessibilityLabel: "Add environment",
icon: "plus",
onPress: () =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
}),
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
},
]}
/>
@@ -111,10 +109,7 @@ export function SettingsEnvironmentsRouteScreen() {
<NativeHeaderToolbar.Button
icon="plus"
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
}
separateBackground
tintColor={headerIconColor}
@@ -166,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>
);
}
@@ -2,6 +2,7 @@ import { useAuth, useUser } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Updates from "expo-updates";
import { useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "../../components/AppSymbol";
@@ -29,6 +30,7 @@ import {
subscribeAgentAwarenessRegistrationStatus,
} from "../agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
@@ -38,7 +40,6 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
@@ -130,7 +131,7 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<LegacySettingsSection />
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
@@ -146,6 +147,7 @@ function ConfiguredSettingsRouteScreen() {
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useSavedRemoteConnections();
@@ -434,8 +436,14 @@ function ConfiguredSettingsRouteScreen() {
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
return;
}
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
}, [isLoaded, navigation]);
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -511,7 +519,7 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<LegacySettingsSection />
<BetaSettingsSection />
<ArchivedThreadsSettingsSection />
@@ -522,36 +530,45 @@ 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" />
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
<SettingsSwitchRow
icon="folder"
label="Project Grouping"
value={projectGroupingEnabled}
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
/>
</SettingsSection>
);
}
/**
* Device-local legacy toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → General → Legacy features backed by
* mobile preferences.
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
*/
function LegacySettingsSection() {
function BetaSettingsSection() {
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
return (
<View className="gap-3">
<SettingsSection title="Legacy">
<SettingsSection title="Beta">
<SettingsSwitchRow
icon="sidebar.left"
label="Legacy Thread List"
value={!threadListV2Enabled}
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
Brings back the original grouped thread list. The default list is flat, in creation order:
active work renders as cards; settled threads collapse to compact rows.
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
</Text>
</View>
);
@@ -569,7 +586,6 @@ function AppSettingsSection() {
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
const updateCheckAvailable = isAppUpdateCheckAvailable();
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
@@ -597,13 +613,13 @@ function AppSettingsSection() {
}, []);
const handleVersionPress = useCallback(() => {
if (!updateCheckAvailable || updateInFlight.current) return;
if (!Updates.isEnabled || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate, updateCheckAvailable]);
}, [checkForUpdate]);
const statusLabel =
updateState === "checking"
@@ -639,7 +655,7 @@ function AppSettingsSection() {
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{updateCheckAvailable ? (
{Updates.isEnabled ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
@@ -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>
);
@@ -64,8 +64,7 @@ export function SettingsRow(props: {
disabled={props.disabled}
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: target },
screen: target,
})
}
>
@@ -2,8 +2,6 @@ export type SettingsSheetTarget =
| "SettingsEnvironments"
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage"
| "SettingsUsage";
| "SettingsClientStorage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -1,12 +1,6 @@
import { useEffect, useRef, useState } from "react";
import { Keyboard, View } from "react-native";
import {
CommonActions,
type NavigationState,
type PartialState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useConnectionController } from "../connection/useConnectionController";
@@ -31,8 +25,6 @@ import { retryShowcaseOperation } from "./showcaseRetry";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const SHOWCASE_THREAD_ID = "remote-command-center";
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
function sceneFromPathname(pathname: string): ShowcaseScene | null {
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
@@ -174,21 +166,17 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
navigation.dispatch(StackActions.popToTop());
return;
}
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
const routes: Array<{
name: string;
params?: Record<string, unknown>;
state?: { index: number; routes: Array<{ name: string }> };
}> = [{ name: "Home" }];
if (requestedScene === "environments") {
routes.push({
name: "SettingsSheet",
state: {
index: 0,
routes: [
{
name: "SettingsContent",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
},
],
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
});
} else {
@@ -2,11 +2,7 @@ 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 {
KeyboardAvoidingView,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
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";
@@ -29,12 +25,15 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ComposerSurface } from "./ThreadComposer";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
@@ -44,14 +43,13 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
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: {
@@ -91,7 +89,7 @@ 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,
@@ -104,10 +102,6 @@ export function NewTaskDraftScreen(props: {
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
});
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
@@ -283,25 +277,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,
]);
@@ -526,15 +519,7 @@ export function NewTaskDraftScreen(props: {
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => {
// The delayed focus can land after the settings sheet opened, which
// would pop the keyboard underneath its modal.
if (!settingsSheetPresentation.isActiveRef.current) {
promptInputRef.current?.focus();
} else {
settingsSheetPresentation.restoreFocusAfterSave();
}
});
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
});
return () => {
@@ -543,11 +528,7 @@ export function NewTaskDraftScreen(props: {
cancelAnimationFrame(focusFrame);
}
};
}, [
selectedProject,
settingsSheetPresentation.isActiveRef,
settingsSheetPresentation.restoreFocusAfterSave,
]);
}, [selectedProject]);
const environmentMenuActions = useMemo(
() =>
@@ -561,6 +542,10 @@ export function NewTaskDraftScreen(props: {
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
@@ -570,6 +555,54 @@ export function NewTaskDraftScreen(props: {
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
flow.runtimeMode === "approval-required"
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: flow.runtimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: flow.interactionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
@@ -640,12 +673,10 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: flow.selectedModelOption?.label ?? "Model",
optionDescriptors: providerOptionDescriptors,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
});
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
@@ -655,6 +686,13 @@ export function NewTaskDraftScreen(props: {
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
@@ -662,6 +700,28 @@ export function NewTaskDraftScreen(props: {
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
return;
}
if (event.startsWith("options:runtime:")) {
flow.setRuntimeMode(
event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
);
return;
}
if (event.startsWith("options:interaction:")) {
flow.setInteractionMode(
event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
);
}
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
@@ -868,9 +928,7 @@ export function NewTaskDraftScreen(props: {
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
// The settings sheet dismisses the keyboard, so its flag keeps the Android
// draft composer expanded through the blur (mirrors ThreadComposer).
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
const isExpanded = !isAndroid || isComposerFocused;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -924,14 +982,28 @@ export function NewTaskDraftScreen(props: {
showChevron={false}
disabled={isIncomingShareTransferPending}
/>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
@@ -957,21 +1029,6 @@ export function NewTaskDraftScreen(props: {
</>
);
const settingsSheet = (
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={flow.providerGroups}
selectedModel={flow.selectedModel}
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={flow.setSelectedModelOptions}
runtimeMode={flow.runtimeMode}
onUpdateRuntimeMode={flow.setRuntimeMode}
/>
);
const startButton = (
<ComposerToolbarButton
accessibilityLabel={
@@ -989,29 +1046,14 @@ export function NewTaskDraftScreen(props: {
// 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).
//
// Composer positioning mirrors ThreadDetailScreen's floating overlay
// (KeyboardStickyView, absolute bottom overlay) rather than
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
// resolves the composer's on-screen frame via a native
// viewPositionInWindow measurement, which this app's Android
// edge-to-edge setup (KeyboardProvider's native content-view margin
// handling neutralizes windowSoftInputMode="adjustResize" while active)
// makes unreliable — the composer stayed under the keyboard instead of
// translating above it. KeyboardStickyView sticks directly to the
// animated keyboard height instead, sidestepping that measurement.
return (
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
<View className="flex-1" />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="flex-1" />
<KeyboardStickyView
enabled={isKeyboardVisible}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
className="px-4 pt-2"
style={{
@@ -1075,8 +1117,7 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
) : null}
</View>
</KeyboardStickyView>
{settingsSheet}
</KeyboardAvoidingView>
</View>
);
}
@@ -1110,7 +1151,6 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
</View>
</KeyboardAvoidingView>
{settingsSheet}
</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,91 +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}
faviconPath={scope.representative.faviconPath}
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}
faviconPath={project.faviconPath}
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>
@@ -14,10 +14,8 @@ export interface PendingApprovalCardProps {
}
export function PendingApprovalCard(props: PendingApprovalCardProps) {
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
// behind this card, so a translucent surface bleeds messages through it.
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">
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
Approval needed
</Text>
@@ -1,64 +1,18 @@
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
import { useCallback, useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
Easing,
FadeInUp,
FadeOutDown,
LinearTransition,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ControlPill } from "../../components/ControlPill";
import { cn } from "../../lib/cn";
import { useThemeColor } from "../../lib/useThemeColor";
import {
isPendingUserInputOptionSelected,
type PendingUserInput,
type PendingUserInputDraftAnswer,
} from "../../lib/threadActivity";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
/**
* Constant while a request is pending (it reserves keyboard space), so the
* keyboard transition is pure translation; changes only on rare discrete
* corrections, which the layout transition smooths.
*/
readonly maxHeight: number;
readonly collapsed: boolean;
readonly onToggleCollapsed: () => void;
/** Renders a stop control on the collapsed bar, which replaces the composer. */
readonly onStopThread?: () => void;
/**
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
* collapsed bar (inside a clipping window) on the UI thread; the host
* animates it directly from the tap handler so the card and the feed
* inset glide start the same frame.
*/
readonly cardProgress?: SharedValue<number>;
/**
* Receives how far the expanded card extends above the bar footprint
* (written from onLayout with no re-render); the host adds it to the
* thread feed's end inset so the end of the chat stays visible above the
* card.
*/
readonly cardCoverage?: SharedValue<number>;
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly answers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
questionId: string,
label: string,
) => void;
readonly onChangeCustomAnswer: (
@@ -69,242 +23,71 @@ export interface PendingUserInputCardProps {
readonly onSubmit: () => Promise<unknown>;
}
/**
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
* card is an absolutely-positioned overlay rising above it. The overlay's
* measured height (which drives the thread feed's bottom inset) therefore
* never changes on collapse/expand, so the transcript stays perfectly still
* while the card animates over it.
*
* Android cannot use the overlay: it does not hit-test touches outside a
* parent's bounds, which made everything above the bar-sized wrapper
* untouchable. There the expanded card renders in-flow instead (the wrapper
* grows with it, and the host skips the coverage inset since the measured
* overlay already includes the card).
*/
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const iconSubtle = useThemeColor("--color-icon-subtle");
const questionCount = props.pendingUserInput.questions.length;
const cardCoverage = props.cardCoverage;
const barHeightRef = useRef(0);
const cardHeightRef = useRef(0);
// Measured card height, written straight from onLayout: the collapse slide
// distance. Not animated — it only changes on discrete relayouts.
const cardHeight = useSharedValue(0);
const notifyCoverage = useCallback(() => {
if (!cardCoverage) {
return;
}
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
if (coverage === cardCoverage.value) {
return;
}
if (cardCoverage.value === 0) {
// First measurement lands while the list is doing its initial
// end-pin (thread opened onto a pending request); animating it from
// zero would move the end anchor out from under that scroll.
cardCoverage.value = coverage;
return;
}
// Animated so a coverage change at rest (discrete max-height
// corrections) glides the feed instead of stepping it; toggle timing is
// owned by the host's progress values.
cardCoverage.value = withTiming(coverage, {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
});
}, [cardCoverage]);
const handleBarLayout = useCallback(
(event: LayoutChangeEvent) => {
barHeightRef.current = event.nativeEvent.layout.height;
notifyCoverage();
},
[notifyCoverage],
);
const handleCardLayout = useCallback(
(event: LayoutChangeEvent) => {
cardHeightRef.current = event.nativeEvent.layout.height;
cardHeight.value = event.nativeEvent.layout.height;
notifyCoverage();
},
[cardHeight, notifyCoverage],
);
const cardProgress = props.cardProgress;
// No opacity: fading an opaque card over the live transcript reads as a
// crossfade (card text, transcript, and bar all half-visible at once).
// Instead the card stays opaque and slides its full height down past the
// clipping window's bottom edge, so the transcript is only revealed where
// the card has physically left.
const cardAnimatedStyle = useAnimatedStyle(() => {
const progress = cardProgress === undefined ? 1 : cardProgress.value;
return {
transform: [{ translateY: (1 - progress) * cardHeight.value }],
};
});
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
// style): expanding animates existing views on the UI thread the same
// frame the host starts the progress timing, instead of paying a React
// mount + layout before anything moves.
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
// The bar renders UNDER the card (earlier in JSX), always opaque: while
// expanded the opaque card covers it, and during the collapse slide the
// card's top edge wipes past and reveals it — no opacity handoff, so no
// crossfade frames.
const bar = showBar ? (
<View
onLayout={handleBarLayout}
pointerEvents={props.collapsed ? "auto" : "none"}
accessibilityElementsHidden={!props.collapsed}
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Expand user input, ${questionCount} question${
questionCount === 1 ? "" : "s"
}`}
onPress={props.onToggleCollapsed}
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
>
<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-sans text-xs text-neutral-500 dark:text-neutral-400">
{questionCount} question{questionCount === 1 ? "" : "s"}
</Text>
<View className="flex-1" />
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
{props.onStopThread ? (
<ControlPill
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
className="h-9 w-9"
onPress={props.onStopThread}
/>
) : null}
</View>
) : null;
const card = renderCard ? (
// 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.
<Animated.View
onLayout={handleCardLayout}
pointerEvents={props.collapsed ? "none" : "auto"}
accessibilityElementsHidden={props.collapsed}
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
entering={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
exiting={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
layout={CARD_LAYOUT_TRANSITION}
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
style={
EXPANDED_CARD_IS_OVERLAY
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
: { maxHeight: props.maxHeight }
}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Collapse user input"
onPress={props.onToggleCollapsed}
className="flex-row items-start gap-2"
>
<View className="flex-1 gap-2.5">
<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>
</View>
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
</View>
</Pressable>
<ScrollView
bounces={false}
className="min-h-0"
contentContainerClassName="gap-2.5 pb-1"
keyboardShouldPersistTaps="handled"
nestedScrollEnabled
showsVerticalScrollIndicator
style={{ flexShrink: 1 }}
>
{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 = isPendingUserInputOptionSelected(draft, option.label);
return (
<Pressable
key={option.label}
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
<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(
"rounded-full border px-3 py-2.5 ",
"font-t3-bold text-sm",
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",
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question,
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)
}
onFocus={() => props.onInputFocusChange?.(true)}
onBlur={() => props.onInputFocusChange?.(false)}
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"
/>
{option.label}
</Text>
</Pressable>
);
})}
</View>
);
})}
</ScrollView>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
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",
@@ -317,26 +100,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</Animated.View>
) : null;
return (
<View className="relative">
{bar}
{EXPANDED_CARD_IS_OVERLAY ? (
// Clipping window for the collapse slide: same footprint as the
// expanded card, bottom edge on the bar's bottom edge. The sliding
// card exits through the bottom edge instead of drawing over the
// composer area, wiping the bar (and the transcript) into view.
<View
pointerEvents={props.collapsed ? "none" : "box-none"}
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
style={{ height: props.maxHeight }}
>
{card}
</View>
) : (
card
)}
</View>
);
}
@@ -14,7 +14,6 @@ import {
serializeComposerFileLink,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import * as Haptics from "expo-haptics";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
@@ -22,7 +21,6 @@ import {
Image,
Platform,
Pressable,
StyleSheet,
useColorScheme,
View,
type ViewStyle,
@@ -55,7 +53,7 @@ import {
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -64,14 +62,13 @@ import {
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
applyProviderOptionSelection,
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { buildThreadSettingsMenu } from "./thread-settings-menu";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
@@ -118,8 +115,6 @@ export interface ThreadComposerProps {
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void;
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
readonly onEditorFocusChange?: (focused: boolean) => void;
}
/**
@@ -277,28 +272,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const fallbackInputRef = useRef<ComposerEditorHandle>(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
isEditorFocused: isFocused,
});
const wasExpandedBeforePreviewRef = useRef(false);
const inFlightThreadIdsRef = useRef(new Set<string>());
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
// Opening and closing count as active so the composer stays expanded while
// focus moves between its native editor and the settings modal.
const isExpanded = isFocused || settingsSheetPresentation.isActive;
const isExpanded = isFocused;
const canSend = hasContent;
// Notify the parent from the derived value, not focus events: the parent
// sizes the feed inset from this, and blur-during-sheet would otherwise
// report collapsed while the composer still renders expanded.
useEffect(() => {
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
@@ -314,16 +296,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
}, [inputRef]);
const onEditorFocusChange = props.onEditorFocusChange;
const handleFocus = useCallback(() => {
setIsFocused(true);
onEditorFocusChange?.(true);
}, [onEditorFocusChange]);
onExpandedChange?.(true);
}, [onExpandedChange]);
const handleBlur = useCallback(() => {
setIsFocused(false);
onEditorFocusChange?.(false);
}, [onEditorFocusChange]);
onExpandedChange?.(false);
}, [onExpandedChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
@@ -606,12 +587,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[props.serverConfig, currentModelSelection],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
// An existing thread is bound to its harness: sessions can't move between
// provider instances, so the picker only offers the thread's own group.
const threadProviderGroups = useMemo(
() => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
[providerGroups, currentModelSelection.instanceId],
);
const currentModelOption =
modelOptions.find(
(option) =>
@@ -626,68 +601,96 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
interactionMode: currentInteractionMode,
});
// iOS gets a native menu on the trigger pill: the everyday adjustments
// apply without resigning the keyboard, while "All Settings…" (and the
// Android trigger) still route through the sheet, which must dismiss it.
const settingsMenu = useMemo(
() =>
Platform.OS === "ios"
? buildThreadSettingsMenu({
providerGroups: threadProviderGroups,
selectedModel: currentModelSelection,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
})
: null,
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
);
const onUpdateModelSelection = props.onUpdateModelSelection;
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
const handleSettingsMenuAction = useCallback(
(eventId: string) => {
const event = settingsMenu?.events.get(eventId);
if (!event) {
return;
}
switch (event.type) {
case "select-model":
void Haptics.selectionAsync();
onUpdateModelSelection(event.option.selection);
return;
case "set-option": {
const options = applyProviderOptionSelection(providerOptionDescriptors, {
id: event.optionId,
value: event.value,
});
if (options) {
void Haptics.selectionAsync();
onUpdateModelSelection({ ...currentModelSelection, options });
}
return;
}
case "set-runtime":
void Haptics.selectionAsync();
onUpdateRuntimeMode(event.mode);
return;
}
},
[
currentModelSelection,
onUpdateModelSelection,
onUpdateRuntimeMode,
providerOptionDescriptors,
settingsMenu,
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
currentRuntimeMode === "approval-required"
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: currentRuntimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: currentInteractionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
props.onUpdateInteractionMode(interactionMode);
}
}
return (
<Animated.View
className="px-4"
@@ -695,22 +698,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
style={{
paddingTop: isExpanded ? 8 : 6,
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
}}
>
{/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
silently drops experimental_backgroundImage on Android, which left this
strip fully transparent and the feed text legible through the composer. */}
<View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{
experimental_backgroundImage: isDarkMode
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
},
]}
/>
<Animated.View
className="relative w-full self-center"
layout={COMPOSER_LAYOUT_TRANSITION}
@@ -857,31 +849,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
{settingsMenu ? (
<ControlPillMenu
actions={settingsMenu.actions}
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
/>
</ControlPillMenu>
) : (
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
accessibilityLabel="Model"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
label={currentModelOption?.label ?? currentModelSelection.model}
/>
)}
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -915,21 +904,6 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</Animated.View>
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={threadProviderGroups}
selectedModel={currentModelSelection}
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={(options) =>
props.onUpdateModelSelection({ ...currentModelSelection, options })
}
runtimeMode={currentRuntimeMode}
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
/>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
@@ -2,7 +2,6 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
ApprovalRequestId,
EnvironmentId,
@@ -14,45 +13,14 @@ import type {
RuntimeMode,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import {
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import {
AppState,
Keyboard,
Platform,
useColorScheme,
useWindowDimensions,
View,
type GestureResponderEvent,
} from "react-native";
import {
KeyboardController,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import Animated, {
Easing,
FadeInDown,
FadeOut,
useAnimatedReaction,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPill } from "../../components/ControlPill";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
@@ -66,11 +34,6 @@ import type {
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
import {
derivePendingUserInputMaxHeight,
ESTIMATED_KEYBOARD_HEIGHT,
USER_INPUT_TOGGLE_DURATION_MS,
} from "./pendingUserInputLayout";
import {
COMPOSER_COLLAPSED_CHROME,
COMPOSER_EXPANDED_CHROME,
@@ -91,15 +54,13 @@ export interface ThreadDetailScreenProps {
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: EnvironmentConnectionPhase;
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
readonly activeThreadBusy: boolean;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
@@ -126,7 +87,7 @@ export interface ThreadDetailScreenProps {
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
question: UserInputQuestion,
questionId: string,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
@@ -208,48 +169,8 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
const USER_INPUT_TOGGLE_TIMING = {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
};
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const liveKeyboardHeight = useKeyboardState((state) => state.height);
// Android can swallow the IME hide callbacks when the app is backgrounded
// mid keyboard-hide (the reported repro: send — which blurs and starts the
// hide — then Home within a second). The keyboard library's height AND
// visibility then stay frozen open, so gating the sticky translation on
// visibility alone still strands the composer after resume. Quarantine the
// translation on every Android resume instead; any sign of a live keyboard
// stream — an owned input gaining focus, or any visibility/height movement —
// lifts it. A healthy resume sees no visual difference (the translation is
// already zero while the keyboard is closed).
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
useEffect(() => {
if (Platform.OS !== "android") {
return;
}
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") {
setKeyboardStateSuspect(true);
}
});
return () => {
subscription.remove();
};
}, []);
useEffect(() => {
setKeyboardStateSuspect(false);
}, [isKeyboardVisible, liveKeyboardHeight]);
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
if (focused) {
setKeyboardStateSuspect(false);
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -260,17 +181,7 @@ 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 [endFollowEnabled, setEndFollowEnabled] = useState(true);
// Android keys the safe-area padding on keyboard visibility (#5988): the
// back gesture closes the keyboard while the editor stays focused, and a
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
// NOT use visibility — it only flips on keyboardDidHide, after the hide
// animation, so the composer would ride down flush to the screen edge and
// then snap up into the inset. On iOS blur precedes the hide, so the
// focus-keyed inset is already in place while the composer rides down.
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
? 0
: Math.max(insets.bottom, 12);
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
// not. Whether messages are already on screen decides the pill label: no
@@ -291,41 +202,6 @@ 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;
// While a user-input request is pending, the questionnaire owns the
// composer slot outright: expanded it is the full card, collapsed it is a
// composer-style bar in the same place (with its own stop control). The
// composer never mounts into the transition, which keeps the collapse and
// keyboard animations coherent. Collapse state is keyed by request id so a
// new request re-expands automatically.
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<ApprovalRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
// The card's height RESERVES keyboard space at all times instead of
// tracking the keyboard: transforms (the sticky translation) apply
// same-frame on the UI thread while layout props lag a Yoga pass behind,
// so any height that follows the keyboard flashes the card over the nav
// header on the way up. With a constant height the keyboard transition is
// pure translation — frame-perfect by construction — and the resting card
// stays compact over the transcript. Before the first open the reserve is
// an estimate; once a real height is known the card corrects once,
// discretely.
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
useEffect(() => {
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
setLastKnownKeyboardHeight(liveKeyboardHeight);
}
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
windowHeight,
keyboardHeight:
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
navigationHeaderHeight,
// The questionnaire owns the composer slot, so only the composer's
// bottom inset still overlaps.
composerOverlapHeight: composerBottomInset,
});
const estimatedOverlayHeight = composerOverlapHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
@@ -342,103 +218,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
-nativeInsetOvercount,
);
// The expanded questionnaire is an absolute overlay on iOS, so it never
// changes the measured overlay height (that constancy is what keeps the
// feed from snapping on collapse/expand). The toggle choreography runs on
// SHARED VALUES set directly in the tap handler — one JS hop, then the
// card's rise/sink and the feed's end-inset glide animate in lockstep on
// the UI thread, keyboard-style, instead of waiting on React mount +
// onLayout + state round trips. Coverage (how far the card extends above
// the bar) is measured straight into a shared value by the card's
// onLayout, with no re-render.
const userInputCardProgress = useSharedValue(1);
const userInputInsetProgress = useSharedValue(1);
const userInputCardCoverage = useSharedValue(0);
// Android renders the expanded card in-flow (it cannot hit-test the iOS
// overlay outside the bar's bounds), so its measured overlay height already
// includes the card — the coverage extra is iOS-only.
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
const combinedContentInsetEndAdjustment = useSharedValue(
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
);
useAnimatedReaction(
() =>
contentInsetEndAdjustment.value +
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
(value) => {
combinedContentInsetEndAdjustment.value = value;
},
[userInputCoverageApplies],
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const endFollowEnabledRef = useRef(true);
endFollowEnabledRef.current = endFollowEnabled;
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// The list's own corrections for these inset changes drift on short
// content (and the error compounds across toggles), so deterministically
// re-pin the end once a toggle settles: a no-op when the resting position
// is already right, corrective when it is not. Follow state is re-checked
// inside the callback — the user may grab the list during the settle
// window, and yanking them back would override a live gesture.
const scheduleUserInputRepin = useCallback(
(delayMs: number) => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
userInputRepinTimerRef.current = setTimeout(() => {
userInputRepinTimerRef.current = null;
if (!endFollowEnabledRef.current) {
return;
}
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, delayMs);
},
[freeze, scrollMessageToEnd],
);
useEffect(
() => () => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
},
[],
);
const handleToggleUserInputCollapsed = useCallback(() => {
if (activeUserInputRequestId === null) {
return;
}
if (userInputCollapsed) {
// Expanding: card and feed glide start NOW, on the UI thread.
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
setCollapsedUserInputRequestId(null);
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
// Collapsing hides the custom-answer inputs; release the keyboard with
// them instead of leaving it up over a dead responder.
Keyboard.dismiss();
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
// Instant: the sinking card still covers the strip being revealed, and
// animating the inset downward is what drifted the short-content end
// anchor.
userInputInsetProgress.value = 0;
setCollapsedUserInputRequestId(activeUserInputRequestId);
scheduleUserInputRepin(60);
}
}, [
activeUserInputRequestId,
scheduleUserInputRepin,
userInputCardProgress,
userInputCollapsed,
userInputInsetProgress,
]);
useEffect(() => {
// A new request always arrives expanded.
userInputCardProgress.value = 1;
userInputInsetProgress.value = 1;
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
@@ -459,7 +239,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);
@@ -531,16 +310,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
composerEditorRef.current?.blur();
}, []);
const handleScrollToEnd = useCallback(() => {
void Haptics.selectionAsync();
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, [freeze, scrollMessageToEnd]);
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
const isDarkMode = useColorScheme() === "dark";
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
feedTouchStartRef.current = {
pageX: event.nativeEvent.pageX,
@@ -594,16 +363,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
) : (
@@ -613,10 +380,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
// The animated keyboard height can remain stale after a dismissed
// IME on both platforms. Visibility is the authoritative closed
// state, so disable the translation rather than stranding the pill.
enabled={isKeyboardVisible && !keyboardStateSuspect}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
@@ -624,60 +387,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
{showScrollToEndButton ? (
<Animated.View
pointerEvents="box-none"
className="absolute -top-11 left-0 right-0 z-20 items-center"
entering={FadeInDown.duration(160)}
exiting={FadeOut.duration(100)}
>
{isLiquidGlassSupported ? (
<LiquidGlassView
colorScheme={isDarkMode ? "dark" : "light"}
effect="regular"
interactive
// Interactive glass can render larger than the requested
// box (minimum touch size), so center the pill instead of
// relying on it filling the glass exactly.
style={{
alignItems: "center",
borderRadius: 18,
height: 36,
justifyContent: "center",
overflow: "hidden",
width: 36,
}}
>
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 bg-transparent"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
</LiquidGlassView>
) : (
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
)}
</Animated.View>
) : null}
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
// The questionnaire replaces the composer, so it must pad
// the home indicator the composer normally covers.
style={
activeUserInputRequestId !== null
? { paddingBottom: composerBottomInset }
: undefined
}
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
@@ -691,13 +404,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
maxHeight={pendingUserInputMaxHeight}
collapsed={userInputCollapsed}
onToggleCollapsed={handleToggleUserInputCollapsed}
onStopThread={props.onStopThread}
cardProgress={userInputCardProgress}
cardCoverage={userInputCardCoverage}
onInputFocusChange={handleOwnedInputFocusChange}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
@@ -710,40 +416,35 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>
{/* Hidden (not unmounted) while a user-input request owns the
composer slot, so composer drafts and editor state survive. */}
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
<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}
onEditorFocusChange={handleOwnedInputFocusChange}
/>
</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}
/>
</View>
</KeyboardStickyView>
) : null}
+58 -163
View File
@@ -45,12 +45,17 @@ 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 { scopedThreadKey } from "../../lib/scopedEntities";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -90,10 +95,6 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
resolveThreadFeedLiveFollow,
type ThreadFeedLiveFollowEvent,
} from "./thread-feed-live-follow";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
@@ -104,10 +105,6 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -120,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),
@@ -158,13 +163,7 @@ export interface ThreadFeedProps {
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
readonly loading: boolean;
readonly onLoadEarlier: () => void;
} | null;
}
function MessageAttachmentImage(props: {
@@ -887,12 +886,6 @@ function renderFeedEntry(
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
const attachments = message.attachments ?? [];
const hasReviewCommentContext = message.text.includes("<review_comment");
// A bubble that sizes itself from its content cannot lay out a block whose
// intrinsic width overflows `maxWidth`: Android positions the bubble's
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -915,11 +908,7 @@ function renderFeedEntry(
style={{
backgroundColor: userBubbleColor,
maxWidth: props.userBubbleMaxWidth,
...(hasReviewCommentContext
? { width: props.reviewCommentBubbleWidth }
: hasWideBlock
? { width: props.userBubbleMaxWidth }
: null),
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
}}
>
{message.text.trim().length > 0 ? (
@@ -1334,7 +1323,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
@@ -1342,34 +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);
props.onEndFollowEnabledChange?.(enabled);
},
[props.onEndFollowEnabledChange],
);
const transitionEndFollow = useCallback(
(event: ThreadFeedLiveFollowEvent) => {
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
},
[setEndFollow],
);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1474,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
@@ -1481,73 +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);
// LegendList recomputes its inset-aware end distance before invoking
// this handler, so getState() is current. Only the actual end re-arms
// follow: its broader maintain-scroll threshold is large enough for a
// streaming chunk to pull a user back before their upward drag escapes.
// A live user-scroll session still wins even if the first scroll event
// remains inside LegendList's at-end tolerance.
const listState = props.listRef.current?.getState();
if (listState) {
transitionEndFollow({
type: "scroll",
isAtEnd: listState.isAtEnd,
userScrollSessionActive: userScrollSessionRef.current,
});
}
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
nearListEnd.value =
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
},
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
);
const clearUserScrollSettle = useCallback(() => {
if (userScrollSettleTimerRef.current !== null) {
clearTimeout(userScrollSettleTimerRef.current);
userScrollSettleTimerRef.current = null;
}
}, []);
const handleScrollBeginDrag = useCallback(() => {
clearUserScrollSettle();
userScrollSessionRef.current = true;
// Pause before the first scroll event. Otherwise a stream update can run
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
transitionEndFollow({ type: "user-scroll-begin" });
}, [clearUserScrollSettle, transitionEndFollow]);
const finishUserScroll = useCallback(
(releaseIsAtEnd?: boolean) => {
clearUserScrollSettle();
const userScrollSessionActive = userScrollSessionRef.current;
userScrollSessionRef.current = false;
transitionEndFollow({
type: "user-scroll-end",
// With no momentum, preserve the finger-release position. Streaming
// growth during the native momentum-detection window must not turn a
// release at the live edge into an opt-out from follow.
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
userScrollSessionActive,
});
},
[clearUserScrollSettle, props.listRef, transitionEndFollow],
);
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
// can report zero and still decelerate. Give native momentum a short window
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
// and the session survives until the settled momentum-end position. This
// mirrors the native-event handoff used by the home thread list's scroll gate.
const handleScrollEndDrag = useCallback(() => {
clearUserScrollSettle();
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
const handleMomentumScrollBegin = useCallback(() => {
if (userScrollSessionRef.current) {
clearUserScrollSettle();
}
}, [clearUserScrollSettle]);
const handleMomentumScrollEnd = useCallback(() => {
finishUserScroll();
}, [finishUserScroll]);
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
// 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);
@@ -1555,30 +1487,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
// Thread identity is env-scoped: two environments can hold the same
// ThreadId, and keying resets (or the list mount) on the bare id would
// carry stale scroll/follow state across an environment switch.
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [feedThreadKey, reportHeaderMaterialVisibility]);
// A thread switch opens pinned to the end; a send explicitly returns to the
// live edge (ThreadDetailScreen scrolls the new message into place). Both
// re-arm follow regardless of where the user had scrolled before.
useEffect(() => {
clearUserScrollSettle();
userScrollSessionRef.current = false;
transitionEndFollow({ type: "reset" });
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
clearUserScrollSettle();
userScrollSessionRef.current = false;
transitionEndFollow({ type: "reset" });
}
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
}, [props.threadId, reportHeaderMaterialVisibility]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
@@ -1614,7 +1525,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// initial scroll-to-end computes with a zero end inset and rests one
// composer-height short of the end. Layout effect: it must land before the
// list's first positioning tick or the one-shot initial scroll misses it.
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
@@ -1906,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
@@ -1930,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,
@@ -1979,26 +1891,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
alignItemsAtEnd
initialScrollAtEnd
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onMomentumScrollBegin={handleMomentumScrollBegin}
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,8 +207,6 @@ function ThreadNavigationSidebarPane(
unsettleThread,
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -497,37 +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]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === 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 {
@@ -636,6 +600,7 @@ function ThreadNavigationSidebarPane(
threadListV2Enabled,
threadListV2Layout,
]);
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
const listMenuActions = useMemo<MenuAction[]>(
() => [
{
@@ -960,26 +925,15 @@ function ThreadNavigationSidebarPane(
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
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}
@@ -1079,8 +1033,6 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1102,22 +1054,18 @@ function ThreadNavigationSidebarPane(
},
[
archiveThread,
arrangedPinnedKeys,
confirmDeletePendingTask,
confirmDeleteThread,
handleChangeRequestState,
handleSelectThread,
handleSwipeableClose,
handleSwipeableWillOpen,
movePinnedThread,
openPendingTask,
pinReorderEnvironmentIds,
pinThread,
pinningEnvironmentIds,
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1125,7 +1073,6 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -1206,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",
@@ -1263,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>
@@ -1353,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
@@ -1394,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,10 +8,6 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import * as Option from "effect/Option";
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
import {
requestOlderThreadTurns,
threadHasOlderTurns,
} from "@t3tools/client-runtime/state/threads";
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
import { Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
@@ -194,20 +190,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();
@@ -784,7 +766,6 @@ function ThreadRouteContent(
draftAttachments={composer.draftAttachments}
connectionStateLabel={routeConnectionState}
threadSyncStatus={selectedThreadDetailState.status}
loadEarlier={loadEarlierTurns}
activeThreadBusy={composer.activeThreadBusy}
environmentId={selectedThread.environmentId}
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
@@ -1,652 +0,0 @@
import type {
ModelSelection,
ProviderInteractionMode,
ProviderOptionDescriptor,
ProviderOptionSelection,
RuntimeMode,
} from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import * as Haptics from "expo-haptics";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Modal,
Platform,
Pressable,
ScrollView,
Switch,
useWindowDimensions,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
import { useThemeColor } from "../../lib/useThemeColor";
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
/**
* The everyday harnesses stay expanded; every other provider (OpenRouter
* catalogs and friends) folds behind its header so a 300-model catalog can't
* bury the list.
*/
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
/**
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
* covering model, provider options, runtime mode, and plan mode in one label.
*/
export function threadSettingsSummaryLabel(input: {
readonly modelLabel: string;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
}): string {
const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
return [
input.modelLabel,
...providerOptionValueLabels(input.optionDescriptors),
...(runtime ? [runtime.shortLabel] : []),
...(input.interactionMode === "plan" ? ["Plan"] : []),
].join(" · ");
}
function ModelRow(props: {
readonly option: ModelOption;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
// Selected rows get the same primary treatment as the submenu rows.
// Subtle backgrounds (bg-subtle-strong) get overridden by the OS
// selection chrome on iOS 26, so use the explicit high-contrast style
// everywhere instead.
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{props.option.label}
</Text>
{props.option.isDefault ? (
<View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
</View>
) : null}
{props.option.isLegacy ? (
<View className="rounded-md bg-subtle px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
</View>
) : null}
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
/**
* Provider section header with the harness logo. Secondary providers render
* as a tappable fold (count + chevron while collapsed); primary providers
* and the group holding the current selection are static headers.
*/
function ProviderHeader(props: {
readonly driver: string | undefined;
readonly label: string;
readonly collapsible: boolean;
readonly collapsed: boolean;
readonly modelCount: number;
readonly onToggle: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole={props.collapsible ? "button" : "header"}
accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
accessibilityLabel={
props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
}
disabled={!props.collapsible}
onPress={props.onToggle}
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
)}
>
<ProviderIcon provider={props.driver} size={15} />
<Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{props.label}
</Text>
{props.collapsible ? (
<>
<View className="flex-1" />
{props.collapsed ? (
<Text className="text-2xs font-t3-medium text-foreground-muted">
{props.modelCount}
</Text>
) : null}
<SymbolView
name={props.collapsed ? "chevron.down" : "chevron.up"}
size={11}
tintColor={iconSubtle}
type="monochrome"
/>
</>
) : null}
</Pressable>
);
}
/** Compact row that opens a single-choice submenu panel. */
function DisclosureRow(props: {
readonly label: string;
readonly value: string | undefined;
readonly disabled?: boolean;
readonly onPress: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"flex-row items-center gap-2 px-5 py-3 active:opacity-70",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<View className="flex-1" />
{props.value ? (
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
{props.value}
</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
);
}
/** Single option inside a submenu panel. */
function ChoiceRow(props: {
readonly label: string;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
className={cn(
"mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
>
{props.label}
</Text>
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
function SwitchRow(props: {
readonly label: string;
readonly value: boolean;
readonly disabled?: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
return (
<View
className={cn(
"flex-row items-center justify-between px-5 py-2.5",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
type SubmenuPage =
| { readonly kind: "descriptor"; readonly id: string }
| { readonly kind: "runtime" };
/**
* Unified thread settings: the sheet is the provider-grouped model list
* (primary harnesses expanded, other providers folded, legacy behind the
* top-right pill) with a Save button, plus compact disclosure rows whose
* single-choice submenus stack in a small panel over the sheet so it never
* changes size. Model changes stage until Save — while staged, the settings
* rows edit the staged model's options and Save applies everything together.
*
* Callers control which harnesses are offered via providerGroups: an
* existing thread must pass only its own provider's group, since a session
* can't switch harness mid-thread.
*
* Rendered through an RN Modal (not the root OverlayPortal) so it also
* presents above natively-presented form sheets like the new-task draft.
* Callers must dismiss the keyboard when opening — the iOS keyboard window
* would otherwise cover the lower half of the sheet.
*/
export function ThreadSettingsSheet(props: {
readonly visible: boolean;
/**
* "save" = the Save/Done button (the user is finished configuring);
* "dismiss" = backdrop, grabber, or system back. Hosts only restore the
* keyboard for "save" so a stray tap outside a control never pops it.
*/
readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
readonly onDismissed: () => void;
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly onSelectModel: (option: ModelOption) => void;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
readonly runtimeMode: RuntimeMode;
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
}) {
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
const wasPresentedRef = useRef(false);
const notifyDismissed = useCallback(() => {
if (!wasPresentedRef.current) {
return;
}
wasPresentedRef.current = false;
props.onDismissed();
}, [props.onDismissed]);
// Every open starts fresh: no staged model, no submenu, legacy hidden,
// secondary providers folded. The sheet stays mounted between opens, so
// state would otherwise stick around.
useEffect(() => {
if (props.visible) {
wasPresentedRef.current = true;
setShowLegacyToggle(false);
setExpandedProviders(new Set());
setPendingModel(null);
setSubmenu(null);
} else if (Platform.OS === "android" && wasPresentedRef.current) {
// React Native only emits Modal.onDismiss on iOS. Android uses no exit
// animation below, so the post-commit effect is its dismissal boundary.
notifyDismissed();
}
}, [notifyDismissed, props.visible]);
const isApplied = (option: ModelOption) =>
option.selection.instanceId === props.selectedModel?.instanceId &&
option.selection.model === props.selectedModel.model;
// The list highlights the staged pick; Save turns it into the applied one.
const isDisplayed = (option: ModelOption) =>
pendingModel ? option.key === pendingModel.key : isApplied(option);
// While a model is staged, the settings rows describe and edit the staged
// model's options (kept on its pending selection); Save applies model and
// options together. Otherwise they edit the applied selection directly.
const displayedDescriptors = pendingModel
? pendingModel.capabilities
? getProviderOptionDescriptors({
caps: pendingModel.capabilities,
selections: pendingModel.selection.options,
})
: []
: props.optionDescriptors;
const hasLegacyModels = props.providerGroups.some((group) =>
group.models.some((model) => model.isLegacy),
);
// Legacy stays hidden unless the pill is toggled this open; a highlighted
// legacy model is exempted from the filter instead of forcing the whole
// legacy list visible.
const showLegacy = showLegacyToggle;
// Stable settings rows: the union of descriptors across the primary
// harnesses' current models (plus whatever the displayed model advertises)
// always renders, with unsupported rows disabled instead of vanishing when
// the selection changes. Keyed by label, not id — Claude and Codex use
// different ids for the same "Reasoning" concept.
const descriptorTemplate = (() => {
const seen = new Map<string, { type: "select" | "boolean" }>();
for (const group of props.providerGroups) {
const driver = group.models[0]?.providerDriver;
if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
continue;
}
for (const model of group.models) {
if (model.isLegacy) {
continue;
}
for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
}
}
for (const descriptor of displayedDescriptors) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
})();
const handleSave = () => {
if (pendingModel) {
void Haptics.selectionAsync();
props.onSelectModel(pendingModel);
}
props.onClose("save");
};
const handleOptionChange = (id: string, value: string | boolean) => {
const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
if (!next) {
return;
}
if (pendingModel) {
setPendingModel({
...pendingModel,
selection: { ...pendingModel.selection, options: next },
});
} else {
props.onUpdateOptionSelections(next);
}
};
const toggleProvider = (providerKey: string) => {
setExpandedProviders((current) => {
const next = new Set(current);
if (!next.delete(providerKey)) {
next.add(providerKey);
}
return next;
});
};
const activeDescriptor =
submenu?.kind === "descriptor"
? displayedDescriptors.find(
(descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
)
: undefined;
const submenuContent =
submenu?.kind === "runtime"
? {
title: "Runtime",
rows: RUNTIME_MODE_CHOICES.map((choice) => ({
id: choice.mode,
label: choice.label,
selected: choice.mode === props.runtimeMode,
onPress: () => {
void Haptics.selectionAsync();
props.onUpdateRuntimeMode(choice.mode);
setSubmenu(null);
},
})),
}
: activeDescriptor?.type === "select"
? {
title: activeDescriptor.label,
rows: selectableChoices(activeDescriptor).map((choice) => ({
id: choice.id,
label: choice.label,
selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
onPress: () => {
void Haptics.selectionAsync();
handleOptionChange(activeDescriptor.id, choice.id);
setSubmenu(null);
},
})),
}
: null;
return (
<Modal
transparent
statusBarTranslucent
navigationBarTranslucent
animationType={Platform.OS === "ios" ? "fade" : "none"}
visible={props.visible}
onDismiss={notifyDismissed}
onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
>
<View className="flex-1 justify-end">
<Pressable
accessibilityLabel="Close thread settings"
className="absolute inset-0 bg-backdrop"
onPress={() => props.onClose("dismiss")}
/>
<View
className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
style={{ maxHeight: windowHeight * 0.85 }}
>
{/* The grabber doubles as the accessible close control: the dim
backdrop above a tall sheet is a sliver, and VoiceOver can't
reach it at all. */}
<Pressable
accessibilityLabel="Close thread settings"
accessibilityRole="button"
onPress={() => props.onClose("dismiss")}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
{hasLegacyModels ? (
<View className="flex-row justify-end px-4 pb-1.5">
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: showLegacy }}
hitSlop={8}
onPress={() => {
void Haptics.selectionAsync();
setShowLegacyToggle(!showLegacy);
}}
className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
>
<Text className="text-2xs font-t3-medium text-foreground-muted">
{showLegacy ? "Hide legacy models" : "Show legacy models"}
</Text>
</Pressable>
</View>
) : null}
{/* Only the model list scrolls. Provider catalogs can run to
hundreds of models (OpenRouter), so the rows below stay pinned
and reachable instead of living at the end of that scroll. */}
<ScrollView
style={{ flexShrink: 1 }}
contentContainerStyle={{ paddingBottom: 8 }}
showsVerticalScrollIndicator={false}
>
{props.providerGroups.map((group) => {
const driver = group.models[0]?.providerDriver;
const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
const visibleModels = showLegacy
? group.models
: group.models.filter((model) => !model.isLegacy || isDisplayed(model));
if (visibleModels.length === 0) {
return null;
}
const containsSelection = group.models.some(isDisplayed);
const collapsible = !isPrimary && !containsSelection;
const collapsed = collapsible && !expandedProviders.has(group.providerKey);
return (
<View key={group.providerKey}>
<ProviderHeader
driver={driver}
label={group.providerLabel}
collapsible={collapsible}
collapsed={collapsed}
modelCount={visibleModels.length}
onToggle={() => toggleProvider(group.providerKey)}
/>
{collapsed
? null
: visibleModels.map((option) => (
<ModelRow
key={option.key}
option={option}
selected={isDisplayed(option)}
onPress={() => {
void Haptics.selectionAsync();
// Re-tapping the applied model cancels staging.
setPendingModel((current) =>
pendingModelAfterPress({
current,
pressed: option,
pressedIsApplied: isApplied(option),
}),
);
}}
/>
))}
</View>
);
})}
</ScrollView>
<View className="mx-5 h-px bg-border" />
<View style={{ paddingBottom: insets.bottom + 12 }}>
{descriptorTemplate.map((entry) => {
const live = displayedDescriptors.find(
(descriptor) => descriptor.label === entry.label,
);
if ((live?.type ?? entry.type) === "select") {
return (
<DisclosureRow
key={entry.label}
label={entry.label}
value={live ? getProviderOptionCurrentLabel(live) : undefined}
disabled={!live}
onPress={() => {
if (live) {
setSubmenu({ kind: "descriptor", id: live.id });
}
}}
/>
);
}
return (
<SwitchRow
key={entry.label}
label={entry.label}
value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
disabled={!live}
onValueChange={(value) => {
if (live) {
handleOptionChange(live.id, value);
}
}}
/>
);
})}
<DisclosureRow
label="Runtime"
value={
RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
}
onPress={() => setSubmenu({ kind: "runtime" })}
/>
<Pressable
accessibilityRole="button"
onPress={handleSave}
className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{pendingModel ? "Save" : "Done"}
</Text>
</Pressable>
</View>
</View>
{/* Submenus stack over the sheet instead of replacing its content,
so the main sheet keeps its size while drilling in and out. */}
{submenuContent ? (
<View className="absolute inset-0 justify-end">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
className="absolute inset-0 bg-backdrop"
onPress={() => setSubmenu(null)}
/>
<View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
accessibilityRole="button"
onPress={() => setSubmenu(null)}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
<Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{submenuContent.title}
</Text>
<ScrollView
style={{ maxHeight: windowHeight * 0.5 }}
contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
showsVerticalScrollIndicator={false}
bounces={false}
>
{submenuContent.rows.map((row) => (
<ChoiceRow
key={row.id}
label={row.label}
selected={row.selected}
onPress={row.onPress}
/>
))}
</ScrollView>
</View>
</View>
) : null}
</View>
</Modal>
);
}
@@ -3,7 +3,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import type {
EnvironmentId,
ModelSelection,
ProjectReadFileResult,
ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode,
@@ -14,14 +13,8 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import {
isDefaultThreadEnvModeSettled,
resolveDefaultThreadEnvMode,
} from "@t3tools/shared/threadEnvMode";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
@@ -32,13 +25,11 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import {
appendComposerDraftAttachments,
clearComposerDraft,
@@ -68,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";
@@ -124,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;
@@ -157,10 +145,7 @@ type NewTaskFlowContextValue = {
readonly reset: () => void;
readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (
key: string | null,
options?: ReadonlyArray<ProviderOptionSelection>,
) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
readonly setStartFromOrigin: (value: boolean) => void;
@@ -190,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>(
@@ -354,35 +351,10 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
// Default mode until the user picks one explicitly — same resolution web
// uses for new draft threads: per-project setting, then the repo's
// checked-in t3.json, then the server's configured default.
const t3ProjectFileQuery = useEnvironmentQuery(
selectedProject !== null && selectedProject.workspaceRoot !== ""
? projectEnvironment.readFile({
environmentId: selectedProject.environmentId,
input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
})
: null,
);
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
const t3ProjectFileDefaultMode = useMemo(() => {
if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null;
return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null;
}, [t3ProjectFileData]);
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFile: t3ProjectFileDefaultMode,
globalDefault: selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local",
});
// While unsettled the resolved default is provisional. Nothing may write
// it into the draft during that window (the auto-branch effect does), or
// the frozen interim value beats the t3.json default once it loads.
const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({
explicitMode: selectedProjectDraft.workspaceSelection?.mode,
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFilePending: t3ProjectFileQuery.isPending,
});
// The server's configured default decides the mode until the user picks one
// explicitly — same resolution web uses for new draft threads.
const defaultWorkspaceMode: WorkspaceMode =
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
@@ -397,16 +369,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections only count while their provider is usable on the
// server; otherwise the server's default model wins instead of silently
// targeting a disabled provider. The draft selection is an explicit pick
// and passes through as-is; the project default (last used, possibly from
// desktop) is implicit and additionally never resolves to a legacy model.
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveDefaultableModelSelection(
const projectDefaultModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
@@ -444,9 +414,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
// Options ride along in the same write: a follow-up setSelectedModelOptions
// call would rebuild the selection from the stale pre-switch model.
(key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
(key: string | null) => {
if (!key || !selectedProjectDraftKey) {
return;
}
@@ -455,7 +423,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: options ? { ...option.selection, options } : option.selection,
modelSelection: option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
@@ -652,11 +620,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}, [refreshBranches, selectedProject]);
useEffect(() => {
if (
!defaultWorkspaceModeSettled ||
workspaceMode !== "worktree" ||
selectedBranchName !== null
) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
@@ -668,14 +632,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [
allBranchRefs,
availableBranches,
defaultWorkspaceModeSettled,
selectBranch,
selectedBranchName,
workspaceMode,
]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -889,7 +846,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const value = useMemo<NewTaskFlowContextValue>(
() => ({
projectScopes,
logicalProjects,
selectedEnvironmentId,
selectedProjectKey,
selectedModelKey,
@@ -955,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" };
}
@@ -1,38 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
describe("derivePendingUserInputMaxHeight", () => {
it("caps a tall portrait viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 0,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(560);
});
it("subtracts the keyboard while editing a custom answer", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 336,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(387);
});
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 375,
keyboardHeight: 240,
navigationHeaderHeight: 44,
composerOverlapHeight: 94,
}),
).toBe(160);
});
});
@@ -1,37 +0,0 @@
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
/**
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
* height has been observed. Overestimating only costs card height; an
* underestimate would let the card overshoot on the first keyboard open.
*/
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
/**
* One clock for the questionnaire expand/collapse choreography: the card's
* enter/exit and the feed-inset glide must share it or they visibly drift.
* Sized for the near-full-height slide (the card travels its own height),
* in the same class as the iOS keyboard's ~250ms.
*/
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
export function derivePendingUserInputMaxHeight(input: {
readonly windowHeight: number;
readonly keyboardHeight: number;
readonly navigationHeaderHeight: number;
readonly composerOverlapHeight: number;
}): number {
const availableHeight =
input.windowHeight -
Math.max(0, input.keyboardHeight) -
Math.max(0, input.navigationHeaderHeight) -
Math.max(0, input.composerOverlapHeight) -
PENDING_USER_INPUT_VERTICAL_GAP;
return Math.min(
PENDING_USER_INPUT_MAX_HEIGHT,
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
);
}
@@ -1,70 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
describe("resolveThreadFeedLiveFollow", () => {
it("pauses immediately when the user starts scrolling", () => {
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
});
it("stays paused away from the actual end", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("does not mistake programmatic layout compensation for a user scroll", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("does not re-arm at the end while a user scroll session is active", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("re-arms at the actual end only after the user scroll session ends", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(true);
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("ignores momentum-end events from programmatic scrolling", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("re-arms after an explicit reset", () => {
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
});
});
@@ -1,35 +0,0 @@
export type ThreadFeedLiveFollowEvent =
| { readonly type: "reset" }
| { readonly type: "user-scroll-begin" }
| {
readonly type: "user-scroll-end";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
}
| {
readonly type: "scroll";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
};
export function resolveThreadFeedLiveFollow(
current: boolean,
event: ThreadFeedLiveFollowEvent,
): boolean {
switch (event.type) {
case "reset":
return true;
case "user-scroll-begin":
return false;
case "user-scroll-end":
return event.userScrollSessionActive ? event.isAtEnd : current;
case "scroll":
if (event.userScrollSessionActive) {
return false;
}
if (event.isAtEnd) {
return true;
}
return current;
}
}
@@ -22,7 +22,6 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -135,7 +134,6 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
>
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
open={!props.collapsed}
size={compact ? 22 : 18}
projectTitle={props.project.title}
@@ -431,8 +429,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly titleRegenerationSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
@@ -454,8 +450,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -475,21 +470,6 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const menuActions = useMemo<MenuAction[]>(
() => [
THREAD_ROW_MENU_ACTIONS[0]!,
...buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
THREAD_ROW_MENU_ACTIONS[1]!,
],
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
@@ -502,10 +482,9 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete, handleRegenerateTitle],
[handleArchive, handleDelete],
);
const statusPill = effectiveStatus ? (
@@ -694,7 +673,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={menuActions}
actions={THREAD_ROW_MENU_ACTIONS}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,7 +27,6 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -66,8 +65,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -205,8 +204,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
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;
}) {
@@ -231,7 +228,6 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
@@ -295,9 +291,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
) : (
<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 className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -333,8 +327,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
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;
@@ -342,7 +334,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
@@ -357,16 +348,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 title regeneration. */
readonly titleRegenerationSupported: 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
@@ -388,7 +369,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -396,7 +376,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onArchiveThread,
onPinThread,
onUnpinThread,
onMovePinnedThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
@@ -422,10 +401,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
@@ -435,14 +410,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
@@ -486,42 +453,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,
],
);
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
() =>
buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
[props.titleRegenerationSupported, thread.titleRegeneration],
[pinnedRow, props.pinningSupported],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
@@ -533,31 +470,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
[pinMenuItem, snoozePresetActions],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [
CARD_MENU_ACTIONS[0]!,
...pinMenuItem,
...titleRegenerationMenuItems,
...CARD_MENU_ACTIONS.slice(1),
],
[pinMenuItem, titleRegenerationMenuItems],
);
const slimMenuActions = useMemo<MenuAction[]>(
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const snoozedMenuActions = useMemo<MenuAction[]>(
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const legacyMenuActions = useMemo<MenuAction[]>(
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -566,10 +485,7 @@ 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 === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
@@ -585,9 +501,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
handleSettle,
handleSnooze,
@@ -668,7 +581,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
@@ -816,9 +728,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
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 className="ml-5 h-px bg-border-subtle" />
</View>
)}
</Pressable>
@@ -857,7 +767,6 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<View className="opacity-40">
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
@@ -927,11 +836,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? snoozedMenuActions
? SNOOZED_MENU_ACTIONS
: !props.settlementSupported
? legacyMenuActions
? LEGACY_MENU_ACTIONS
: canUnsettle
? slimMenuActions
? SLIM_MENU_ACTIONS
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -1,284 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
function modelOption(
model: string,
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
): ModelOption {
const providerKey = overrides.providerKey ?? "codex";
return {
key: `${providerKey}:${model}`,
label: model,
subtitle: providerKey,
providerKey,
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
isDefault: overrides.isDefault ?? false,
isLegacy: overrides.isLegacy ?? false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make(providerKey),
model,
options: [],
},
};
}
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
const first = models[0];
if (!first) {
throw new Error("group requires at least one model");
}
return {
providerKey: first.providerKey,
providerLabel: first.providerLabel,
models,
};
}
const effortDescriptor: ProviderOptionDescriptor = {
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "ultrathink", label: "Ultrathink" },
{ id: "ultracode", label: "Ultracode" },
],
currentValue: "high",
promptInjectedValues: ["ultrathink"],
};
const fastModeDescriptor: ProviderOptionDescriptor = {
id: "fastMode",
label: "Fast mode",
type: "boolean",
currentValue: false,
};
function baseInput() {
const models = [
modelOption("gpt-current", { isDefault: true }),
modelOption("gpt-next"),
modelOption("gpt-old", { isLegacy: true }),
];
return {
providerGroups: [group(models)],
selectedModel: models[0]?.selection ?? null,
optionDescriptors: [effortDescriptor, fastModeDescriptor],
runtimeMode: "auto",
} as const;
}
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
return id === undefined ? undefined : menu.events.get(id);
}
describe("buildThreadSettingsMenu", () => {
it("orders the top level as model, options, runtime", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.map((action) => action.title)).toEqual([
"Model",
"Reasoning",
"Fast mode",
"Runtime",
]);
});
it("summarizes the current choice on each submenu row", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
});
it("checkmarks the selected model and resolves selection events", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const current = modelItems.find((action) => action.title === "gpt-current");
expect(current?.state).toBe("on");
expect(current?.subtitle).toBe("Default");
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
expect(event?.type).toBe("select-model");
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
});
it("folds unselected legacy models behind a nested submenu", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"Legacy Models",
]);
expect(
modelItems
.find((action) => action.title === "Legacy Models")
?.subactions?.map((action) => action.title),
).toEqual(["gpt-old"]);
});
it("keeps a selected legacy model in the main list", () => {
const input = baseInput();
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
const menu = buildThreadSettingsMenu({
...input,
selectedModel: legacy?.selection ?? null,
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"gpt-old",
]);
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
});
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
const menu = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
});
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
// The hidden value stays visible as the current summary; it just can't be
// picked from the phone.
expect(reasoning?.subtitle).toBe("Ultracode");
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
});
it("resolves select-option and runtime events with checkmarked current values", () => {
const menu = buildThreadSettingsMenu(baseInput());
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
type: "set-option",
optionId: "effort",
value: "low",
});
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
expect(
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
).toEqual({ type: "set-runtime", mode: "full-access" });
});
it("toggles boolean options with the inverted current value", () => {
const menu = buildThreadSettingsMenu(baseInput());
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
expect(fastMode?.state).toBe("off");
expect(fastMode?.subactions).toBeUndefined();
expect(eventFor(menu, fastMode?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: true,
});
const enabled = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
});
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
expect(enabledRow?.state).toBe("on");
expect(eventFor(enabled, enabledRow?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: false,
});
});
it("keeps the menu presented only for top-level toggles", () => {
const menu = buildThreadSettingsMenu(baseInput());
// Root-level boolean toggles refresh in place with clean chrome, so they
// keep the menu presented.
expect(
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
).toBe(true);
// Picks inside nested submenus close the menu: staying presented leaves
// the submenu on screen with an expanded-submenu header, and the
// bottom-anchored collapse back out drops by the levels' height delta.
const expected = undefined;
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
(action) => action.subactions === undefined,
);
expect(nestedPicks.length).toBeGreaterThan(0);
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
true,
);
});
it("sections models by provider only when multiple groups are offered", () => {
const codexModels = [modelOption("gpt-current", { isDefault: true })];
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
const menu = buildThreadSettingsMenu({
providerGroups: [group(codexModels), group(claudeModels)],
selectedModel: codexModels[0]?.selection ?? null,
optionDescriptors: [],
runtimeMode: "auto",
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
).toEqual([
{ title: "Codex", inline: true },
{ title: "Claude", inline: true },
]);
const claudeSection = modelItems.find((action) => action.title === "Claude");
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
});
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
const types = new Set<ThreadSettingsMenuEvent["type"]>();
for (const event of menu.events.values()) {
types.add(event.type);
}
return types;
};
it("registers an event for every leaf action id", () => {
const menu = buildThreadSettingsMenu(baseInput());
const leafIds: string[] = [];
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
for (const item of items) {
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
} else if (item.id !== undefined) {
leafIds.push(item.id);
}
}
};
collect(menu.actions);
for (const id of leafIds) {
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
}
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
});
});
@@ -1,202 +0,0 @@
import type { MenuAction } from "@react-native-menu/menu";
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
} from "@t3tools/shared/model";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
export function selectableChoices(
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
export type ThreadSettingsMenuEvent =
| { readonly type: "select-model"; readonly option: ModelOption }
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
export type ThreadSettingsMenu = {
readonly actions: MenuAction[];
/** Menu action id → the change it applies, for the onPressAction dispatch. */
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
};
/**
* Native menu replacement for the thread settings sheet (model, select and
* boolean provider options, runtime mode). The menu presents from the
* composer pill without resigning the keyboard, so adjusting settings never
* bounces focus. A thread is bound to one harness, so the menu covers the
* sheet's full surface for existing threads; the sheet remains the Android
* and new-task-draft surface.
*
* Selections apply immediately — the sheet's stage-then-Save flow only exists
* because the sheet batches a model change with its option edits.
*/
export function buildThreadSettingsMenu(input: {
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
}): ThreadSettingsMenu {
const events = new Map<string, ThreadSettingsMenuEvent>();
const actions: MenuAction[] = [];
const isSelected = (option: ModelOption) =>
option.selection.instanceId === input.selectedModel?.instanceId &&
option.selection.model === input.selectedModel.model;
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
// 16+): the root refreshes in place with clean chrome. Picks inside nested
// submenus close the menu — keeping the submenu presented renders an
// expanded-submenu header with no way to pop back to the root, and the
// bottom-anchored collapse back out travels the levels' height difference.
const keepPresented = { keepsMenuPresented: true } as const;
const modelAction = (option: ModelOption, id: string): MenuAction => {
events.set(id, { type: "select-model", option });
return {
id,
title: option.label,
...(option.isDefault ? { subtitle: "Default" } : {}),
state: isSelected(option) ? "on" : "off",
};
};
const modelItems: MenuAction[] = [];
const legacyItems: MenuAction[] = [];
let selectedModelLabel: string | undefined;
input.providerGroups.forEach((group, groupIndex) => {
const groupItems: MenuAction[] = [];
group.models.forEach((option, modelIndex) => {
if (isSelected(option)) {
selectedModelLabel = option.label;
}
const id = `model:${groupIndex}:${modelIndex}`;
// A highlighted legacy model stays in the main list (mirroring the
// sheet) so the checkmark isn't hidden behind the Legacy fold.
if (option.isLegacy && !isSelected(option)) {
legacyItems.push(modelAction(option, id));
} else {
groupItems.push(modelAction(option, id));
}
});
if (groupItems.length === 0) {
return;
}
// A thread is bound to one harness, so provider sections only appear for
// multi-group callers (the new-task draft, if it ever adopts the menu).
if (input.providerGroups.length > 1) {
modelItems.push({
id: `model-group:${groupIndex}`,
title: group.providerLabel,
displayInline: true,
subactions: groupItems,
});
} else {
modelItems.push(...groupItems);
}
});
if (legacyItems.length > 0) {
modelItems.push({
id: "legacy-models",
title: "Legacy Models",
subactions: legacyItems,
});
}
if (modelItems.length > 0) {
actions.push({
id: "model",
title: "Model",
...(selectedModelLabel === undefined
? input.selectedModel
? { subtitle: input.selectedModel.model }
: {}
: { subtitle: selectedModelLabel }),
subactions: modelItems,
});
}
for (const descriptor of input.optionDescriptors) {
if (descriptor.type === "boolean") {
const id = `option:${descriptor.id}`;
events.set(id, {
type: "set-option",
optionId: descriptor.id,
value: !(descriptor.currentValue ?? false),
});
actions.push({
id,
title: descriptor.label,
state: descriptor.currentValue ? "on" : "off",
attributes: keepPresented,
});
continue;
}
const currentValue = getProviderOptionCurrentValue(descriptor);
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
const id = `option:${descriptor.id}:${choice.id}`;
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
return {
id,
title: choice.label,
state: choice.id === currentValue ? "on" : "off",
};
});
if (choices.length === 0) {
continue;
}
const currentLabel = getProviderOptionCurrentLabel(descriptor);
actions.push({
id: `option:${descriptor.id}`,
title: descriptor.label,
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
subactions: choices,
});
}
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
(choice) => choice.mode === input.runtimeMode,
)?.label;
actions.push({
id: "runtime",
title: "Runtime",
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
const id = `runtime:${choice.mode}`;
events.set(id, { type: "set-runtime", mode: choice.mode });
return {
id,
title: choice.label,
state: choice.mode === input.runtimeMode ? "on" : "off",
};
}),
});
return { actions, events };
}
@@ -1,64 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
import type { ModelOption } from "../../lib/modelOptions";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
function modelOption(
model: string,
options: ReadonlyArray<ProviderOptionSelection> = [],
): ModelOption {
return {
key: `codex:${model}`,
label: model,
subtitle: "Codex",
providerKey: "codex",
providerLabel: "Codex",
providerDriver: "codex",
isDefault: false,
isLegacy: false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make("codex"),
model,
options,
},
};
}
describe("thread settings sheet state", () => {
it("clears staging when the applied model is pressed", () => {
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed: modelOption("gpt-current"),
pressedIsApplied: true,
}),
).toBeNull();
});
it("preserves staged options when the highlighted model is pressed again", () => {
const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]);
expect(
pendingModelAfterPress({
current: pending,
pressed: modelOption("gpt-next"),
pressedIsApplied: false,
}),
).toBe(pending);
});
it("stages a different model", () => {
const pressed = modelOption("gpt-other");
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed,
pressedIsApplied: false,
}),
).toBe(pressed);
});
});
@@ -1,13 +0,0 @@
import type { ModelOption } from "../../lib/modelOptions";
/** Preserve staged provider options when the highlighted model is tapped again. */
export function pendingModelAfterPress(input: {
readonly current: ModelOption | null;
readonly pressed: ModelOption;
readonly pressedIsApplied: boolean;
}): ModelOption | null {
if (input.pressedIsApplied) {
return null;
}
return input.current?.key === input.pressed.key ? input.current : input.pressed;
}
@@ -1,36 +0,0 @@
import { describe, expect, it } from "vite-plus/test";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
describe("buildThreadTitleRegenerationMenuItems", () => {
it("hides regeneration when the environment does not advertise support", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
).toEqual([]);
});
it("offers regeneration for a supported environment", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerate title",
image: "arrow.clockwise",
},
]);
});
it("shows and disables the pending state", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerating…",
image: "arrow.clockwise",
attributes: { disabled: true },
},
]);
});
});
@@ -1,17 +0,0 @@
import type { MenuAction } from "@react-native-menu/menu";
export function buildThreadTitleRegenerationMenuItems(input: {
readonly supported: boolean;
readonly isRegenerating: boolean;
}): MenuAction[] {
if (!input.supported) return [];
return [
{
id: "regenerate-title",
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
image: "arrow.clockwise",
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
},
];
}
@@ -104,24 +104,20 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => {
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }),
).toBe(true);
});
it("honors an explicit legacy opt-in", () => {
expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe(
false,
);
expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe(
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
true,
);
});
it("honors an explicit device opt-out", () => {
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
});
it("holds the default while preferences are still loading so the list does not remount", () => {
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }),
).toBe(true);
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
true,
);
});
});
@@ -9,7 +9,6 @@ import {
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
@@ -103,23 +102,23 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* The flat Thread List v2 is the default on every app variant; the Settings →
* Legacy toggle opts a device back into the grouped legacy list. Preferences
* persist as sparse patches, so `undefined` genuinely means "never chosen".
* Thread List v2 is on by default on every app variant; the Settings → Beta
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
* genuinely means "never chosen".
*
* `preferencesLoaded` guards the startup window: preferences load
* asynchronously, and rendering one list before the stored choice arrives would
* remount the whole thing a tick later. While loading, hold the default — that
* is where every device without an explicit legacy opt-in lands anyway.
* is where every device without an explicit opt-out lands anyway.
*/
export function resolveThreadListV2Enabled(input: {
readonly legacyPreference: boolean | undefined;
readonly preference: boolean | undefined;
readonly preferencesLoaded: boolean;
}): boolean {
if (!input.preferencesLoaded) {
return true;
}
return input.legacyPreference !== true;
return input.preference ?? true;
}
export function resolveThreadListV2Status(
@@ -384,8 +383,8 @@ export function buildThreadListV2Items(input: {
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
// Visibility parity with web: snooze outranks everything, including a
// pin — a snoozed thread leaves the list until it wakes (or raises its
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
// thread reappears at its exact spot in the pinned block.
// hand). The pin survives underneath, so a woken thread reappears at
// its original spot in the creation-ordered pinned block.
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
snoozed.push(thread);
if (
@@ -445,7 +444,7 @@ export function buildThreadListV2Items(input: {
);
const items: ThreadListV2Item[] = [];
for (const thread of sortPinnedThreadsByOrderKey(pinned)) {
for (const thread of sortThreadsForListV2(pinned)) {
items.push({
thread,
variant: "card",
@@ -5,15 +5,15 @@ import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveThreadListV2Enabled } from "./threadListV2";
/**
* Resolved Thread List v2 state: on unless the device opted into the legacy
* grouped list (Settings → Legacy). Every consumer must read through this
* Resolved Thread List v2 state: the device-local preference if the user has
* set one, otherwise the default (on). Every consumer must read through this
* rather than the raw preference, which is undefined until explicitly chosen.
*/
export function useThreadListV2Enabled(): boolean {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferencesResult);
return resolveThreadListV2Enabled({
legacyPreference: loaded ? preferencesResult.value.legacyThreadListEnabled : undefined,
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
preferencesLoaded: loaded,
});
}
@@ -1,98 +0,0 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { KeyboardController } from "react-native-keyboard-controller";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
export type ThreadSettingsSheetCloseReason = "save" | "dismiss";
type PresentationPhase = "closed" | "opening" | "visible" | "closing";
/**
* Keeps the custom native composer and the settings modal from owning focus at
* the same time. Opening waits for the keyboard dismissal to finish, while
* focus restoration waits for the modal's dismissal callback.
*/
export function useThreadSettingsSheetPresentation(input: {
readonly editorRef: RefObject<ComposerEditorHandle | null>;
readonly isEditorFocused: boolean;
}) {
const [phase, setPhase] = useState<PresentationPhase>("closed");
const isActiveRef = useRef(false);
const isMountedRef = useRef(true);
const openingIdRef = useRef(0);
const restoreFocusOnSaveRef = useRef(false);
const shouldRestoreAfterDismissRef = useRef(false);
useEffect(
() => () => {
isMountedRef.current = false;
isActiveRef.current = false;
openingIdRef.current += 1;
},
[],
);
const open = useCallback(() => {
if (isActiveRef.current) {
return;
}
isActiveRef.current = true;
restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();
shouldRestoreAfterDismissRef.current = false;
setPhase("opening");
const openingId = openingIdRef.current + 1;
openingIdRef.current = openingId;
// Keyboard.dismiss() only tracks React Native TextInputs. The composer is
// a custom native text view, so explicitly resign its first responder too.
input.editorRef.current?.blur();
void KeyboardController.dismiss().then(() => {
if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
return;
}
setPhase("visible");
});
}, [input.editorRef, input.isEditorFocused]);
const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {
if (!isActiveRef.current) {
return;
}
openingIdRef.current += 1;
shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;
setPhase("closing");
}, []);
const onDismissed = useCallback(() => {
const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;
shouldRestoreAfterDismissRef.current = false;
restoreFocusOnSaveRef.current = false;
isActiveRef.current = false;
setPhase("closed");
if (shouldRestoreFocus) {
input.editorRef.current?.focus();
}
}, [input.editorRef]);
// The new-task screen can have an autofocus queued before the sheet opens.
// Preserve that intent for Save without allowing it to focus under the modal.
const restoreFocusAfterSave = useCallback(() => {
if (isActiveRef.current) {
restoreFocusOnSaveRef.current = true;
}
}, []);
return {
isActive: phase !== "closed",
isActiveRef,
isVisible: phase === "visible",
open,
close,
onDismissed,
restoreFocusAfterSave,
} as const;
}
@@ -32,19 +32,6 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
}
describe("runAppUpdateCheck", () => {
it("does nothing while running from the Metro development server", async () => {
vi.stubGlobal("__DEV__", true);
const client = makeUpdateClient();
try {
await runAppUpdateCheck({ client });
} finally {
vi.unstubAllGlobals();
}
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
@@ -113,32 +100,6 @@ describe("runAppUpdateCheck", () => {
reportError.mockRestore();
});
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
"treats Expo's %s failure as an unavailable update check",
async (code) => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const error = Object.assign(new Error("Updates are unavailable"), { code });
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => {
throw error;
}),
});
const failures: string[] = [];
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => states.push(state),
});
expect(reportError).not.toHaveBeenCalled();
expect(failures).toEqual([]);
expect(states).toEqual(["checking", "idle"]);
reportError.mockRestore();
},
);
it("coalesces overlapping launch and manual checks", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
@@ -48,17 +48,8 @@ interface Deferred {
}
const HIDDEN_UPDATE_TAP_COUNT = 5;
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
"ERR_UPDATES_DISABLED",
]);
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
}
/**
* Keeps the manual update affordance discoverable only to someone deliberately
* tapping the version row five times.
@@ -82,7 +73,7 @@ export function registerHiddenUpdateTap(count: number): {
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!isAppUpdateCheckAvailable(client)) return;
if (!client.isEnabled) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
@@ -216,27 +207,19 @@ function reportUpdateFailure(
fallback: string,
onFailure: AppUpdateCheckOptions["onFailure"],
): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
if (isAppUpdateUnavailableError(error)) return;
reportAtomCommandResult(result, { label: "app update check" });
onFailure?.(error instanceof Error ? error.message : fallback);
}
function isAppUpdateUnavailableError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("code" in error)) return false;
const code = error.code;
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
}
export function createAppUpdateLaunchCheck(
client: AppUpdateClient = Updates,
): () => Promise<void> | undefined {
let started = false;
return () => {
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
if (started || !client.isEnabled) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
@@ -1,50 +0,0 @@
import { Chart, Host, type ChartDataPoint } from "@expo/ui/swift-ui";
import { frame } from "@expo/ui/swift-ui/modifiers";
import { useMemo } from "react";
import type { DailyTotals } from "@t3tools/shared/usageMerge";
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
import { useProviderColors } from "./usageProviders";
export interface UsageDailyChartProps {
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly height: number;
}
/**
* Native Swift Charts daily bars. Points sharing an x value stack, so emitting
* one point per provider per day yields per-provider bands whose stack height
* is the day's total; changes animate natively.
*
* Axes are hidden: 30-90 categorical day labels cannot fit on a phone, so the
* screen renders its own edge labels under the chart instead.
*/
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
const colors = useProviderColors();
const data = useMemo((): ChartDataPoint[] => {
return buildChartDays(days, daily, metric).flatMap((day) =>
day.values.map((entry) => ({
x: day.day,
y: entry.value,
color: colors[entry.provider],
})),
);
}, [days, daily, metric, colors]);
return (
<Host style={{ height, width: "100%" }}>
<Chart
type="bar"
data={data}
animate
showGrid={false}
barStyle={{ cornerRadius: 2 }}
modifiers={[frame({ height })]}
/>
</Host>
);
}
@@ -1,44 +0,0 @@
import { useMemo } from "react";
import { View } from "react-native";
import type { DailyTotals } from "@t3tools/shared/usageMerge";
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
import { useProviderColors } from "./usageProviders";
export interface UsageDailyChartProps {
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly height: number;
}
/**
* Stacked daily bars drawn with plain views. Android and any platform without
* Swift Charts land here; iOS resolves `UsageDailyChart.ios.tsx` instead.
*/
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
const colors = useProviderColors();
const chartDays = useMemo(() => buildChartDays(days, daily, metric), [days, daily, metric]);
const max = chartDays.reduce((peak, day) => Math.max(peak, day.total), 0);
return (
<View style={{ height }} className="flex-row items-end gap-px">
{/* column-reverse stacks the bottom-first provider values upward
without reversing the array (Hermes lacks Array#toReversed). */}
{chartDays.map((day) => (
<View key={day.day} className="h-full flex-1 flex-col-reverse overflow-hidden rounded-sm">
{day.values.map((entry) => (
<View
key={entry.provider}
style={{
height: max === 0 ? 0 : (entry.value / max) * height,
backgroundColor: colors[entry.provider],
}}
/>
))}
</View>
))}
</View>
);
}
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff. Show more