Compare commits
145
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
54d006d522 | ||
|
|
a3823306b7 | ||
|
|
a3e58c648b | ||
|
|
6031e5e53e | ||
|
|
48bb962515 | ||
|
|
ba79f14d2d | ||
|
|
66b6fb4cf0 | ||
|
|
d95c7667e4 | ||
|
|
886195ec1e | ||
|
|
288d8e3457 | ||
|
|
5208bdeb0d | ||
|
|
a6c9b41f90 | ||
|
|
70c423a5e4 | ||
|
|
89c320df0b | ||
|
|
7b2cf4374f | ||
|
|
49964e38c0 | ||
|
|
e70cdb478d | ||
|
|
be01b287b9 | ||
|
|
c2f8cb7ca1 | ||
|
|
89ee692bf0 | ||
|
|
a20923ce46 | ||
|
|
8101cd0449 | ||
|
|
30164cb1ba | ||
|
|
0640410726 | ||
|
|
2c7267ad43 | ||
|
|
daf8ee0b2f | ||
|
|
ed886fe181 | ||
|
|
4eaf5ef8bb | ||
|
|
0de9540739 | ||
|
|
31891a1a0c | ||
|
|
45d9aa90ba | ||
|
|
7a84f6cf10 | ||
|
|
f0fb406acf | ||
|
|
82406bce99 | ||
|
|
72d673a855 | ||
|
|
e2cd2383ce | ||
|
|
5661c6116c | ||
|
|
6d70e6d778 | ||
|
|
be1a836745 | ||
|
|
239ef1c54d | ||
|
|
61b51ae0e3 | ||
|
|
bfc69e4b4d | ||
|
|
af281c9fc4 | ||
|
|
bd422fd8d1 | ||
|
|
33a03c8a7b | ||
|
|
a17459e8a9 | ||
|
|
b2ee17d7c1 | ||
|
|
7963cc70f3 | ||
|
|
b792ed9f7b | ||
|
|
2e66b1fdfc | ||
|
|
8100062a78 | ||
|
|
a1762fdd74 | ||
|
|
388b43a27c | ||
|
|
23f0a1ae38 | ||
|
|
85b1734d4d | ||
|
|
3ffe84f968 | ||
|
|
220efad62b | ||
|
|
b98a0f0d22 | ||
|
|
95305c36fa | ||
|
|
48aa875c0e | ||
|
|
a8cd2ad2eb | ||
|
|
4a07c1ca9d | ||
|
|
cf5c9948c8 | ||
|
|
2288d416aa | ||
|
|
ddfe45c66e | ||
|
|
9547cf2463 | ||
|
|
1c7d059f55 | ||
|
|
6fa4576078 | ||
|
|
ae7b27de82 | ||
|
|
6b73b3defe | ||
|
|
7aad7911f6 | ||
|
|
6da92244cc | ||
|
|
c471145e96 | ||
|
|
64a991ad45 | ||
|
|
0ec4fbc4a3 | ||
|
|
ea50b695a7 | ||
|
|
331c6dce7f | ||
|
|
4f5834ba72 | ||
|
|
aa16c180e5 | ||
|
|
470d4eb993 | ||
|
|
99d91ddaa4 | ||
|
|
ab3b55e29a | ||
|
|
e4abc31f1e | ||
|
|
b7d1981b57 | ||
|
|
64a3cd6d7d | ||
|
|
48e2c27f2f | ||
|
|
8b2ea5721a | ||
|
|
df2f1273e9 | ||
|
|
f9e8236899 | ||
|
|
8f341f20c9 | ||
|
|
808d685355 | ||
|
|
80720ad592 | ||
|
|
a483337a02 | ||
|
|
1ffba7093a | ||
|
|
3da315e7b5 | ||
|
|
a2ca89aa10 | ||
|
|
990bb0b689 | ||
|
|
7251f1a1f1 | ||
|
|
30e471530b | ||
|
|
de592a00e8 | ||
|
|
2a04db134c | ||
|
|
37d3667de4 | ||
|
|
9697b765e5 | ||
|
|
9d9a872bcc | ||
|
|
9235c83eb7 | ||
|
|
e0c85a20ef | ||
|
|
3c5bdb84a9 | ||
|
|
70de6e1786 | ||
|
|
47dfc65265 | ||
|
|
41ebf22eea | ||
|
|
3d429662c9 | ||
|
|
7b38fb5c6b | ||
|
|
7537adc30f | ||
|
|
94696b0f54 | ||
|
|
fff6a5b028 | ||
|
|
da6e1a9678 | ||
|
|
8eca20005b | ||
|
|
2fa1fec8d8 | ||
|
|
9bd2a4c688 | ||
|
|
4fb03aff0b | ||
|
|
d7950ac153 | ||
|
|
36caf34c68 | ||
|
|
90e3778660 | ||
|
|
94331c58ec | ||
|
|
c30a6d9b99 | ||
|
|
37ae1abbe9 | ||
|
|
82b76e2138 | ||
|
|
8a16cadbaf | ||
|
|
2b1d4fecb8 | ||
|
|
cec1bb9de3 | ||
|
|
25ec0b9d13 | ||
|
|
966cc05a90 | ||
|
|
1cbd88aba0 | ||
|
|
553867262c | ||
|
|
11639bf439 | ||
|
|
a261a6440a | ||
|
|
6f04a5cffb | ||
|
|
30c9622806 | ||
|
|
69dfb7f09a | ||
|
|
e60821f0e0 | ||
|
|
64bf016191 | ||
|
|
5192f777fe | ||
|
|
283c7ac4ba | ||
|
|
78eb3ecae9 | ||
|
|
d3037064e6 |
No files matched your search
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
- 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).
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
@@ -50,24 +50,13 @@ 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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
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.
|
||||
|
||||
```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.
|
||||
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.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
|
||||
+12
-9
@@ -1,12 +1,14 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# 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.
|
||||
# `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.
|
||||
|
||||
# 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_...
|
||||
# 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
|
||||
|
||||
# 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
|
||||
@@ -15,8 +17,9 @@
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
|
||||
# automatically.
|
||||
T3CODE_RELAY_URL=https://relay.t3.codes
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
|
||||
@@ -11,9 +11,11 @@
|
||||
# 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
|
||||
@@ -25,7 +27,9 @@ github:Noojuno
|
||||
github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:saphid
|
||||
github:shiroyasha9
|
||||
github:StiensWout
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
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,
|
||||
};
|
||||
@@ -0,0 +1,292 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
|
||||
const {
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
} = require("./thread-transfer-report.cjs");
|
||||
|
||||
function result(overrides = {}) {
|
||||
const observed = {
|
||||
totalWireBytes: 2_200_000,
|
||||
threadSnapshotWireBytes: 1_950_000,
|
||||
threadSnapshotDecodedBytes: 9_100_000,
|
||||
measuredTurnWebSocketWireBytes: 250_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_150_000,
|
||||
measuredTurnWebSocketMessages: 15,
|
||||
};
|
||||
const ceiling = {
|
||||
totalWireBytes: 2_900_000,
|
||||
threadSnapshotWireBytes: 2_600_000,
|
||||
measuredTurnWebSocketWireBytes: 320_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_550_000,
|
||||
measuredTurnWebSocketMessages: 20,
|
||||
};
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: 10,
|
||||
historyCommandToolsPerTurn: 5,
|
||||
historyMcpResultBytes: 900_000,
|
||||
measuredCommandTools: 20,
|
||||
measuredMcpResultBytes: 1_100_000,
|
||||
},
|
||||
providers: {
|
||||
codex: { observed: { ...observed, ...overrides }, ceiling },
|
||||
claudeAgent: { observed, ceiling },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("validates the fixed artifact schema", () => {
|
||||
assert.equal(validateResult(result()).schemaVersion, 1);
|
||||
assert.throws(
|
||||
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
|
||||
/unexpected fields/,
|
||||
);
|
||||
assert.throws(
|
||||
() => validateResult(result({ totalWireBytes: "lots" })),
|
||||
/non-negative safe integer/,
|
||||
);
|
||||
});
|
||||
|
||||
test("renders baseline, impact, ceiling, and ceiling changes", () => {
|
||||
const baseline = result();
|
||||
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
|
||||
current.providers.codex.ceiling = {
|
||||
...current.providers.codex.ceiling,
|
||||
measuredTurnWebSocketWireBytes: 330_000,
|
||||
};
|
||||
const comment = renderComment({
|
||||
current,
|
||||
baseline,
|
||||
currentRun: {
|
||||
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
conclusion: "success",
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
|
||||
},
|
||||
baselineRun: {
|
||||
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
matchesBase: true,
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
|
||||
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
|
||||
assert.match(comment, /This PR changes transfer ceilings/);
|
||||
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
|
||||
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
|
||||
assert.match(
|
||||
comment,
|
||||
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
|
||||
const outputs = {};
|
||||
const listWorkflowRunArtifacts = () => {};
|
||||
const listWorkflowRuns = () => {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
const github = {
|
||||
paginate: async (method, input) => {
|
||||
if (method === listPullRequestsAssociatedWithCommit) {
|
||||
return [
|
||||
{
|
||||
number: 5350,
|
||||
state: "open",
|
||||
head: { sha: "head-sha", ref: "feature-branch", repo: null },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRunArtifacts) {
|
||||
return [
|
||||
{
|
||||
name: "thread-transfer-results",
|
||||
expired: false,
|
||||
runId: input.run_id,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRuns) {
|
||||
return [{ id: 1, head_sha: "base-sha" }];
|
||||
}
|
||||
throw new Error("unexpected pagination call");
|
||||
},
|
||||
rest: {
|
||||
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
|
||||
pulls: {
|
||||
get: async () => ({
|
||||
data: {
|
||||
head: { sha: "head-sha" },
|
||||
base: { sha: "base-sha", ref: "main" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
};
|
||||
await resolve({
|
||||
github,
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "true");
|
||||
assert.equal(outputs.pull_number, "5350");
|
||||
assert.equal(outputs.pr_artifact, "true");
|
||||
assert.equal(outputs.baseline_run_id, "1");
|
||||
assert.equal(outputs.baseline_matches_base, "true");
|
||||
});
|
||||
|
||||
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
|
||||
const outputs = {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
let fetchedPull = false;
|
||||
await resolve({
|
||||
github: {
|
||||
paginate: async (method) => {
|
||||
assert.equal(method, listPullRequestsAssociatedWithCommit);
|
||||
return [5350, 5351].map((number) => ({
|
||||
number,
|
||||
state: "open",
|
||||
head: {
|
||||
sha: "head-sha",
|
||||
ref: "feature-branch",
|
||||
repo: { full_name: "pingdotgg/t3code" },
|
||||
},
|
||||
}));
|
||||
},
|
||||
rest: {
|
||||
actions: {},
|
||||
pulls: {
|
||||
get: async () => {
|
||||
fetchedPull = true;
|
||||
},
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
},
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "false");
|
||||
assert.equal(fetchedPull, false);
|
||||
});
|
||||
|
||||
test("does not publish a stale result after the PR head advances", async () => {
|
||||
let listedComments = false;
|
||||
const info = [];
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => {
|
||||
listedComments = true;
|
||||
return [];
|
||||
},
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
throw new Error("must not create a stale comment");
|
||||
},
|
||||
updateComment: () => {
|
||||
throw new Error("must not update a stale comment");
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: (message) => info.push(message) },
|
||||
5350,
|
||||
"old-head-sha",
|
||||
"stale body",
|
||||
);
|
||||
|
||||
assert.equal(published, false);
|
||||
assert.equal(listedComments, false);
|
||||
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
|
||||
});
|
||||
|
||||
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
|
||||
let updatedComment = false;
|
||||
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => [
|
||||
{
|
||||
id: 1,
|
||||
user: { login: "github-actions[bot]" },
|
||||
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
|
||||
},
|
||||
],
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
updateComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: () => {} },
|
||||
5350,
|
||||
sha,
|
||||
"missing artifact warning",
|
||||
{ preserveResultSha: sha },
|
||||
);
|
||||
|
||||
assert.equal(published, true);
|
||||
assert.equal(updatedComment, false);
|
||||
});
|
||||
@@ -84,8 +84,29 @@ jobs:
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
|
||||
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
|
||||
run: vp run test
|
||||
|
||||
- name: Publish transfer budget report
|
||||
if: always()
|
||||
run: |
|
||||
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
|
||||
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
|
||||
else
|
||||
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
- name: Upload thread transfer result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer-result.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
|
||||
@@ -747,15 +747,9 @@ jobs:
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
@@ -823,7 +817,7 @@ jobs:
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -840,11 +834,11 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
token: ${{ github.token }}
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
@@ -860,7 +854,7 @@ jobs:
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
token: ${{ github.token }}
|
||||
|
||||
deploy_web:
|
||||
name: Deploy hosted web app
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Thread Transfer Report
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish PR comment
|
||||
if: github.event.workflow_run.event == 'pull_request'
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# workflow_run has a write-capable token even for fork PRs. Only load the
|
||||
# publisher from the trusted default branch and never execute PR code.
|
||||
- name: Checkout trusted publisher
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
- name: Test trusted publisher
|
||||
run: node --test .github/scripts/thread-transfer-report.test.cjs
|
||||
|
||||
- id: resolve
|
||||
name: Resolve PR and baseline artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.resolve({ github, context, core });
|
||||
|
||||
- name: Download PR result
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/pr
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
|
||||
- name: Download main baseline
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/main
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
|
||||
- name: Update thread transfer comment
|
||||
if: steps.resolve.outputs.publish == 'true'
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
|
||||
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
|
||||
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
|
||||
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
|
||||
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
|
||||
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
|
||||
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.publish({ github, context, core });
|
||||
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
|
||||
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
|
||||
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
|
||||
- `--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.
|
||||
- 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).
|
||||
- Stop what you started, by the PID you tracked. See rule 1.
|
||||
|
||||
## Test data
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.31",
|
||||
"version": "0.0.32",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
|
||||
import * as ElectronApp from "../electron/ElectronApp.ts";
|
||||
import * as ElectronDialog from "../electron/ElectronDialog.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
|
||||
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
|
||||
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
|
||||
import * as DesktopClerk from "./DesktopClerk.ts";
|
||||
@@ -17,7 +18,9 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
|
||||
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopObservability from "./DesktopObservability.ts";
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShutdown from "./DesktopShutdown.ts";
|
||||
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
|
||||
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
|
||||
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
const clerk = yield* DesktopClerk.DesktopClerk;
|
||||
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
|
||||
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
|
||||
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
|
||||
yield* shellEnvironment.installIntoProcess;
|
||||
const hasCommandLinePasswordStore =
|
||||
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
|
||||
const linuxElectronOptions =
|
||||
environment.platform === "linux" && !hasCommandLinePasswordStore
|
||||
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
|
||||
: preReadyElectronOptions.linux;
|
||||
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
|
||||
if (
|
||||
linuxElectronOptions.passwordStore !== null ||
|
||||
preReadyElectronOptions.linux?.passwordStore !== null
|
||||
) {
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
}
|
||||
if (linuxElectronOptions.passwordStore !== null) {
|
||||
yield* electronApp.appendCommandLineSwitch(
|
||||
"password-store",
|
||||
linuxElectronOptions.passwordStore,
|
||||
);
|
||||
}
|
||||
}
|
||||
const userDataPath = yield* appIdentity.resolveUserDataPath;
|
||||
yield* electronApp.setPath("userData", userDataPath);
|
||||
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
|
||||
yield* desktopSettings.load;
|
||||
|
||||
if (environment.platform === "linux") {
|
||||
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
|
||||
if (linuxElectronOptions !== null) {
|
||||
yield* logStartupInfo("linux password store configured", {
|
||||
passwordStore: hasCommandLinePasswordStore
|
||||
? "command-line"
|
||||
: (linuxElectronOptions.passwordStore ?? "electron-default"),
|
||||
xdgCurrentDesktop: process.env.XDG_CURRENT_DESKTOP ?? null,
|
||||
xdgSessionDesktop: process.env.XDG_SESSION_DESKTOP ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
yield* appIdentity.configure;
|
||||
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
|
||||
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
|
||||
);
|
||||
yield* logStartupInfo("app ready");
|
||||
if (environment.platform === "linux") {
|
||||
const selectedBackend = yield* safeStorage.selectedStorageBackend;
|
||||
yield* logStartupInfo("safe storage ready", {
|
||||
backend: Option.getOrElse(selectedBackend, () => "unknown"),
|
||||
});
|
||||
}
|
||||
yield* appIdentity.configure;
|
||||
yield* applicationMenu.configure;
|
||||
yield* updates.configure;
|
||||
yield* linuxUrlHandler.register;
|
||||
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
|
||||
}).pipe(Effect.withSpan("desktop.startup"));
|
||||
|
||||
|
||||
@@ -64,6 +64,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
|
||||
}),
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
|
||||
export const DesktopConfig = Config.all({
|
||||
appDataDirectory: trimmedString("APPDATA"),
|
||||
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
|
||||
xdgDataHome: trimmedString("XDG_DATA_HOME"),
|
||||
t3Home: trimmedString("T3CODE_HOME"),
|
||||
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
|
||||
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
|
||||
|
||||
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
|
||||
return decoded.slice("encrypted:".length);
|
||||
});
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
|
||||
import * as NodePath from "node:path";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
resolveEarlyLinuxElectronOptions,
|
||||
resolveEarlyLinuxPasswordStorePreference,
|
||||
} from "./DesktopEarlyElectronStartup.ts";
|
||||
|
||||
describe("DesktopEarlyElectronStartup", () => {
|
||||
const joinPath = NodePath.posix.join;
|
||||
|
||||
it("reads the persisted linux password-store preference before Electron is ready", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("accepts JSONC in the early desktop settings file", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/home/user/.t3-test" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => `{
|
||||
// manually edited setting
|
||||
"linuxPasswordStore": "gnome-libsecret",
|
||||
}`,
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
|
||||
it("falls back to auto when the early settings document is missing or invalid", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: () => {
|
||||
throw new Error("missing");
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "auto");
|
||||
});
|
||||
|
||||
it("preserves absolute root paths when resolving early settings", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: { T3CODE_HOME: "/" },
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet6");
|
||||
});
|
||||
|
||||
it("resolves the early linux Electron switches", () => {
|
||||
const options = resolveEarlyLinuxElectronOptions({
|
||||
env: {
|
||||
T3CODE_HOME: "/home/user/.t3-test",
|
||||
XDG_CURRENT_DESKTOP: "niri",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "auto" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(options, {
|
||||
linuxWmClass: "t3code-dev",
|
||||
passwordStore: "gnome-libsecret",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "kwallet" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "kwallet");
|
||||
});
|
||||
|
||||
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference({
|
||||
env: {
|
||||
T3CODE_HOME: " ",
|
||||
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
|
||||
},
|
||||
homeDirectory: "/home/user",
|
||||
joinPath,
|
||||
readFileString: (path) => {
|
||||
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
|
||||
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(preference, "gnome-libsecret");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,90 @@
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStoreSwitch,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import {
|
||||
resolveDesktopBaseDir,
|
||||
resolveDesktopStateDir,
|
||||
type JoinPath,
|
||||
} from "./DesktopStatePaths.ts";
|
||||
|
||||
interface EarlyDesktopSettingsInput {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly readFileString: (path: string) => string;
|
||||
}
|
||||
|
||||
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
|
||||
|
||||
export interface EarlyLinuxElectronOptions {
|
||||
readonly linuxWmClass: string;
|
||||
readonly passwordStore: LinuxPasswordStoreSwitch | null;
|
||||
}
|
||||
|
||||
const trimNonEmpty = (value: string | undefined): string | null => {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
};
|
||||
|
||||
const EarlyDesktopSettingsJson = fromLenientJson(
|
||||
Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
}),
|
||||
);
|
||||
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
|
||||
|
||||
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
|
||||
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
|
||||
|
||||
function resolveEarlyDesktopSettingsPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
}): string {
|
||||
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory: input.homeDirectory,
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment: isDevelopmentEnvironment(input.env),
|
||||
joinPath: input.joinPath,
|
||||
t3Home,
|
||||
});
|
||||
return input.joinPath(stateDir, "desktop-settings.json");
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxPasswordStorePreference(
|
||||
input: EarlyDesktopSettingsInput,
|
||||
): LinuxPasswordStorePreference {
|
||||
const settingsPath = resolveEarlyDesktopSettingsPath(input);
|
||||
try {
|
||||
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
|
||||
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
|
||||
} catch {
|
||||
return DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveEarlyLinuxElectronOptions(
|
||||
input: EarlyLinuxElectronOptionsInput,
|
||||
): EarlyLinuxElectronOptions {
|
||||
const preference = resolveEarlyLinuxPasswordStorePreference(input);
|
||||
return {
|
||||
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
|
||||
passwordStore: resolveLinuxPasswordStoreSwitch({
|
||||
preference,
|
||||
env: input.env,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
|
||||
|
||||
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
|
||||
import * as DesktopConfig from "./DesktopConfig.ts";
|
||||
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
|
||||
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
|
||||
|
||||
export interface MakeDesktopEnvironmentInput {
|
||||
@@ -66,6 +67,8 @@ export class DesktopEnvironment extends Context.Service<
|
||||
readonly appUserModelId: string;
|
||||
readonly linuxDesktopEntryName: string;
|
||||
readonly linuxWmClass: string;
|
||||
readonly linuxApplicationsDir: string;
|
||||
readonly appImagePath: Option.Option<string>;
|
||||
readonly userDataDirName: string;
|
||||
readonly legacyUserDataDirName: string;
|
||||
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
|
||||
@@ -147,8 +150,11 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
: input.platform === "darwin"
|
||||
? path.join(homeDirectory, "Library", "Application Support")
|
||||
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
|
||||
const configuredBaseDir = config.t3Home;
|
||||
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
|
||||
const baseDir = resolveDesktopBaseDir({
|
||||
homeDirectory,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const rootDir = path.resolve(input.dirname, "../../..");
|
||||
const appRoot = input.isPackaged ? input.appPath : rootDir;
|
||||
const branding = resolveDesktopAppBranding({
|
||||
@@ -156,12 +162,18 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
appVersion: input.appVersion,
|
||||
});
|
||||
const displayName = branding.displayName;
|
||||
const stateDir = path.join(
|
||||
const stateDir = resolveDesktopStateDir({
|
||||
baseDir,
|
||||
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
|
||||
);
|
||||
isDevelopment,
|
||||
joinPath: path.join,
|
||||
t3Home: config.t3Home,
|
||||
});
|
||||
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const linuxApplicationsDir = path.join(
|
||||
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
|
||||
"applications",
|
||||
);
|
||||
const resourcesPath = input.resourcesPath;
|
||||
|
||||
return DesktopEnvironment.of({
|
||||
@@ -205,6 +217,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
|
||||
),
|
||||
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
|
||||
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
|
||||
linuxApplicationsDir,
|
||||
appImagePath: config.appImagePath,
|
||||
userDataDirName,
|
||||
legacyUserDataDirName,
|
||||
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
|
||||
|
||||
@@ -35,6 +35,7 @@ describe("DesktopLifecycle", () => {
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: (listener) =>
|
||||
Effect.acquireRelease(
|
||||
Effect.sync(() => {
|
||||
@@ -77,6 +78,7 @@ describe("DesktopLifecycle", () => {
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: () => Effect.void,
|
||||
zoomMain: () => Effect.void,
|
||||
syncAppearance: Effect.void,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
|
||||
|
||||
interface RecordedRegistration {
|
||||
readonly directories: string[];
|
||||
readonly files: Array<{ readonly path: string; readonly content: string }>;
|
||||
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
|
||||
}
|
||||
|
||||
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
|
||||
DesktopEnvironment.DesktopEnvironment.of({
|
||||
platform: "linux",
|
||||
isPackaged: true,
|
||||
isDevelopment: false,
|
||||
displayName: "T3 Code (Alpha)",
|
||||
linuxWmClass: "t3code",
|
||||
linuxApplicationsDir: "/home/alice/.local/share/applications",
|
||||
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
|
||||
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
|
||||
...overrides,
|
||||
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
|
||||
|
||||
const mockProcess = (exitCode: number) =>
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
|
||||
const makeHandlerLayer = (
|
||||
recorded: RecordedRegistration,
|
||||
input: {
|
||||
readonly environment?: Record<string, unknown>;
|
||||
readonly xdgMimeExitCode?: number;
|
||||
readonly writeError?: PlatformError.PlatformError;
|
||||
} = {},
|
||||
) =>
|
||||
DesktopLinuxUrlHandler.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
|
||||
FileSystem.layerNoop({
|
||||
makeDirectory: (path) =>
|
||||
Effect.sync(() => {
|
||||
recorded.directories.push(path);
|
||||
}),
|
||||
writeFileString: (path, content) =>
|
||||
input.writeError
|
||||
? Effect.fail(input.writeError)
|
||||
: Effect.sync(() => {
|
||||
recorded.files.push({ path, content });
|
||||
}),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
recorded.commands.push({
|
||||
command: childProcess.command,
|
||||
args: childProcess.args,
|
||||
});
|
||||
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const runRegister = (
|
||||
recorded: RecordedRegistration,
|
||||
input: Parameters<typeof makeHandlerLayer>[1] = {},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
|
||||
yield* handler.register;
|
||||
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
|
||||
|
||||
const emptyRecording = (): RecordedRegistration => ({
|
||||
directories: [],
|
||||
files: [],
|
||||
commands: [],
|
||||
});
|
||||
|
||||
describe("DesktopLinuxUrlHandler", () => {
|
||||
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
|
||||
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
|
||||
displayName: "T3 Code (Nightly)",
|
||||
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
|
||||
scheme: "t3code",
|
||||
});
|
||||
|
||||
assert.include(entry, "[Desktop Entry]");
|
||||
assert.include(entry, "Name=T3 Code (Nightly)");
|
||||
// Exec composes both escaping layers: a literal backslash becomes four
|
||||
// backslashes in the file, a quote three characters, a dollar sign two
|
||||
// backslashes plus the sign.
|
||||
assert.include(
|
||||
entry,
|
||||
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
|
||||
);
|
||||
assert.include(entry, "NoDisplay=true");
|
||||
assert.notInclude(entry, "StartupWMClass=");
|
||||
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
|
||||
});
|
||||
|
||||
it("carries structured context on registration errors", () => {
|
||||
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme: "t3code",
|
||||
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
cause: new Error("boom"),
|
||||
});
|
||||
assert.equal(
|
||||
writeError.message,
|
||||
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
|
||||
);
|
||||
assert.equal(
|
||||
writeError.desktopEntryPath,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
|
||||
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme: "t3code",
|
||||
exitCode: 4,
|
||||
});
|
||||
assert.equal(
|
||||
exitError.message,
|
||||
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded);
|
||||
|
||||
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
|
||||
assert.equal(recorded.files.length, 1);
|
||||
assert.equal(
|
||||
recorded.files[0]?.path,
|
||||
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
);
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
|
||||
);
|
||||
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
|
||||
assert.deepEqual(recorded.commands, [
|
||||
{
|
||||
command: "xdg-mime",
|
||||
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("falls back to the process executable outside an AppImage", () => {
|
||||
const recorded = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
|
||||
|
||||
assert.include(
|
||||
recorded.files[0]?.content,
|
||||
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("does nothing on other platforms or unpackaged builds", () => {
|
||||
const nonLinux = emptyRecording();
|
||||
const unpackaged = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
|
||||
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
|
||||
|
||||
for (const recorded of [nonLinux, unpackaged]) {
|
||||
assert.deepEqual(recorded.directories, []);
|
||||
assert.deepEqual(recorded.files, []);
|
||||
assert.deepEqual(recorded.commands, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it.effect("never fails startup when registration cannot complete", () => {
|
||||
const xdgMimeFailed = emptyRecording();
|
||||
const writeFailed = emptyRecording();
|
||||
|
||||
return Effect.gen(function* () {
|
||||
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
|
||||
yield* runRegister(writeFailed, {
|
||||
writeError: PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "writeFileString",
|
||||
description: "read-only filesystem",
|
||||
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(xdgMimeFailed.files.length, 1);
|
||||
assert.deepEqual(writeFailed.commands, []);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as ChildProcess from "effect/unstable/process/ChildProcess";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
|
||||
import { makeComponentLogger } from "./DesktopObservability.ts";
|
||||
|
||||
// Linux ships as an AppImage, so the .desktop entry users end up with is
|
||||
// created by whatever integration tool they use (AppImageLauncher names it
|
||||
// appimagekit_<hash>-….desktop) and its filename is not under our control.
|
||||
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
|
||||
// setDesktopName, which cannot match those files — so the browser keeps
|
||||
// prompting "Choose an application" for every OAuth callback. Instead, write
|
||||
// our own handler entry pointing at the current AppImage and claim the
|
||||
// scheme default via xdg-mime, exactly what the file manager's "set as
|
||||
// default" checkbox would record in mimeapps.list.
|
||||
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
|
||||
|
||||
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
|
||||
|
||||
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
|
||||
"DesktopLinuxUrlHandlerRegistrationError",
|
||||
{
|
||||
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
|
||||
scheme: Schema.String,
|
||||
desktopEntryPath: Schema.optionalKey(Schema.String),
|
||||
exitCode: Schema.optionalKey(Schema.Number),
|
||||
cause: Schema.optionalKey(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
|
||||
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
|
||||
}
|
||||
}
|
||||
|
||||
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
|
||||
|
||||
const escapeDesktopEntryString = (value: string): string =>
|
||||
value
|
||||
.replaceAll("\\", "\\\\")
|
||||
.replaceAll("\n", "\\n")
|
||||
.replaceAll("\r", "\\r")
|
||||
.replaceAll("\t", "\\t");
|
||||
|
||||
// Exec values are unescaped twice by implementations: first the general
|
||||
// string-value rules, then the Exec quoting rules — so writing composes the
|
||||
// layers in reverse. The argument is double-quoted with reserved characters
|
||||
// backslash-escaped and literal percent signs doubled (field codes), and the
|
||||
// general string escaping is applied on top: a literal backslash ends up as
|
||||
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
|
||||
export function escapeDesktopEntryExecArgument(value: string): string {
|
||||
const quoted = value
|
||||
.replaceAll("\\", () => "\\\\")
|
||||
.replaceAll("`", () => "\\`")
|
||||
.replaceAll("$", () => "\\$")
|
||||
.replaceAll('"', () => '\\"')
|
||||
.replaceAll("%", () => "%%");
|
||||
return escapeDesktopEntryString(`"${quoted}"`);
|
||||
}
|
||||
|
||||
// The AppImage integration entry owns the window identity and icon. This
|
||||
// hidden URL-only entry must not compete with it for StartupWMClass matching.
|
||||
export function renderUrlHandlerDesktopEntry(input: {
|
||||
readonly displayName: string;
|
||||
readonly execTarget: string;
|
||||
readonly scheme: string;
|
||||
}): string {
|
||||
return [
|
||||
"[Desktop Entry]",
|
||||
"Type=Application",
|
||||
`Name=${escapeDesktopEntryString(input.displayName)}`,
|
||||
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
|
||||
"Terminal=false",
|
||||
"NoDisplay=true",
|
||||
"StartupNotify=false",
|
||||
`MimeType=x-scheme-handler/${input.scheme};`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export class DesktopLinuxUrlHandler extends Context.Service<
|
||||
DesktopLinuxUrlHandler,
|
||||
{
|
||||
readonly register: Effect.Effect<void>;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
|
||||
const desktopEntryPath = environment.path.join(
|
||||
environment.linuxApplicationsDir,
|
||||
URL_HANDLER_DESKTOP_ENTRY_NAME,
|
||||
);
|
||||
|
||||
const writeDesktopEntry = Effect.gen(function* () {
|
||||
// Inside the mounted AppImage, process.execPath points at a transient
|
||||
// /tmp/.mount_* path — the handler must launch the AppImage itself.
|
||||
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
|
||||
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
desktopEntryPath,
|
||||
renderUrlHandlerDesktopEntry({
|
||||
displayName: environment.displayName,
|
||||
execTarget,
|
||||
scheme,
|
||||
}),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "write-desktop-entry",
|
||||
scheme,
|
||||
desktopEntryPath,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const setDefaultHandler = Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
"xdg-mime",
|
||||
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
|
||||
{
|
||||
stdin: "ignore",
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
},
|
||||
);
|
||||
const handle = yield* spawner.spawn(command);
|
||||
const exitCode = yield* handle.exitCode;
|
||||
if ((exitCode as unknown as number) !== 0) {
|
||||
return yield* new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
exitCode: Number(exitCode),
|
||||
});
|
||||
}
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError((error) =>
|
||||
isRegistrationError(error)
|
||||
? error
|
||||
: new DesktopLinuxUrlHandlerRegistrationError({
|
||||
step: "set-default-handler",
|
||||
scheme,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const register = Effect.gen(function* () {
|
||||
if (environment.platform !== "linux" || !environment.isPackaged) {
|
||||
return;
|
||||
}
|
||||
yield* writeDesktopEntry;
|
||||
yield* setDefaultHandler;
|
||||
yield* logInfo("registered URL scheme handler", { scheme });
|
||||
}).pipe(
|
||||
// Registration is best-effort: a missing xdg-mime or read-only home must
|
||||
// never block startup — the OS chooser remains as fallback.
|
||||
Effect.catch((error) =>
|
||||
logWarning("URL scheme handler registration failed", {
|
||||
scheme,
|
||||
step: error.step,
|
||||
message: error.message,
|
||||
...(error.desktopEntryPath === undefined
|
||||
? {}
|
||||
: { desktopEntryPath: error.desktopEntryPath }),
|
||||
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
|
||||
}),
|
||||
),
|
||||
Effect.withSpan("desktop.linuxUrlHandler.register"),
|
||||
);
|
||||
|
||||
return DesktopLinuxUrlHandler.of({ register });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
|
||||
@@ -0,0 +1,130 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import { beforeEach, vi } from "vite-plus/test";
|
||||
|
||||
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
|
||||
() => ({
|
||||
appendSwitchMock: vi.fn(),
|
||||
getSwitchValueMock: vi.fn(),
|
||||
hasSwitchMock: vi.fn(),
|
||||
registerSchemesMock: vi.fn(),
|
||||
}),
|
||||
);
|
||||
|
||||
vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
getSwitchValue: getSwitchValueMock,
|
||||
hasSwitch: hasSwitchMock,
|
||||
},
|
||||
},
|
||||
protocol: {
|
||||
registerSchemesAsPrivileged: registerSchemesMock,
|
||||
},
|
||||
}));
|
||||
|
||||
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
|
||||
|
||||
describe("DesktopPreReadyPlatform", () => {
|
||||
beforeEach(() => {
|
||||
appendSwitchMock.mockReset();
|
||||
getSwitchValueMock.mockReset();
|
||||
hasSwitchMock.mockReset();
|
||||
registerSchemesMock.mockReset();
|
||||
});
|
||||
|
||||
it("reads an explicit Electron command-line switch value", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: (switchName) => switchName === "password-store",
|
||||
getSwitchValue: (switchName) => {
|
||||
assert.equal(switchName, "password-store");
|
||||
return "basic";
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.equal(value, "basic");
|
||||
});
|
||||
|
||||
it("treats valueless Electron command-line switches as absent", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => true,
|
||||
getSwitchValue: () => "",
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it("returns null for missing Electron command-line switches", () => {
|
||||
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
|
||||
{
|
||||
hasSwitch: () => false,
|
||||
getSwitchValue: () => {
|
||||
throw new Error("Unexpected switch value read.");
|
||||
},
|
||||
},
|
||||
"password-store",
|
||||
);
|
||||
|
||||
assert.isNull(value);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
|
||||
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
|
||||
) {}
|
||||
|
||||
const events: Array<string> = [];
|
||||
registerSchemesMock.mockImplementation(() => {
|
||||
events.push("pre-ready");
|
||||
});
|
||||
|
||||
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
|
||||
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
|
||||
);
|
||||
|
||||
const clerkShapedLayer = Layer.effect(
|
||||
ClerkShaped,
|
||||
Effect.promise(() => Promise.resolve()).pipe(
|
||||
Effect.map(() => {
|
||||
events.push("clerk");
|
||||
return { ready: true as const };
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const runtimeLayer = clerkShapedLayer.pipe(
|
||||
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(preReadyLayer),
|
||||
);
|
||||
|
||||
const result = yield* Effect.all({
|
||||
clerk: ClerkShaped,
|
||||
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
assert.deepEqual(result, {
|
||||
clerk: { ready: true },
|
||||
preReady: {
|
||||
linux: null,
|
||||
linuxPasswordStoreCommandLine: null,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(events, ["pre-ready", "clerk"]);
|
||||
assert.equal(registerSchemesMock.mock.calls.length, 1);
|
||||
assert.equal(appendSwitchMock.mock.calls.length, 0);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
|
||||
import * as NodeFS from "node:fs";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as NodePath from "node:path";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
|
||||
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
|
||||
|
||||
export interface DesktopPreReadyCommandLineReader {
|
||||
readonly hasSwitch: (switchName: string) => boolean;
|
||||
readonly getSwitchValue: (switchName: string) => string;
|
||||
}
|
||||
|
||||
export function readCommandLineSwitchValue(
|
||||
commandLine: DesktopPreReadyCommandLineReader,
|
||||
switchName: string,
|
||||
): string | null {
|
||||
if (!commandLine.hasSwitch(switchName)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const value = commandLine.getSwitchValue(switchName).trim();
|
||||
return value.length > 0 ? value : null;
|
||||
}
|
||||
|
||||
export const resolveEarlyLinuxElectronOptionsFromProcess =
|
||||
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
|
||||
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
|
||||
env: process.env,
|
||||
homeDirectory: NodeOS.homedir(),
|
||||
joinPath: NodePath.posix.join,
|
||||
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
|
||||
});
|
||||
|
||||
export class DesktopPreReadyElectronOptions extends Context.Service<
|
||||
DesktopPreReadyElectronOptions,
|
||||
{
|
||||
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
|
||||
readonly linuxPasswordStoreCommandLine: string | null;
|
||||
}
|
||||
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
|
||||
const linuxPasswordStoreCommandLine =
|
||||
platform === "linux"
|
||||
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
|
||||
: null;
|
||||
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
|
||||
|
||||
if (linux !== null) {
|
||||
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
|
||||
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
|
||||
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
|
||||
}
|
||||
}
|
||||
|
||||
return { linux, linuxPasswordStoreCommandLine };
|
||||
});
|
||||
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
|
||||
|
||||
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
|
||||
// observe app readiness before scheme privileges and command-line switches exist.
|
||||
export const layer = Layer.mergeAll(
|
||||
ElectronProtocol.layerSchemePrivileges,
|
||||
Layer.effect(DesktopPreReadyElectronOptions, make),
|
||||
);
|
||||
@@ -0,0 +1,32 @@
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
export type JoinPath = (first: string, ...segments: string[]) => string;
|
||||
|
||||
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
|
||||
if (Option.isNone(t3Home)) {
|
||||
return Option.none();
|
||||
}
|
||||
const trimmed = t3Home.value.trim();
|
||||
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
|
||||
}
|
||||
|
||||
export function resolveDesktopBaseDir(input: {
|
||||
readonly homeDirectory: string;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
|
||||
input.joinPath(input.homeDirectory, ".t3"),
|
||||
);
|
||||
}
|
||||
|
||||
export function resolveDesktopStateDir(input: {
|
||||
readonly baseDir: string;
|
||||
readonly isDevelopment: boolean;
|
||||
readonly joinPath: JoinPath;
|
||||
readonly t3Home: Option.Option<string>;
|
||||
}): string {
|
||||
const useDevSubdir =
|
||||
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
|
||||
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
|
||||
}
|
||||
@@ -91,6 +91,7 @@ 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"]),
|
||||
),
|
||||
|
||||
@@ -14,6 +14,7 @@ const {
|
||||
quitMock,
|
||||
relaunchMock,
|
||||
removeListenerMock,
|
||||
removeSwitchMock,
|
||||
setAboutPanelOptionsMock,
|
||||
setAppUserModelIdMock,
|
||||
setAsDefaultProtocolClientMock,
|
||||
@@ -34,6 +35,7 @@ const {
|
||||
quitMock: vi.fn(),
|
||||
relaunchMock: vi.fn(),
|
||||
removeListenerMock: vi.fn(),
|
||||
removeSwitchMock: vi.fn(),
|
||||
setAboutPanelOptionsMock: vi.fn(),
|
||||
setAppUserModelIdMock: vi.fn(),
|
||||
setAsDefaultProtocolClientMock: vi.fn(() => true),
|
||||
@@ -52,6 +54,7 @@ vi.mock("electron", () => ({
|
||||
app: {
|
||||
commandLine: {
|
||||
appendSwitch: appendSwitchMock,
|
||||
removeSwitch: removeSwitchMock,
|
||||
},
|
||||
dock: {
|
||||
setIcon: setDockIconMock,
|
||||
@@ -89,6 +92,7 @@ describe("ElectronApp", () => {
|
||||
quitMock.mockClear();
|
||||
relaunchMock.mockClear();
|
||||
removeListenerMock.mockClear();
|
||||
removeSwitchMock.mockClear();
|
||||
setPathMock.mockClear();
|
||||
});
|
||||
|
||||
@@ -178,4 +182,13 @@ describe("ElectronApp", () => {
|
||||
]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
|
||||
it.effect("removes command-line switches through the service", () =>
|
||||
Effect.gen(function* () {
|
||||
const electronApp = yield* ElectronApp.ElectronApp;
|
||||
yield* electronApp.removeCommandLineSwitch("password-store");
|
||||
|
||||
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
|
||||
}).pipe(Effect.provide(ElectronApp.layer)),
|
||||
);
|
||||
});
|
||||
@@ -69,6 +69,7 @@ export class ElectronApp extends Context.Service<
|
||||
readonly onBeforeQuitForUpdate: (
|
||||
listener: () => void,
|
||||
) => Effect.Effect<void, never, Scope.Scope>;
|
||||
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
|
||||
readonly on: <Args extends ReadonlyArray<unknown>>(
|
||||
eventName: string,
|
||||
listener: (...args: Args) => void,
|
||||
@@ -191,6 +192,10 @@ export const make = ElectronApp.of({
|
||||
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
|
||||
}),
|
||||
).pipe(Effect.asVoid),
|
||||
removeCommandLineSwitch: (switchName) =>
|
||||
Effect.sync(() => {
|
||||
Electron.app.commandLine.removeSwitch(switchName);
|
||||
}),
|
||||
on: addScopedAppListener,
|
||||
});
|
||||
|
||||
|
||||
@@ -23,6 +23,21 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
|
||||
"ElectronDialogPickFilesError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
@@ -69,6 +84,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
@@ -81,6 +97,12 @@ export interface ElectronDialogPickFolderInput {
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface ElectronDialogPickFilesInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
@@ -92,6 +114,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>;
|
||||
@@ -137,6 +162,32 @@ export const make = ElectronDialog.of({
|
||||
}
|
||||
return Option.fromNullishOr(result.filePaths[0]);
|
||||
}),
|
||||
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = {
|
||||
properties: ["openFile", "multiSelections"],
|
||||
filters: [...input.filters],
|
||||
...(defaultPath === null ? {} : { defaultPath }),
|
||||
};
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFilesError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
|
||||
@@ -105,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Must run synchronously during process bootstrap, before Electron emits `ready`.
|
||||
*/
|
||||
export function registerDesktopSchemePrivilegesSync(): void {
|
||||
Electron.protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
scheme: DESKTOP_PRODUCTION_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
scheme: DESKTOP_DEVELOPMENT_SCHEME,
|
||||
privileges: {
|
||||
standard: true,
|
||||
secure: true,
|
||||
supportFetchAPI: true,
|
||||
corsEnabled: true,
|
||||
},
|
||||
},
|
||||
]);
|
||||
}
|
||||
|
||||
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
|
||||
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
|
||||
);
|
||||
|
||||
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
|
||||
|
||||
async function proxyRequest(
|
||||
request: Request,
|
||||
targetOrigin: URL,
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import * as Electron from "electron";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
|
||||
const electronSafeStorageErrorFields = {
|
||||
cause: Schema.Defect(),
|
||||
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
|
||||
readonly decryptString: (
|
||||
value: Uint8Array,
|
||||
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
|
||||
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
|
||||
}
|
||||
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
|
||||
|
||||
export const make = ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
export const make = Effect.gen(function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
|
||||
return ElectronSafeStorage.of({
|
||||
isEncryptionAvailable: Effect.try({
|
||||
try: () => Electron.safeStorage.isEncryptionAvailable(),
|
||||
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
encryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.encryptString(value),
|
||||
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
|
||||
}),
|
||||
decryptString: (value) =>
|
||||
Effect.try({
|
||||
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
|
||||
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
|
||||
}),
|
||||
selectedStorageBackend: Effect.sync(() => {
|
||||
if (platform !== "linux") {
|
||||
return Option.none();
|
||||
}
|
||||
try {
|
||||
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
|
||||
} catch {
|
||||
return Option.none();
|
||||
}
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.succeed(ElectronSafeStorage, make);
|
||||
export const layer = Layer.effect(ElectronSafeStorage, make);
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
pickThemeFiles,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
@@ -79,6 +80,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);
|
||||
|
||||
@@ -1,4 +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";
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
DesktopPreviewSetColorSchemeInputSchema,
|
||||
DesktopPreviewTabInputSchema,
|
||||
DesktopPreviewWebviewConfigSchema,
|
||||
PreviewAnnotationPayloadSchema,
|
||||
PreviewAnnotationSubmissionResultSchema,
|
||||
PreviewAutomationSnapshot,
|
||||
PreviewAutomationStatus,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -227,7 +227,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
|
||||
export const pickElement = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
|
||||
payload: DesktopPreviewTabInputSchema,
|
||||
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
|
||||
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
|
||||
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
|
||||
const manager = yield* PreviewManager.PreviewManager;
|
||||
return yield* manager.pickElement(tabId);
|
||||
|
||||
@@ -3,10 +3,15 @@ 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";
|
||||
@@ -268,3 +273,49 @@ 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: "" })),
|
||||
);
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
resolveLinuxPasswordStoreSwitch,
|
||||
resolveLinuxSecretStorageUnavailableMessage,
|
||||
} from "./linuxSecretStorage.ts";
|
||||
|
||||
const autoSwitch = (env: NodeJS.ProcessEnv) =>
|
||||
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
|
||||
|
||||
describe("linuxSecretStorage", () => {
|
||||
it("preserves explicit supported password-store preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
|
||||
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
|
||||
});
|
||||
|
||||
it("falls back to auto for missing or unsupported preferences", () => {
|
||||
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
|
||||
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
|
||||
});
|
||||
|
||||
it("uses explicit preferences instead of the auto heuristic", () => {
|
||||
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
|
||||
).toBe(preference);
|
||||
// An explicit preference also wins where auto would have stayed out of the way.
|
||||
expect(
|
||||
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
|
||||
).toBe(preference);
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
|
||||
});
|
||||
|
||||
it("does not force a password-store for desktops Electron already recognizes", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
|
||||
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({})).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
|
||||
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
|
||||
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("overrides KDE sessions identified only by legacy variables", () => {
|
||||
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
|
||||
// basic text for the rest. Either way these are the variables a previous session leaves behind,
|
||||
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
|
||||
for (const session of [
|
||||
"kde",
|
||||
"kde-plasma",
|
||||
"kde4",
|
||||
"plasma",
|
||||
"plasmawayland",
|
||||
"plasmawayland-dev",
|
||||
"plasmax11",
|
||||
"plasmax11-dev",
|
||||
]) {
|
||||
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
|
||||
}
|
||||
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
|
||||
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
});
|
||||
|
||||
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
|
||||
expect(
|
||||
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
|
||||
).toBe("gnome-libsecret");
|
||||
// A previous KDE session left these behind; the compositor running now is not KDE.
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
|
||||
"gnome-libsecret",
|
||||
);
|
||||
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
|
||||
expect(
|
||||
autoSwitch({
|
||||
XDG_CURRENT_DESKTOP: "Hyprland",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
KDE_SESSION_VERSION: "6",
|
||||
}),
|
||||
).toBe("gnome-libsecret");
|
||||
});
|
||||
|
||||
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "gnome-libsecret",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
|
||||
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet6",
|
||||
selectedBackend: "gnome_libsecret",
|
||||
env: { XDG_CURRENT_DESKTOP: "niri" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "kwallet",
|
||||
selectedBackend: "gnome-libsecret",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
});
|
||||
|
||||
it("uses KWallet remediation wording for KDE-looking sessions", () => {
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "kwallet6",
|
||||
env: {},
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { XDG_CURRENT_DESKTOP: "KDE" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { DESKTOP_SESSION: "plasmawayland" },
|
||||
}),
|
||||
).toContain("KWallet");
|
||||
// A desktop name outranks a bare KDE marker when choosing the wording.
|
||||
expect(
|
||||
resolveLinuxSecretStorageUnavailableMessage({
|
||||
configuredPreference: "auto",
|
||||
selectedBackend: "unknown",
|
||||
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
|
||||
}),
|
||||
).toContain("GNOME Keyring");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
export type LinuxPasswordStorePreference =
|
||||
| "auto"
|
||||
| "gnome-libsecret"
|
||||
| "kwallet"
|
||||
| "kwallet5"
|
||||
| "kwallet6";
|
||||
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
|
||||
|
||||
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
|
||||
|
||||
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
|
||||
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
|
||||
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
|
||||
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
|
||||
"Deepin",
|
||||
"GNOME",
|
||||
"Pantheon",
|
||||
"UKUI",
|
||||
"Unity",
|
||||
"X-Cinnamon",
|
||||
"XFCE",
|
||||
]);
|
||||
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
|
||||
const ELECTRON_KDE_DESKTOP = "KDE";
|
||||
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
|
||||
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
|
||||
|
||||
const KDE_NAME_PREFIXES = ["kde", "plasma"];
|
||||
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
|
||||
|
||||
export function normalizeLinuxPasswordStorePreference(
|
||||
value: unknown,
|
||||
): LinuxPasswordStorePreference {
|
||||
return value === "gnome-libsecret" ||
|
||||
value === "kwallet" ||
|
||||
value === "kwallet5" ||
|
||||
value === "kwallet6"
|
||||
? value
|
||||
: DEFAULT_LINUX_PASSWORD_STORE;
|
||||
}
|
||||
|
||||
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
|
||||
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
|
||||
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
|
||||
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
|
||||
// specific one sets linuxPasswordStore explicitly.
|
||||
export function resolveLinuxPasswordStoreSwitch(input: {
|
||||
readonly preference: LinuxPasswordStorePreference;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): LinuxPasswordStoreSwitch | null {
|
||||
if (input.preference !== "auto") {
|
||||
return input.preference;
|
||||
}
|
||||
|
||||
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
|
||||
}
|
||||
|
||||
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
|
||||
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
|
||||
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
|
||||
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
|
||||
// it lands on the same backend.
|
||||
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
|
||||
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
|
||||
const trimmed = name.trim();
|
||||
if (trimmed.length === 0) {
|
||||
continue;
|
||||
}
|
||||
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveLinuxSecretStorageUnavailableMessage(input: {
|
||||
readonly configuredPreference: LinuxPasswordStorePreference;
|
||||
readonly selectedBackend: string | null;
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
}): string {
|
||||
if (input.configuredPreference === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
input.configuredPreference === "kwallet" ||
|
||||
input.configuredPreference === "kwallet5" ||
|
||||
input.configuredPreference === "kwallet6"
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
|
||||
if (backend === "gnome-libsecret") {
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
if (
|
||||
backend === "kwallet" ||
|
||||
backend === "kwallet5" ||
|
||||
backend === "kwallet6" ||
|
||||
looksLikeKdeSession(input.env)
|
||||
) {
|
||||
return getKWalletRemediationMessage();
|
||||
}
|
||||
|
||||
return getGnomeKeyringRemediationMessage();
|
||||
}
|
||||
|
||||
function getGnomeKeyringRemediationMessage(): string {
|
||||
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
|
||||
}
|
||||
|
||||
function getKWalletRemediationMessage(): string {
|
||||
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
|
||||
}
|
||||
|
||||
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
|
||||
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
|
||||
// rather than an unprotected credential store.
|
||||
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
|
||||
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
|
||||
if (currentDesktopNames.length > 0) {
|
||||
return currentDesktopNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
const legacyNames = legacyDesktopNames(env);
|
||||
if (legacyNames.length > 0) {
|
||||
return legacyNames.some(isKdeDesktopName);
|
||||
}
|
||||
|
||||
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
|
||||
}
|
||||
|
||||
function isKdeDesktopName(name: string): boolean {
|
||||
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
|
||||
}
|
||||
|
||||
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
|
||||
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function nonEmptyDesktopNames(value: string | undefined): string[] {
|
||||
return splitDesktopNameList(value).flatMap((entry) => {
|
||||
const normalized = normalizeDesktopName(entry);
|
||||
return normalized ? [normalized] : [];
|
||||
});
|
||||
}
|
||||
|
||||
function isSet(value: string | undefined): boolean {
|
||||
return Boolean(value?.trim());
|
||||
}
|
||||
|
||||
function isAffirmativeFlag(value: string | undefined): boolean {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
|
||||
}
|
||||
|
||||
function splitDesktopNameList(value: string | undefined): string[] {
|
||||
return value?.split(":") ?? [];
|
||||
}
|
||||
|
||||
function normalizeDesktopName(value: string | undefined): string | null {
|
||||
const normalized = value?.trim().toLowerCase();
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
|
||||
function normalizeSelectedStorageBackend(value: string | null): string | null {
|
||||
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
|
||||
return normalized && normalized.length > 0 ? normalized : null;
|
||||
}
|
||||
@@ -43,12 +43,14 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
|
||||
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
|
||||
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
|
||||
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
|
||||
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
|
||||
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
|
||||
import * as DesktopObservability from "./app/DesktopObservability.ts";
|
||||
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
|
||||
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
|
||||
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
|
||||
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
|
||||
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
|
||||
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
|
||||
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
|
||||
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
|
||||
@@ -181,6 +183,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
|
||||
const desktopApplicationLayer = Layer.mergeAll(
|
||||
DesktopLifecycle.layer,
|
||||
DesktopApplicationMenu.layer,
|
||||
DesktopLinuxUrlHandler.layer,
|
||||
DesktopShellEnvironment.layer,
|
||||
desktopSshLayer,
|
||||
).pipe(
|
||||
@@ -195,16 +198,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
|
||||
Layer.provideMerge(ElectronApp.layer),
|
||||
);
|
||||
|
||||
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
);
|
||||
|
||||
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
|
||||
// yield and let Electron emit ready.
|
||||
const desktopRuntimeLayer = desktopClerkLayer.pipe(
|
||||
Layer.flatMap((clerkContext) =>
|
||||
desktopApplicationLayer.pipe(
|
||||
Layer.provideMerge(Layer.succeedContext(clerkContext)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(NodeHttpClient.layerUndici),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(electronLayer),
|
||||
),
|
||||
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
|
||||
),
|
||||
Layer.provideMerge(DesktopPreReadyPlatform.layer),
|
||||
);
|
||||
|
||||
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -97,6 +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) =>
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
|
||||
const keyboardEvent = (
|
||||
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
|
||||
) => ({
|
||||
key: "Enter",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: false,
|
||||
isComposing: false,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("resolveAnnotationSubmission", () => {
|
||||
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
|
||||
});
|
||||
|
||||
it("leaves Shift+Enter and composition events available for editing", () => {
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
|
||||
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
|
||||
|
||||
interface AnnotationKeyboardEvent {
|
||||
readonly key: string;
|
||||
readonly metaKey: boolean;
|
||||
readonly ctrlKey: boolean;
|
||||
readonly shiftKey: boolean;
|
||||
readonly isComposing: boolean;
|
||||
}
|
||||
|
||||
export function resolveAnnotationSubmission(
|
||||
event: AnnotationKeyboardEvent,
|
||||
): PreviewAnnotationSubmission | null {
|
||||
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
|
||||
return event.metaKey || event.ctrlKey ? "send" : "attach";
|
||||
}
|
||||
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
|
||||
"clipboard-sanitized-write",
|
||||
"notifications",
|
||||
"geolocation",
|
||||
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
|
||||
// and silently granting it would hand every page the user's installed-font
|
||||
// fingerprint (and font file bytes via FontData.blob()). The app's own font
|
||||
// picker runs in the main window session, which is unaffected by this list.
|
||||
]);
|
||||
|
||||
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
|
||||
|
||||
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isPreviewRefreshShortcut", () => {
|
||||
const input = (overrides: Partial<Electron.Input> = {}) =>
|
||||
({
|
||||
type: "keyDown",
|
||||
key: "r",
|
||||
meta: true,
|
||||
control: false,
|
||||
shift: false,
|
||||
alt: false,
|
||||
...overrides,
|
||||
}) as Electron.Input;
|
||||
|
||||
it("recognizes the platform refresh chord without matching modified variants", () => {
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
|
||||
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const {
|
||||
browserWindowConstructor,
|
||||
createFromPath,
|
||||
|
||||
@@ -11,6 +11,7 @@ import type {
|
||||
DesktopPreviewPointerEvent,
|
||||
PreviewAnnotationPayload,
|
||||
PreviewAnnotationRect,
|
||||
PreviewAnnotationSubmissionResult,
|
||||
DesktopPreviewRecordingArtifact,
|
||||
DesktopPreviewRecordingFrame,
|
||||
DesktopPreviewScreenshotArtifact,
|
||||
@@ -109,7 +110,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
|
||||
colorScheme: "light",
|
||||
radius: "0.625rem",
|
||||
@@ -406,6 +407,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
|
||||
{ key: "w", meta: true, shift: false, control: false },
|
||||
]);
|
||||
|
||||
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
|
||||
input.type === "keyDown" &&
|
||||
input.key.toLowerCase() === "r" &&
|
||||
(input.meta || input.control) &&
|
||||
!input.shift &&
|
||||
!input.alt;
|
||||
|
||||
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
|
||||
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
|
||||
if (value.kind === "pointer") {
|
||||
@@ -1365,6 +1373,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
});
|
||||
});
|
||||
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
|
||||
if (isPreviewRefreshShortcut(input)) {
|
||||
event.preventDefault();
|
||||
runFork(
|
||||
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
|
||||
wc.reload(),
|
||||
).pipe(Effect.ignore),
|
||||
);
|
||||
return;
|
||||
}
|
||||
runFork(forwardShortcut(event, input));
|
||||
};
|
||||
yield* Scope.addFinalizer(
|
||||
@@ -1792,7 +1809,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
const wc = yield* requireWebContents(tabId);
|
||||
yield* cancelPickElement(tabId);
|
||||
const annotationTheme = yield* Ref.get(annotationThemeRef);
|
||||
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
|
||||
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
|
||||
(resume) => {
|
||||
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
|
||||
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
|
||||
@@ -1807,14 +1824,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
);
|
||||
});
|
||||
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
|
||||
payload: PreviewAnnotationPayload | null,
|
||||
payload: PreviewAnnotationSubmissionResult | null,
|
||||
) {
|
||||
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
|
||||
if (!active || active.cancel !== cancel) return;
|
||||
yield* cleanup();
|
||||
resume(Effect.succeed(payload));
|
||||
});
|
||||
const settle = (payload: PreviewAnnotationPayload | null) => {
|
||||
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
|
||||
runFork(settlePick(payload));
|
||||
};
|
||||
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
|
||||
@@ -1844,11 +1861,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
return;
|
||||
}
|
||||
const cropRect = normalizeCaptureRect(args[1]);
|
||||
const submission = args[2] === "send" ? "send" : "attach";
|
||||
runFork(
|
||||
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
|
||||
Effect.matchEffect({
|
||||
onFailure: () => Effect.sync(() => settle(payload)),
|
||||
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
|
||||
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
|
||||
onSuccess: (screenshot) =>
|
||||
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
|
||||
}),
|
||||
Effect.ensuring(
|
||||
attempt(
|
||||
@@ -3586,7 +3605,7 @@ export class PreviewManager extends Context.Service<
|
||||
) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly pickElement: (
|
||||
tabId: string,
|
||||
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
|
||||
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
|
||||
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
|
||||
readonly captureScreenshot: (
|
||||
tabId: string,
|
||||
|
||||
@@ -11,8 +11,10 @@ import type {
|
||||
PreviewAnnotationRegionTarget,
|
||||
PreviewAnnotationStrokeTarget,
|
||||
PreviewAnnotationStyleChange,
|
||||
PreviewAnnotationSubmission,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
|
||||
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
|
||||
import {
|
||||
ANNOTATION_CAPTURED_CHANNEL,
|
||||
@@ -426,7 +428,7 @@ function startAnnotation(): void {
|
||||
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
|
||||
composerRow.appendChild(dragHandle);
|
||||
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot");
|
||||
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
|
||||
submit.className +=
|
||||
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
|
||||
composerRow.appendChild(submit);
|
||||
@@ -1182,7 +1184,7 @@ function startAnnotation(): void {
|
||||
refreshToolButtons();
|
||||
};
|
||||
|
||||
submit.addEventListener("click", () => {
|
||||
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
|
||||
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
|
||||
return;
|
||||
pendingCapture = true;
|
||||
@@ -1223,13 +1225,18 @@ function startAnnotation(): void {
|
||||
...regions.map((region) => region.rect),
|
||||
...strokes.map((stroke) => stroke.bounds),
|
||||
]);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
|
||||
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
|
||||
});
|
||||
});
|
||||
comment.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
|
||||
};
|
||||
submit.addEventListener("click", () => submitAnnotation("attach"));
|
||||
root.addEventListener("keydown", (event) => {
|
||||
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
|
||||
// Keep this in the bubble phase so editor inputs receive the event before
|
||||
// it is isolated from listeners installed by the inspected page.
|
||||
event.stopImmediatePropagation();
|
||||
if (!submission) return;
|
||||
event.preventDefault();
|
||||
submit.click();
|
||||
submitAnnotation(submission);
|
||||
});
|
||||
|
||||
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
|
||||
|
||||
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
const require = NodeModule.createRequire(import.meta.url);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
|
||||
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
|
||||
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
|
||||
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
|
||||
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
|
||||
|
||||
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
|
||||
|
||||
const DesktopSettingsPatch = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(
|
||||
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
|
||||
),
|
||||
mainWindowBounds: Schema.optionalKey(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
|
||||
assert.deepEqual(
|
||||
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
|
||||
{
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
|
||||
Effect.gen(function* () {
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* writeSettingsPatch({
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "gnome-libsecret",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
|
||||
),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"normalizes unsupported linux password-store values without dropping other settings",
|
||||
() =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const settings = yield* DesktopAppSettings.DesktopAppSettings;
|
||||
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
|
||||
yield* fileSystem.writeFileString(
|
||||
environment.desktopSettingsPath,
|
||||
`{
|
||||
"linuxPasswordStore": "unsupported-store",
|
||||
"serverExposureMode": "network-accessible",
|
||||
"tailscaleServeEnabled": true,
|
||||
"tailscaleServePort": 8443,
|
||||
"updateChannel": "nightly",
|
||||
"updateChannelConfiguredByUser": true
|
||||
}\n`,
|
||||
);
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
wslBackendEnabled: false,
|
||||
wslOnly: false,
|
||||
wslDistro: null,
|
||||
} satisfies DesktopAppSettings.DesktopSettings);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("persists sparse desktop settings documents", () =>
|
||||
withSettings(
|
||||
Effect.gen(function* () {
|
||||
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
|
||||
});
|
||||
|
||||
assert.deepEqual(yield* settings.load, {
|
||||
linuxPasswordStore: "auto",
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
|
||||
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
|
||||
import * as SynchronizedRef from "effect/SynchronizedRef";
|
||||
|
||||
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import {
|
||||
DEFAULT_LINUX_PASSWORD_STORE,
|
||||
normalizeLinuxPasswordStorePreference,
|
||||
type LinuxPasswordStorePreference,
|
||||
} from "../linuxSecretStorage.ts";
|
||||
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
|
||||
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly linuxPasswordStore: LinuxPasswordStorePreference;
|
||||
readonly mainWindowBounds: DesktopWindowBounds | null;
|
||||
readonly mainWindowMaximized: boolean;
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
|
||||
} as const;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
|
||||
mainWindowBounds: null,
|
||||
mainWindowMaximized: false,
|
||||
serverExposureMode: "local-only",
|
||||
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
|
||||
});
|
||||
|
||||
const DesktopSettingsDocument = Schema.Struct({
|
||||
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
|
||||
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
|
||||
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
|
||||
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
|
||||
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
|
||||
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
|
||||
|
||||
return {
|
||||
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
|
||||
mainWindowBounds,
|
||||
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
|
||||
serverExposureMode:
|
||||
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
|
||||
): DesktopSettingsDocument {
|
||||
const document: Mutable<DesktopSettingsDocument> = {};
|
||||
|
||||
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
|
||||
document.linuxPasswordStore = settings.linuxPasswordStore;
|
||||
}
|
||||
if (settings.mainWindowBounds !== null) {
|
||||
document.mainWindowBounds = settings.mainWindowBounds;
|
||||
}
|
||||
|
||||
@@ -13,14 +13,23 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
environmentIdentificationMode: "artwork",
|
||||
favorites: [],
|
||||
fontFamilyCode: "",
|
||||
fontFamilyComposer: "",
|
||||
fontFamilySans: "",
|
||||
fontFamilyTerminal: "",
|
||||
fontSizeCode: 13,
|
||||
fontSizeInterface: 16,
|
||||
fontSizePrompt: 14,
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -30,8 +39,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
legacySidebarEnabled: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
|
||||
}
|
||||
return Effect.succeed(decoded.slice("enc:".length));
|
||||
},
|
||||
selectedStorageBackend: Effect.succeed(Option.none()),
|
||||
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopShellEnvironment.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
|
||||
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -243,6 +244,65 @@ describe("DesktopShellEnvironment", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "wrong-launcher",
|
||||
XDG_SESSION_DESKTOP: "wrong-launcher",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
|
||||
XDG_CURRENT_DESKTOP: "KDE",
|
||||
XDG_SESSION_DESKTOP: "KDE",
|
||||
XDG_SESSION_TYPE: "wayland",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
|
||||
assert.equal(env.XDG_SESSION_TYPE, "wayland");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("overrides stale dbus session addresses from the login shell", () =>
|
||||
Effect.gen(function* () {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
|
||||
};
|
||||
|
||||
yield* runShellEnvironment({
|
||||
env,
|
||||
platform: "linux",
|
||||
handler: () =>
|
||||
envOutput({
|
||||
PATH: "/usr/bin",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
}),
|
||||
});
|
||||
|
||||
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
|
||||
}),
|
||||
);
|
||||
|
||||
it("resolves dbus runtime dir candidates with existence checks", () => {
|
||||
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
|
||||
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
|
||||
uid: 1000,
|
||||
exists: (path) => path === "/run/user/1000/bus",
|
||||
});
|
||||
|
||||
assert.equal(busPath, "unix:path=/run/user/1000/bus");
|
||||
});
|
||||
|
||||
it.effect("logs command failures with safe probe context and the exact cause", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/bash",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as Context from "effect/Context";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -68,12 +69,19 @@ export class DesktopShellEnvironment extends Context.Service<
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"DISPLAY",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const;
|
||||
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
|
||||
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
|
||||
@@ -92,6 +100,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
|
||||
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
|
||||
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
|
||||
|
||||
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
|
||||
|
||||
const linuxRuntimeDirCandidates = (
|
||||
env: NodeJS.ProcessEnv,
|
||||
uid: number | undefined,
|
||||
): ReadonlyArray<string> => {
|
||||
const candidates: string[] = [];
|
||||
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
|
||||
if (Option.isSome(fromEnv)) {
|
||||
candidates.push(normalizeRuntimeDir(fromEnv.value));
|
||||
}
|
||||
if (uid !== undefined) {
|
||||
candidates.push(`/run/user/${uid}`);
|
||||
}
|
||||
return candidates.filter((candidate) => candidate.length > 0);
|
||||
};
|
||||
|
||||
function resolveDefaultLinuxDbusSessionBusPath(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly uid: number | undefined;
|
||||
readonly exists?: (path: string) => boolean;
|
||||
}): string | null {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
|
||||
const busPath = `${runtimeDir}/bus`;
|
||||
if (input.exists === undefined || input.exists(busPath)) {
|
||||
return busPath;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly exists: (path: string) => boolean;
|
||||
readonly uid: number | undefined;
|
||||
}): string | null {
|
||||
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
|
||||
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
|
||||
}
|
||||
|
||||
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
|
||||
const normalized = entry.trim().replace(/^"+|"+$/g, "");
|
||||
return platform === "win32" ? normalized.toLowerCase() : normalized;
|
||||
@@ -356,7 +405,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
|
||||
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
|
||||
function* (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
): Effect.fn.Return<
|
||||
void,
|
||||
never,
|
||||
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
|
||||
> {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const shellEnvironment: EnvironmentPatch = {};
|
||||
|
||||
for (const shell of listLoginShellCandidates(config)) {
|
||||
@@ -383,23 +437,54 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
|
||||
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
const shellPreferredEnvNames = [
|
||||
"DBUS_SESSION_BUS_ADDRESS",
|
||||
"XDG_CURRENT_DESKTOP",
|
||||
"XDG_SESSION_DESKTOP",
|
||||
"XDG_SESSION_TYPE",
|
||||
] as const;
|
||||
for (const name of shellPreferredEnvNames) {
|
||||
if (shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
for (const name of [
|
||||
"DISPLAY",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
"XDG_RUNTIME_DIR",
|
||||
"WAYLAND_DISPLAY",
|
||||
] as const) {
|
||||
if (!config.env[name] && shellEnvironment[name]) {
|
||||
config.env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
config.platform === "linux" &&
|
||||
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
|
||||
) {
|
||||
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
|
||||
const dbusSessionBusPath = `${runtimeDir}/bus`;
|
||||
const busExists = yield* fileSystem
|
||||
.exists(dbusSessionBusPath)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
if (busExists) {
|
||||
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
const installShellEnvironment = (
|
||||
config: ShellEnvironmentConfig,
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
|
||||
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
|
||||
if (config.platform === "win32") {
|
||||
return installWindowsEnvironment(config);
|
||||
}
|
||||
@@ -411,6 +496,7 @@ const installShellEnvironment = (
|
||||
|
||||
export const make = Effect.gen(function* () {
|
||||
const environment = yield* DesktopEnvironment.DesktopEnvironment;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
|
||||
installShellEnvironment({
|
||||
@@ -418,6 +504,7 @@ export const make = Effect.gen(function* () {
|
||||
platform: environment.platform,
|
||||
userShell: Option.none(),
|
||||
}).pipe(
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
|
||||
);
|
||||
|
||||
@@ -43,6 +43,7 @@ function makeElectronAppLayer(
|
||||
setDesktopName: () => Effect.void,
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
@@ -46,11 +46,13 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
|
||||
setDockIcon: () => Effect.void,
|
||||
appendCommandLineSwitch: () => Effect.void,
|
||||
onBeforeQuitForUpdate: () => Effect.void,
|
||||
removeCommandLineSwitch: () => Effect.void,
|
||||
on: () => Effect.void,
|
||||
} satisfies ElectronApp.ElectronApp["Service"]);
|
||||
|
||||
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
|
||||
pickFolder: () => Effect.succeed(Option.none()),
|
||||
pickFiles: () => Effect.succeed([]),
|
||||
confirm: () => Effect.succeed(false),
|
||||
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
|
||||
showErrorBox: () => Effect.void,
|
||||
@@ -79,6 +81,8 @@ 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"]);
|
||||
|
||||
@@ -92,6 +96,30 @@ 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* () {
|
||||
@@ -99,25 +127,7 @@ describe("DesktopApplicationMenu", () => {
|
||||
const applicationMenuTemplate =
|
||||
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
|
||||
|
||||
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({}))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* configureMenu(selectedAction, applicationMenuTemplate);
|
||||
|
||||
const template = yield* Deferred.await(applicationMenuTemplate);
|
||||
const fileMenu = template.find((item) => item.label === "File");
|
||||
@@ -136,4 +146,38 @@ 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,6 +49,13 @@ 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;
|
||||
@@ -127,6 +134,9 @@ 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") {
|
||||
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
|
||||
{ role: "forceReload" },
|
||||
{ role: "toggleDevTools" },
|
||||
{ type: "separator" },
|
||||
{ role: "resetZoom" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
|
||||
{ role: "zoomOut" },
|
||||
/*
|
||||
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") },
|
||||
{ type: "separator" },
|
||||
{ role: "togglefullscreen" },
|
||||
],
|
||||
|
||||
@@ -438,6 +438,51 @@ describe("DesktopWindow", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
const createCount = yield* Ref.make(0);
|
||||
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
|
||||
const layer = makeTestLayer({
|
||||
window: fakeWindow.window,
|
||||
createCount,
|
||||
mainWindow,
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
|
||||
|
||||
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
|
||||
if (!beforeInput) {
|
||||
return yield* Effect.die("before-input-event listener was not registered");
|
||||
}
|
||||
|
||||
let prevented = false;
|
||||
const event = { preventDefault: () => (prevented = true) };
|
||||
const input = {
|
||||
type: "keyDown",
|
||||
isAutoRepeat: true,
|
||||
key: "W",
|
||||
meta: true,
|
||||
control: false,
|
||||
alt: false,
|
||||
shift: false,
|
||||
};
|
||||
beforeInput(event, input);
|
||||
assert.isTrue(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, isAutoRepeat: false });
|
||||
assert.isFalse(prevented);
|
||||
|
||||
prevented = false;
|
||||
beforeInput(event, { ...input, meta: false });
|
||||
assert.isFalse(prevented);
|
||||
}).pipe(Effect.provide(layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the persisted main window bounds when opening the window", () =>
|
||||
Effect.gen(function* () {
|
||||
const fakeWindow = makeFakeBrowserWindow();
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as Clock from "effect/Clock";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -25,6 +26,12 @@ const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
const MAIN_WINDOW_BOUNDS_PERSIST_DEBOUNCE_MS = 500;
|
||||
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
|
||||
// Renderer crash (usually V8 OOM on long sessions) recovery: reload after a
|
||||
// short delay, at most MAX_ATTEMPTS times per rolling WINDOW so a renderer
|
||||
// that dies on boot cannot reload-loop forever.
|
||||
const RENDERER_RECOVERY_RELOAD_DELAY_MS = 500;
|
||||
const RENDERER_RECOVERY_MAX_ATTEMPTS = 3;
|
||||
const RENDERER_RECOVERY_WINDOW_MS = 60_000;
|
||||
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
|
||||
-2, // ERR_FAILED
|
||||
-7, // ERR_TIMED_OUT
|
||||
@@ -54,6 +61,8 @@ export type DesktopWindowError =
|
||||
| ElectronWindow.ElectronWindowCreateError
|
||||
| PreviewManager.PreviewManagerError;
|
||||
|
||||
export type MainWindowZoomDirection = "in" | "out" | "reset";
|
||||
|
||||
export class DesktopWindow extends Context.Service<
|
||||
DesktopWindow,
|
||||
{
|
||||
@@ -80,6 +89,12 @@ 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") {}
|
||||
@@ -514,6 +529,18 @@ export const make = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
// Electron's windowMenu close role owns CmdOrCtrl+W. Holding the
|
||||
// close-terminal shortcut can outlive the terminal that handled its first
|
||||
// press, so reject repeats before they reach the native window accelerator.
|
||||
// Deliberate presses still flow through the renderer or native menu.
|
||||
window.webContents.on("before-input-event", (event, input) => {
|
||||
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
|
||||
const modifier = environment.platform === "darwin" ? input.meta : input.control;
|
||||
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.on("page-title-updated", (event) => {
|
||||
event.preventDefault();
|
||||
window.setTitle(environment.displayName);
|
||||
@@ -537,6 +564,7 @@ export const make = Effect.gen(function* () {
|
||||
|
||||
let developmentLoadRetryIndex = 0;
|
||||
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
|
||||
let rendererRecoveryTimestamps: number[] = [];
|
||||
const clearDevelopmentLoadRetry = () => {
|
||||
if (developmentLoadRetryFiber === undefined) {
|
||||
return;
|
||||
@@ -618,10 +646,39 @@ export const make = Effect.gen(function* () {
|
||||
},
|
||||
);
|
||||
window.webContents.on("render-process-gone", (_event, details) => {
|
||||
void runPromise(
|
||||
logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
const recoverable =
|
||||
details.reason === "crashed" ||
|
||||
details.reason === "oom" ||
|
||||
details.reason === "abnormal-exit";
|
||||
// Long sessions can OOM the renderer (V8 heap exhaustion from
|
||||
// accumulated thread state). Without a reload the user is left staring
|
||||
// at a dead white window while agents keep running invisibly, so
|
||||
// recover by reloading — the renderer rehydrates from the backend,
|
||||
// which is unaffected. Recovery attempts are bounded so a renderer
|
||||
// that dies immediately on boot cannot reload-loop forever.
|
||||
runFork(
|
||||
Effect.gen(function* () {
|
||||
const now = yield* Clock.currentTimeMillis;
|
||||
rendererRecoveryTimestamps = rendererRecoveryTimestamps.filter(
|
||||
(timestamp) => now - timestamp < RENDERER_RECOVERY_WINDOW_MS,
|
||||
);
|
||||
const shouldRecover =
|
||||
recoverable &&
|
||||
!window.isDestroyed() &&
|
||||
rendererRecoveryTimestamps.length < RENDERER_RECOVERY_MAX_ATTEMPTS;
|
||||
yield* logWindowWarning("main window render process gone", {
|
||||
reason: details.reason,
|
||||
exitCode: details.exitCode,
|
||||
recovering: shouldRecover,
|
||||
});
|
||||
if (!shouldRecover) {
|
||||
return;
|
||||
}
|
||||
rendererRecoveryTimestamps.push(now);
|
||||
yield* Effect.sleep(RENDERER_RECOVERY_RELOAD_DELAY_MS);
|
||||
if (!window.isDestroyed()) {
|
||||
loadApplication();
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -787,6 +844,18 @@ 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) =>
|
||||
|
||||
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
Looking for older versions? Check the
|
||||
Looking for older versions? Check the{" "}
|
||||
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.1",
|
||||
version: "1.0.2",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
|
||||
@@ -535,6 +535,12 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.isEmpty {
|
||||
feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
|
||||
lastAppliedBuffer = ""
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.hasPrefix(lastAppliedBuffer) {
|
||||
let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
|
||||
feedData(Data(suffix.utf8))
|
||||
|
||||
@@ -138,5 +138,10 @@
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
},
|
||||
"reanimated": {
|
||||
"staticFeatureFlags": {
|
||||
"DISABLE_COMMIT_PAUSING_MECHANISM": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ import { SettingsClientStorageRouteScreen } from "./features/settings/SettingsCl
|
||||
import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteScreen";
|
||||
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
|
||||
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
|
||||
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
|
||||
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
|
||||
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
|
||||
import {
|
||||
@@ -175,6 +176,13 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Appearance",
|
||||
},
|
||||
}),
|
||||
SettingsProjectGrouping: createNativeStackScreen({
|
||||
screen: SettingsProjectGroupingRouteScreen,
|
||||
linking: "project-grouping",
|
||||
options: {
|
||||
title: "Project Grouping",
|
||||
},
|
||||
}),
|
||||
SettingsClientStorage: createNativeStackScreen({
|
||||
screen: SettingsClientStorageRouteScreen,
|
||||
linking: "client-storage",
|
||||
|
||||
@@ -70,7 +70,7 @@ export function AndroidScreenHeader(props: {
|
||||
accessibilityRole="button"
|
||||
hitSlop={8}
|
||||
onPress={props.onBack}
|
||||
className="size-11 items-center justify-center"
|
||||
className="-mr-2 size-11 items-center justify-center"
|
||||
>
|
||||
<SymbolView
|
||||
name="chevron.left"
|
||||
|
||||
@@ -50,6 +50,8 @@ import {
|
||||
IconMinus,
|
||||
IconNetwork,
|
||||
IconPalette,
|
||||
IconPin,
|
||||
IconPinnedOff,
|
||||
IconPlayerPlay,
|
||||
IconPlayerStopFilled,
|
||||
IconPlus,
|
||||
@@ -121,6 +123,8 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
|
||||
magnifyingglass: IconSearch,
|
||||
paintbrush: IconPalette,
|
||||
"person.crop.circle": IconUserCircle,
|
||||
pin: IconPin,
|
||||
"pin.slash": IconPinnedOff,
|
||||
play: IconPlayerPlay,
|
||||
plus: IconPlus,
|
||||
"qrcode.viewfinder": IconQrcode,
|
||||
|
||||
@@ -16,6 +16,18 @@ 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.
|
||||
*/
|
||||
@@ -28,16 +40,7 @@ export function CompactBrandTitle(
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
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;
|
||||
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
|
||||
|
||||
return (
|
||||
<View
|
||||
|
||||
@@ -9,6 +9,7 @@ type ProviderIconProps = {
|
||||
export function ProviderIcon(props: ProviderIconProps) {
|
||||
const isDarkMode = useColorScheme() === "dark";
|
||||
const size = props.size ?? 16;
|
||||
const mono = isDarkMode ? "#e5e5e5" : "#171717";
|
||||
|
||||
if (props.provider === "claudeAgent") {
|
||||
return (
|
||||
@@ -21,10 +22,47 @@ export function ProviderIcon(props: ProviderIconProps) {
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "grok") {
|
||||
const fill = isDarkMode ? "#F5F5F5" : "#0F0F0F";
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 24 24" fill="none">
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861"
|
||||
/>
|
||||
<Path
|
||||
fill={fill}
|
||||
d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "cursor") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 466.73 532.09" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#EDECEC" : "#26251E"}
|
||||
d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"
|
||||
/>
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
if (props.provider === "opencode") {
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 32 40" fill="none">
|
||||
<Path d="M24 32H8V16H24V32Z" fill={isDarkMode ? "#4B4646" : "#CFCECD"} />
|
||||
<Path d="M24 8H8V32H24V8ZM32 40H0V0H32V40Z" fill={isDarkMode ? "#F1ECEC" : "#211E1E"} />
|
||||
</Svg>
|
||||
);
|
||||
}
|
||||
|
||||
// codex (and unknown drivers)
|
||||
return (
|
||||
<Svg width={size} height={size} viewBox="0 0 256 260" fill="none">
|
||||
<Path
|
||||
fill={isDarkMode ? "#e5e5e5" : "#171717"}
|
||||
fill={mono}
|
||||
d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"
|
||||
/>
|
||||
</Svg>
|
||||
|
||||
@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ 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";
|
||||
|
||||
@@ -42,6 +43,11 @@ 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`
|
||||
@@ -50,20 +56,33 @@ 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 null;
|
||||
if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
|
||||
return <CloudEnvironmentRowsContent {...props} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
if (props.connectedCloudEnvironments.length === 0) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(
|
||||
props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
|
||||
) {
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const discoveryAvailable = props.discoveryAvailable ?? true;
|
||||
const availableCloudEnvironments = discoveryAvailable
|
||||
? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
|
||||
: [];
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -89,25 +108,27 @@ function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
{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>
|
||||
<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>
|
||||
{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}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -152,7 +173,9 @@ function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
|
||||
{/* Rendered alongside any connected rows — a failed discovery must not
|
||||
hide behind an otherwise-healthy list. */}
|
||||
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
|
||||
{discoveryAvailable &&
|
||||
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,
|
||||
}}
|
||||
|
||||
@@ -21,6 +21,7 @@ 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,
|
||||
@@ -47,6 +48,7 @@ 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;
|
||||
}) {
|
||||
@@ -207,18 +209,27 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
>
|
||||
<View className="w-full max-w-[720px] self-center gap-3">
|
||||
<View className="flex-row items-center gap-2.5">
|
||||
<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>
|
||||
{/* 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>
|
||||
}
|
||||
/>
|
||||
|
||||
<ControlPillMenu
|
||||
actions={menuActions}
|
||||
|
||||
@@ -3,7 +3,6 @@ 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";
|
||||
@@ -20,6 +19,7 @@ import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -42,6 +42,9 @@ export function HomeRouteScreen() {
|
||||
settleThread,
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -124,8 +127,16 @@ export function HomeRouteScreen() {
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title after the split branch blanks the detail header. */}
|
||||
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
|
||||
{/* Restore the compact title after the split branch blanks the detail
|
||||
header. The brand slot doubles as the connection status surface:
|
||||
while an environment reconnects, the lockup fades to a status label
|
||||
in place (no layout shift in the list below). */}
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
@@ -136,6 +147,9 @@ export function HomeRouteScreen() {
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
@@ -155,11 +169,11 @@ export function HomeRouteScreen() {
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
threadSearchMatchKey,
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
@@ -71,8 +72,6 @@ import {
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -97,7 +96,6 @@ 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,6 +109,12 @@ interface HomeScreenProps {
|
||||
) => Promise<boolean>;
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onMovePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -516,6 +520,24 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onUnsnoozeThread],
|
||||
);
|
||||
const handlePinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onPinThread(thread);
|
||||
},
|
||||
[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 handleDeleteThread = props.onDeleteThread;
|
||||
const handleUnsettleThread = props.onUnsettleThread;
|
||||
// The settled tail renders in pages; expansion resets when the filter
|
||||
@@ -575,6 +597,38 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order (reorder-capable threads only) for the
|
||||
// Move up/down position flags. Computed from all shells, not the rendered
|
||||
// list, so search/scope filtering never disables or misdirects a move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
props.threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, props.threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -671,7 +725,11 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
);
|
||||
|
||||
const renderV2Item = useCallback(
|
||||
({ item }: { readonly item: ThreadListV2ListItem }) => {
|
||||
({ 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);
|
||||
if (item.type === "v2-pending") {
|
||||
const pendingScopeKey = scopedProjectKey(
|
||||
item.pendingTask.message.environmentId,
|
||||
@@ -689,6 +747,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
: null
|
||||
}
|
||||
showPendingDivider={item.showPendingDivider}
|
||||
showTrailingDivider={showTrailingDivider}
|
||||
onSelectPendingTask={props.onSelectPendingTask}
|
||||
onDeletePendingTask={props.onDeletePendingTask}
|
||||
/>
|
||||
@@ -718,8 +777,10 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
showTrailingDivider={showTrailingDivider}
|
||||
project={
|
||||
projectByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
}
|
||||
@@ -753,9 +814,19 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
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
|
||||
@@ -768,12 +839,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
handleUnpinThread,
|
||||
handleUnsnoozeThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
pinReorderEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
@@ -784,6 +861,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
serverConfigs,
|
||||
settlementEnvironmentIds,
|
||||
snoozeEnvironmentIds,
|
||||
threadListV2Items,
|
||||
threadSearchMatchByKey,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
@@ -939,20 +1017,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
? null
|
||||
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
|
||||
"this environment");
|
||||
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
|
||||
// Connection state surfaces in the header title slot
|
||||
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
|
||||
// reconnects never shift the rows.
|
||||
const emptyState = deriveEmptyState({
|
||||
catalogState: props.catalogState,
|
||||
projectCount: props.projects.length,
|
||||
});
|
||||
const 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 (
|
||||
@@ -971,41 +1042,17 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||
{emptyState.loading ? (
|
||||
<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 />}
|
||||
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View className="pb-4">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
|
||||
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
// mobile — the menu is the one filter surface).
|
||||
@@ -1086,7 +1133,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1141,7 +1187,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
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,12 +31,6 @@ 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;
|
||||
@@ -76,7 +70,9 @@ 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 repository label for a singleton repository scope", () => {
|
||||
it("uses the physical project title for a singleton 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("codething-mvp");
|
||||
expect(groups[0]?.title).toBe("codething-mvp");
|
||||
expect(scopes[0]?.title).toBe("local-worktree-name");
|
||||
expect(groups[0]?.title).toBe("local-worktree-name");
|
||||
});
|
||||
|
||||
it("sorts the newest thread first regardless of snapshot order", () => {
|
||||
@@ -565,10 +565,16 @@ describe("buildHomeThreadGroups", () => {
|
||||
);
|
||||
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository" })).toHaveLength(1);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "repository_path" })).toHaveLength(
|
||||
2,
|
||||
);
|
||||
expect(buildGroups(projects, threads, { projectGroupingMode: "separate" })).toHaveLength(2);
|
||||
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"]);
|
||||
});
|
||||
|
||||
it("default view shows only threads from the last 5 days", () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import {
|
||||
deriveLogicalProjectKey,
|
||||
buildProjectGroups,
|
||||
derivePhysicalProjectKey,
|
||||
deriveProjectGroupLabel,
|
||||
} from "@t3tools/client-runtime/state/project-grouping";
|
||||
@@ -37,10 +37,6 @@ 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,
|
||||
@@ -60,64 +56,19 @@ export function buildHomeProjectScopes(input: {
|
||||
const projects = input.projects.filter(
|
||||
(project) => input.environmentId === null || project.environmentId === input.environmentId,
|
||||
);
|
||||
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 buildProjectGroups({
|
||||
projects,
|
||||
settings: {
|
||||
sidebarProjectGroupingMode: input.projectGroupingMode,
|
||||
sidebarProjectGroupingOverrides: {},
|
||||
},
|
||||
}).map((group) => {
|
||||
return {
|
||||
key,
|
||||
title: deriveProjectGroupLabel({ representative, members: projects }),
|
||||
representative,
|
||||
projects,
|
||||
projectRefs: projectRefsByGroup.get(key) ?? [],
|
||||
key: group.key,
|
||||
title: group.label,
|
||||
representative: group.representative,
|
||||
projects: group.members.map((member) => member.project),
|
||||
projectRefs: group.memberProjectRefs,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -264,9 +215,11 @@ 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],
|
||||
@@ -345,7 +298,9 @@ export function buildHomeThreadGroups(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const title = deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const title =
|
||||
groupTitleByKey.get(group.key) ??
|
||||
deriveProjectGroupLabel({ representative, members: group.projects });
|
||||
const groupMatches =
|
||||
query.length === 0 ||
|
||||
title.toLocaleLowerCase().includes(query) ||
|
||||
|
||||
@@ -8,9 +8,14 @@ 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 { threadEnvironment } from "../../state/threads";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
@@ -29,6 +34,20 @@ function environmentSupportsSnooze(environmentId: EnvironmentThreadShell["enviro
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinning(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinning === true
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinReorder === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -202,10 +221,18 @@ export function useThreadListActions(): {
|
||||
readonly snoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => Promise<boolean>;
|
||||
readonly unsnoozeThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly movePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
|
||||
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
|
||||
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
|
||||
const snoozeInFlightThreadKeys = useRef(new Set<string>());
|
||||
|
||||
const archiveThread = useCallback(
|
||||
@@ -310,6 +337,153 @@ export function useThreadListActions(): {
|
||||
async (thread: EnvironmentThreadShell) => (await executeAction("unsettle", thread)) === true,
|
||||
[executeAction],
|
||||
);
|
||||
const pinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
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 } : {}) },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not pin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be pinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[pinMutation],
|
||||
);
|
||||
const unpinThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell) => {
|
||||
if (!environmentSupportsPinning(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
"This environment's server does not support pinning yet. Update the server to use Pin.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
const result = await unpinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not unpin thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The thread could not be unpinned.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
[unpinMutation],
|
||||
);
|
||||
|
||||
// Move up / Move down for the pinned block. Computed against the CANONICAL
|
||||
// keyed pinned order (not the rendered list), so the move is valid even
|
||||
// while search or a project scope filters rows: the same fractional-key
|
||||
// scheme web dragging uses, one write to one thread per move (plus a
|
||||
// one-time section materialization when legacy keyless pins are involved).
|
||||
const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// One move at a time: a second tap before the first write's event lands
|
||||
// would plan from the same stale snapshot and silently collapse two moves
|
||||
// into one — same double-dispatch guard as snoozeThread.
|
||||
const movePinnedInFlightRef = useRef(false);
|
||||
const movePinnedThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
if (movePinnedInFlightRef.current) return false;
|
||||
if (!environmentSupportsPinReorder(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
"This environment's server does not support pinned reordering yet. Update the server to reorder pins.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
shells.filter(
|
||||
(shell) =>
|
||||
shell.pinnedAt != null &&
|
||||
shell.archivedAt === null &&
|
||||
environmentSupportsPinReorder(shell.environmentId),
|
||||
),
|
||||
);
|
||||
const orderedIds = pinned.map((shell) => scopedThreadKey(shell.environmentId, shell.id));
|
||||
const assignments = planPinnedMove({
|
||||
orderedIds,
|
||||
keysById: new Map(
|
||||
pinned.map((shell) => [
|
||||
scopedThreadKey(shell.environmentId, shell.id),
|
||||
shell.pinOrderKey ?? null,
|
||||
]),
|
||||
),
|
||||
movedId: scopedThreadKey(thread.environmentId, thread.id),
|
||||
direction,
|
||||
});
|
||||
if (assignments === null || assignments.length === 0) return false;
|
||||
const shellByKey = new Map(
|
||||
pinned.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
|
||||
);
|
||||
selectionHaptic();
|
||||
movePinnedInFlightRef.current = true;
|
||||
try {
|
||||
for (const assignment of assignments) {
|
||||
const target = shellByKey.get(assignment.id);
|
||||
if (target === undefined) continue;
|
||||
const result = await reorderPinnedMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.id, orderKey: assignment.orderKey },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The pinned thread could not be moved.",
|
||||
);
|
||||
// No rollback: keys already written are valid orderings on their
|
||||
// own (each write is a complete, consistent placement), so a
|
||||
// partial materialization leaves the list sensible, not corrupt.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
movePinnedInFlightRef.current = false;
|
||||
}
|
||||
},
|
||||
[reorderPinnedMutation],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
@@ -320,6 +494,9 @@ export function useThreadListActions(): {
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+33
@@ -4,6 +4,7 @@ import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import {
|
||||
shouldShowWorkspaceConnectionStatus,
|
||||
workspaceConnectionStatusLabel,
|
||||
workspaceConnectionStatusPresentation,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
|
||||
@@ -84,4 +85,36 @@ 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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,11 @@
|
||||
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" ||
|
||||
@@ -24,3 +30,17 @@ 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,11 +37,15 @@ 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, resolveProjectGroupingMode } from "../home/home-list-options";
|
||||
import { HomeListOptionsProvider } from "../home/home-list-options";
|
||||
import { ThreadNavigationSidebar } from "../threads/ThreadNavigationSidebar";
|
||||
import { WORKSPACE_PANE_TIMING } from "./workspace-pane-animation";
|
||||
import { WorkspaceInspectorPane } from "./workspace-inspector-pane";
|
||||
@@ -190,15 +194,17 @@ export function AdaptiveWorkspaceLayout(props: {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
if (!AsyncResult.isSuccess(preferencesResult)) {
|
||||
return AsyncResult.isFailure(preferencesResult) ? (
|
||||
<AdaptiveWorkspaceLayoutContent {...props} projectGroupingMode="repository" />
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={DEFAULT_MOBILE_PROJECT_GROUPING_SETTINGS.sidebarProjectGroupingMode}
|
||||
/>
|
||||
) : null;
|
||||
}
|
||||
const groupingSettings = resolveMobileProjectGroupingSettings(preferencesResult.value);
|
||||
return (
|
||||
<AdaptiveWorkspaceLayoutContent
|
||||
{...props}
|
||||
projectGroupingMode={resolveProjectGroupingMode(
|
||||
preferencesResult.value.projectGroupingEnabled,
|
||||
)}
|
||||
projectGroupingMode={groupingSettings.sidebarProjectGroupingMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
import { ScrollView, View } from "react-native";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { CodeAppearanceSection } from "./appearance/sections/CodeAppearanceSection";
|
||||
import { TerminalAppearanceSection } from "./appearance/sections/TerminalAppearanceSection";
|
||||
import { TextAppearanceSection } from "./appearance/sections/TextAppearanceSection";
|
||||
|
||||
export function SettingsAppearanceRouteScreen() {
|
||||
const navigation = useNavigation();
|
||||
const insets = useSafeAreaInsets();
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
{Platform.OS === "android" ? (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<AndroidScreenHeader title="Appearance" onBack={() => navigation.goBack()} />
|
||||
</>
|
||||
) : null}
|
||||
<ScrollView
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useAuth } from "@clerk/expo";
|
||||
import { AuthView, UserProfileView } from "@clerk/expo/native";
|
||||
import { StackActions, useNavigation } from "@react-navigation/native";
|
||||
import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useEffect } from "react";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -21,16 +21,18 @@ export function SettingsAuthRouteScreen() {
|
||||
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ title: isSignedIn ? "Account" : "Sign in" }} />
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} />
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} />
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -8,7 +8,6 @@ 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";
|
||||
@@ -161,18 +160,19 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
{/* 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,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -131,7 +131,7 @@ function LocalSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
<LegacySettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
@@ -519,7 +519,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
<LegacySettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
@@ -530,45 +530,35 @@ 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">
|
||||
<SettingsSwitchRow
|
||||
icon="folder"
|
||||
label="Project Grouping"
|
||||
value={projectGroupingEnabled}
|
||||
onValueChange={(value) => savePreferences({ projectGroupingEnabled: value })}
|
||||
/>
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Device-local beta toggles. Mobile has no client-settings sync, so this is
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
* 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.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
function LegacySettingsSection() {
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
<SettingsSection title="Beta">
|
||||
<SettingsSection title="Legacy">
|
||||
<SettingsSwitchRow
|
||||
icon="sidebar.left"
|
||||
label="Thread List v2"
|
||||
value={threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
|
||||
label="Legacy Thread List"
|
||||
value={!threadListV2Enabled}
|
||||
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
|
||||
/>
|
||||
</SettingsSection>
|
||||
<Text className="px-2 text-sm text-foreground-muted">
|
||||
One flat thread list in creation order. Active work renders as cards; settled threads
|
||||
collapse to compact rows. Switch back any time.
|
||||
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.
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { Platform, ScrollView, View, useColorScheme } from "react-native";
|
||||
import {
|
||||
Platform,
|
||||
ScrollView,
|
||||
type StyleProp,
|
||||
type TextStyle,
|
||||
View,
|
||||
useColorScheme,
|
||||
} from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../../../components/AppText";
|
||||
import {
|
||||
@@ -54,14 +61,48 @@ 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={[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 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>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@ export type SettingsSheetTarget =
|
||||
| "SettingsEnvironments"
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -25,15 +25,12 @@ 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 {
|
||||
applyProviderOptionMenuEvent,
|
||||
buildProviderOptionMenuActions,
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
|
||||
import {
|
||||
clearComposerDraftContent,
|
||||
@@ -50,6 +47,7 @@ import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../sta
|
||||
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: {
|
||||
@@ -89,7 +87,7 @@ export function NewTaskDraftScreen(props: {
|
||||
const colorScheme = useColorScheme();
|
||||
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
|
||||
const controlsBottomPadding = isKeyboardVisible ? 8 : Math.max(insets.bottom, 10);
|
||||
const { logicalProjects, selectedProject, setProject } = flow;
|
||||
const { projectScopes, selectedProject, selectedProjectKey, setProject } = flow;
|
||||
const { connectedEnvironments } = useRemoteConnectionStatus();
|
||||
const selectedEnvironmentServerConfig = useEnvironmentServerConfig(
|
||||
selectedProject?.environmentId ?? null,
|
||||
@@ -102,6 +100,10 @@ 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);
|
||||
@@ -277,24 +279,25 @@ export function NewTaskDraftScreen(props: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (selectedProject) {
|
||||
const selection = resolveDraftProjectSelection(selectedProjectKey, projects, projectScopes);
|
||||
if (selection.kind === "preserve") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (logicalProjects.length === 1) {
|
||||
setProject(logicalProjects[0]!.project);
|
||||
if (selection.kind === "select") {
|
||||
setProject(selection.project);
|
||||
return;
|
||||
}
|
||||
|
||||
navigation.dispatch(StackActions.replace("NewTask"));
|
||||
}, [
|
||||
logicalProjects,
|
||||
projectScopes,
|
||||
projects,
|
||||
props.initialProjectRef,
|
||||
props.incomingShareId,
|
||||
props.pendingTaskId,
|
||||
navigation,
|
||||
selectedProject,
|
||||
selectedProjectKey,
|
||||
setProject,
|
||||
]);
|
||||
|
||||
@@ -519,7 +522,15 @@ export function NewTaskDraftScreen(props: {
|
||||
|
||||
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
|
||||
const interaction = InteractionManager.runAfterInteractions(() => {
|
||||
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
@@ -528,7 +539,11 @@ export function NewTaskDraftScreen(props: {
|
||||
cancelAnimationFrame(focusFrame);
|
||||
}
|
||||
};
|
||||
}, [selectedProject]);
|
||||
}, [
|
||||
selectedProject,
|
||||
settingsSheetPresentation.isActiveRef,
|
||||
settingsSheetPresentation.restoreFocusAfterSave,
|
||||
]);
|
||||
|
||||
const environmentMenuActions = useMemo(
|
||||
() =>
|
||||
@@ -542,30 +557,6 @@ export function NewTaskDraftScreen(props: {
|
||||
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
|
||||
);
|
||||
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
flow.providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
flow.selectedModel &&
|
||||
model.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
model.selection.model === flow.selectedModel.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
flow.selectedModel &&
|
||||
option.selection.instanceId === flow.selectedModel.instanceId &&
|
||||
option.selection.model === flow.selectedModel.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
[flow.providerGroups, flow.selectedModel],
|
||||
);
|
||||
const providerOptionDescriptors = useMemo(
|
||||
() =>
|
||||
resolveProviderOptionDescriptors({
|
||||
@@ -575,54 +566,6 @@ 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
|
||||
@@ -693,10 +636,12 @@ export function NewTaskDraftScreen(props: {
|
||||
flow.availableBranches.find((branch) => branch.current)?.name ??
|
||||
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
|
||||
null;
|
||||
const configurationLabel = useMemo(
|
||||
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
|
||||
[providerOptionDescriptors],
|
||||
);
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: flow.selectedModelOption?.label ?? "Model",
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: flow.runtimeMode,
|
||||
interactionMode: flow.interactionMode,
|
||||
});
|
||||
const workspaceLabel = useMemo(
|
||||
() =>
|
||||
formatWorkspaceLabel({
|
||||
@@ -706,13 +651,6 @@ 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;
|
||||
@@ -720,28 +658,6 @@ 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;
|
||||
@@ -948,7 +864,9 @@ 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.
|
||||
const isExpanded = !isAndroid || isComposerFocused;
|
||||
// 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 canStart =
|
||||
Boolean(flow.selectedProject) &&
|
||||
Boolean(flow.selectedModel) &&
|
||||
@@ -1002,28 +920,14 @@ export function NewTaskDraftScreen(props: {
|
||||
showChevron={false}
|
||||
disabled={isIncomingShareTransferPending}
|
||||
/>
|
||||
<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>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
disabled={isIncomingShareTransferPending}
|
||||
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={environmentMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
|
||||
@@ -1049,6 +953,21 @@ 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={
|
||||
@@ -1138,6 +1057,7 @@ export function NewTaskDraftScreen(props: {
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1171,6 +1091,7 @@ 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 { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
|
||||
import { useEffect, useRef, useState } 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,12 +11,13 @@ import { cn } from "../../lib/cn";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProjectFavicon } from "../../components/ProjectFavicon";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { useProjects } from "../../state/entities";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import { groupProjectsByRepository } from "../../lib/repositoryGroups";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
|
||||
import { useIncomingShare } from "../sharing/IncomingShareProvider";
|
||||
import { useNewTaskFlow } from "./new-task-flow-provider";
|
||||
|
||||
type NewTaskRouteParams = {
|
||||
readonly incomingShareId?: string | string[];
|
||||
@@ -79,7 +80,7 @@ function deriveProjectEmptyState(catalogState: WorkspaceState): {
|
||||
|
||||
export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRouteParams | undefined>) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { projectScopes } = useNewTaskFlow();
|
||||
const { state: catalogState } = useWorkspaceState();
|
||||
const navigation = useNavigation();
|
||||
const isFocused = useIsFocused();
|
||||
@@ -87,6 +88,7 @@ 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]
|
||||
@@ -100,33 +102,6 @@ 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
|
||||
@@ -137,7 +112,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
) ?? null)
|
||||
: null;
|
||||
|
||||
async function selectProject(item: (typeof items)[number]): Promise<void> {
|
||||
async function selectProject(project: EnvironmentProject): Promise<void> {
|
||||
if (incomingShare?.destination && !reservedDestinationProject) {
|
||||
try {
|
||||
await releaseShareReservation(incomingShare.id, incomingShare.destination);
|
||||
@@ -154,14 +129,26 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
navigation.navigate("NewTaskSheet", {
|
||||
screen: "NewTaskDraft",
|
||||
params: {
|
||||
environmentId: item.environmentId,
|
||||
projectId: item.id,
|
||||
title: item.title,
|
||||
environmentId: project.environmentId,
|
||||
projectId: project.id,
|
||||
title: project.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) {
|
||||
@@ -248,14 +235,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,
|
||||
}}
|
||||
>
|
||||
{items.length === 0 ? (
|
||||
{projectScopes.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">
|
||||
@@ -286,42 +273,89 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
</View>
|
||||
) : (
|
||||
<View collapsable={false} className="overflow-hidden rounded-[24px] bg-card">
|
||||
{items.map((item, index) => {
|
||||
const isFirst = index === 0;
|
||||
const isLast = index === items.length - 1;
|
||||
|
||||
{projectScopes.map((scope, scopeIndex) => {
|
||||
const hasMultipleProjects = scope.projects.length > 1;
|
||||
const expanded = expandedGroupKeys.has(scope.key);
|
||||
const singleProject = hasMultipleProjects ? null : scope.projects[0];
|
||||
return (
|
||||
<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]",
|
||||
)}
|
||||
<View
|
||||
key={scope.key}
|
||||
className={cn(scopeIndex > 0 && "border-t border-border-subtle")}
|
||||
>
|
||||
<View className="flex-row items-center justify-between gap-3">
|
||||
<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="h-7 w-7 items-center justify-center">
|
||||
<ProjectFavicon
|
||||
environmentId={item.environmentId}
|
||||
environmentId={scope.representative.environmentId}
|
||||
size={20}
|
||||
projectTitle={item.title}
|
||||
workspaceRoot={item.workspaceRoot}
|
||||
projectTitle={scope.title}
|
||||
workspaceRoot={scope.representative.workspaceRoot}
|
||||
/>
|
||||
</View>
|
||||
<View className="flex-1">
|
||||
<Text className="text-base leading-snug font-t3-bold">{item.title}</Text>
|
||||
<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>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
name={hasMultipleProjects && expanded ? "chevron.down" : "chevron.right"}
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</View>
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
{hasMultipleProjects && expanded
|
||||
? scope.projects.map((project) => (
|
||||
<Pressable
|
||||
key={scopedProjectKey(project.environmentId, project.id)}
|
||||
disabled={reservedDestinationProject !== null}
|
||||
onPress={() => void selectProject(project)}
|
||||
className="flex-row items-center gap-3 border-t border-border-subtle bg-card py-3 pr-4 pl-10"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
/>
|
||||
<View className="min-w-0 flex-1">
|
||||
<Text className="text-sm font-t3-bold text-foreground">
|
||||
{project.title}
|
||||
</Text>
|
||||
<Text
|
||||
className="text-xs text-foreground-muted"
|
||||
ellipsizeMode="middle"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{project.workspaceRoot}
|
||||
</Text>
|
||||
</View>
|
||||
<SymbolView
|
||||
name="chevron.right"
|
||||
size={14}
|
||||
tintColor={chevronColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
</Pressable>
|
||||
))
|
||||
: null}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</View>
|
||||
|
||||
@@ -14,8 +14,10 @@ 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/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
Approval needed
|
||||
</Text>
|
||||
|
||||
@@ -24,8 +24,11 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
export function PendingUserInputCard(props: PendingUserInputCardProps) {
|
||||
// The surface is opaque on purpose: the card floats over the thread feed
|
||||
// with no blur behind it, so a translucent background renders the questions
|
||||
// on top of whatever message happens to sit underneath.
|
||||
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">
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
|
||||
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
|
||||
User input needed
|
||||
</Text>
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
Image,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
useColorScheme,
|
||||
View,
|
||||
type ViewStyle,
|
||||
@@ -50,7 +51,7 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } from "../../components/ControlPill";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
|
||||
@@ -61,14 +62,11 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import {
|
||||
applyProviderOptionMenuEvent,
|
||||
buildProviderOptionMenuActions,
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
|
||||
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
/**
|
||||
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
|
||||
@@ -272,15 +270,28 @@ 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;
|
||||
const isExpanded = isFocused;
|
||||
// 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 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;
|
||||
@@ -298,13 +309,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
onExpandedChange?.(true);
|
||||
}, [onExpandedChange]);
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
}, []);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
@@ -587,6 +596,12 @@ 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) =>
|
||||
@@ -601,113 +616,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
}),
|
||||
[currentModelOption?.capabilities, currentModelSelection.options],
|
||||
);
|
||||
const configurationLabel = useMemo(
|
||||
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
|
||||
[providerOptionDescriptors],
|
||||
);
|
||||
const modelMenuActions = useMemo(
|
||||
() =>
|
||||
providerGroups.map((group) => ({
|
||||
id: `provider:${group.providerKey}`,
|
||||
title: group.providerLabel,
|
||||
subtitle: group.models.find(
|
||||
(model) =>
|
||||
model.selection.instanceId === currentModelSelection.instanceId &&
|
||||
model.selection.model === currentModelSelection.model,
|
||||
)?.label,
|
||||
subactions: group.models.map((option) => ({
|
||||
id: `model:${option.key}`,
|
||||
title: option.label,
|
||||
state:
|
||||
option.selection.instanceId === currentModelSelection.instanceId &&
|
||||
option.selection.model === currentModelSelection.model
|
||||
? ("on" as const)
|
||||
: undefined,
|
||||
})),
|
||||
})),
|
||||
[providerGroups, currentModelSelection],
|
||||
);
|
||||
|
||||
// ── Options menu ─────────────────────────────────────────
|
||||
const optionsMenuActions = useMemo(
|
||||
() => [
|
||||
...buildProviderOptionMenuActions(providerOptionDescriptors),
|
||||
{
|
||||
id: "options-runtime",
|
||||
title: "Runtime",
|
||||
subtitle:
|
||||
currentRuntimeMode === "approval-required"
|
||||
? "Approve actions"
|
||||
: currentRuntimeMode === "auto-accept-edits"
|
||||
? "Auto-accept edits"
|
||||
: currentRuntimeMode === "auto"
|
||||
? "Auto"
|
||||
: "Full access",
|
||||
subactions: [
|
||||
{ id: "options:runtime:approval-required", title: "Approve actions" },
|
||||
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
|
||||
{ id: "options:runtime:auto", title: "Auto" },
|
||||
{ id: "options:runtime:full-access", title: "Full access" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:runtime:", "");
|
||||
return {
|
||||
id: option.id,
|
||||
title: option.title,
|
||||
state: currentRuntimeMode === value ? ("on" as const) : undefined,
|
||||
};
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: "options-interaction",
|
||||
title: "Interaction",
|
||||
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
|
||||
subactions: [
|
||||
{ id: "options:interaction:default", title: "Default" },
|
||||
{ id: "options:interaction:plan", title: "Plan" },
|
||||
].map((option) => {
|
||||
const value = option.id.replace("options:interaction:", "");
|
||||
return {
|
||||
id: option.id,
|
||||
title: option.title,
|
||||
state: currentInteractionMode === value ? ("on" as const) : undefined,
|
||||
};
|
||||
}),
|
||||
},
|
||||
],
|
||||
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
|
||||
);
|
||||
|
||||
// ── Menu handlers ────────────────────────────────────────
|
||||
function handleModelMenuAction(event: string) {
|
||||
if (!event.startsWith("model:")) {
|
||||
return;
|
||||
}
|
||||
const modelKey = event.slice("model:".length);
|
||||
const option = modelOptions.find((o) => o.key === modelKey);
|
||||
if (option) {
|
||||
props.onUpdateModelSelection(option.selection);
|
||||
}
|
||||
}
|
||||
|
||||
function handleOptionsMenuAction(event: string) {
|
||||
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
|
||||
if (providerOptions) {
|
||||
props.onUpdateModelSelection({
|
||||
...currentModelSelection,
|
||||
options: providerOptions,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("options:runtime:")) {
|
||||
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
|
||||
props.onUpdateRuntimeMode(runtimeMode);
|
||||
return;
|
||||
}
|
||||
if (event.startsWith("options:interaction:")) {
|
||||
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
|
||||
props.onUpdateInteractionMode(interactionMode);
|
||||
}
|
||||
}
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -716,11 +630,22 @@ 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}
|
||||
@@ -867,28 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
@@ -922,6 +834,21 @@ 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}
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface ThreadDetailScreenProps {
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
@@ -371,6 +373,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
|
||||
@@ -45,14 +45,7 @@ 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,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type LayoutAnimationsValues,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
@@ -117,14 +110,6 @@ 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),
|
||||
@@ -164,6 +149,11 @@ export interface ThreadFeedProps {
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
readonly loading: boolean;
|
||||
readonly onLoadEarlier: () => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -1330,6 +1320,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const [viewportHeight, setViewportHeight] = useState(0);
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
|
||||
// whenever the viewport drifts back inside its geometric threshold, which
|
||||
// yanked users off history they were reading every time a stream chunk grew
|
||||
// a row. Follow breaks when the user scrolls up and away, and re-arms only
|
||||
// when the list actually returns to the end (or on send / thread switch).
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
// A "user scroll session" spans from drag start through the end of its
|
||||
// momentum; only motion inside a session can break follow, so MVCP
|
||||
// compensations and programmatic scrolls never strand a follower.
|
||||
const userScrollSessionRef = useRef(false);
|
||||
const setEndFollow = useCallback((enabled: boolean) => {
|
||||
if (endFollowEnabledRef.current === enabled) {
|
||||
return;
|
||||
}
|
||||
endFollowEnabledRef.current = enabled;
|
||||
setEndFollowEnabled(enabled);
|
||||
}, []);
|
||||
const [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1434,11 +1442,6 @@ 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
|
||||
@@ -1446,40 +1449,41 @@ 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);
|
||||
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
|
||||
nearListEnd.value =
|
||||
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
|
||||
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
|
||||
// before invoking this handler, so getState() is current. Returning to
|
||||
// the end re-arms follow no matter who scrolled (the user, or our own
|
||||
// scroll-to-end); moving away breaks it only during a user-initiated
|
||||
// scroll session, so MVCP compensations and programmatic repositioning
|
||||
// can never strand a follower.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
);
|
||||
const handleScrollBeginDrag = useCallback(() => {
|
||||
userScrollSessionRef.current = true;
|
||||
}, []);
|
||||
// The session must survive past finger-lift so momentum that carries the
|
||||
// user away from the end still breaks follow; a drag released with no
|
||||
// momentum ends its session at the release itself, otherwise at momentum
|
||||
// end. Leaving a session open would let a later animated maintain-scroll
|
||||
// read as user motion and break follow spuriously.
|
||||
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const velocity = event.nativeEvent.velocity?.y ?? 0;
|
||||
if (Math.abs(velocity) < 0.05) {
|
||||
userScrollSessionRef.current = false;
|
||||
}
|
||||
}, []);
|
||||
const handleMomentumScrollEnd = useCallback(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
// Gated variant of the 180ms feed layout slide. Instant while browsing
|
||||
// history: maintainVisibleContentPosition compensates the scroll offset in
|
||||
// the same frame a row's measured size lands, so an instant reposition is
|
||||
// invisible — animating it is exactly what made cold upward scrolls slide
|
||||
// and jump. Near the end the slide stays on: streaming growth and sends
|
||||
// shift rows at rest, where the animation is the thing preventing a hard
|
||||
// visual snap.
|
||||
const feedItemLayoutTransition = useMemo(() => {
|
||||
return (values: LayoutAnimationsValues) => {
|
||||
"worklet";
|
||||
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
|
||||
return {
|
||||
initialValues: {
|
||||
originX: values.currentOriginX,
|
||||
originY: values.currentOriginY,
|
||||
width: values.currentWidth,
|
||||
height: values.currentHeight,
|
||||
},
|
||||
animations: {
|
||||
originX: withTiming(values.targetOriginX, { duration }),
|
||||
originY: withTiming(values.targetOriginY, { duration }),
|
||||
width: withTiming(values.targetWidth, { duration }),
|
||||
height: withTiming(values.targetHeight, { duration }),
|
||||
},
|
||||
};
|
||||
};
|
||||
}, [nearListEnd]);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
@@ -1491,6 +1495,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, reportHeaderMaterialVisibility]);
|
||||
|
||||
// A thread switch opens pinned to the end; a send explicitly returns to the
|
||||
// live edge (ThreadDetailScreen scrolls the new message into place). Both
|
||||
// re-arm follow regardless of where the user had scrolled before.
|
||||
useEffect(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
@@ -1817,7 +1835,6 @@ 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
|
||||
@@ -1842,7 +1859,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
|
||||
disclosureToggleSettling || !endFollowEnabled
|
||||
? false
|
||||
: {
|
||||
animated: true,
|
||||
@@ -1891,9 +1908,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
<>
|
||||
{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}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -11,6 +11,7 @@ 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";
|
||||
@@ -55,8 +56,10 @@ 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 { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
|
||||
import {
|
||||
getConnectionAwareBrandHeaderOptions,
|
||||
WorkspaceConnectionTitle,
|
||||
} from "../home/WorkspaceConnectionTitle";
|
||||
import { SidebarHeaderActions } from "./sidebar-header-actions";
|
||||
import { SidebarFilterButton } from "./sidebar-filter-button";
|
||||
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
|
||||
@@ -205,6 +208,9 @@ function ThreadNavigationSidebarPane(
|
||||
snoozeThread,
|
||||
unsnoozeThread,
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -481,6 +487,37 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinningEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinning === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === true) {
|
||||
supported.add(environmentId);
|
||||
}
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
// Canonical arranged pinned order for Move up/down flags — computed from
|
||||
// all shells so search/scope filtering never disables a valid move.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -589,7 +626,6 @@ function ThreadNavigationSidebarPane(
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
|
||||
const listMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -792,6 +828,7 @@ function ThreadNavigationSidebarPane(
|
||||
previous.item.thread === item.item.thread &&
|
||||
previous.item.variant === item.item.variant &&
|
||||
previous.item.snoozed === item.item.snoozed &&
|
||||
previous.item.pinned === item.item.pinned &&
|
||||
previous.snoozeWakeLabelText === item.snoozeWakeLabelText
|
||||
);
|
||||
}
|
||||
@@ -879,6 +916,7 @@ function ThreadNavigationSidebarPane(
|
||||
thread={thread}
|
||||
variant={item.item.variant}
|
||||
snoozed={item.item.snoozed}
|
||||
pinned={item.item.pinned}
|
||||
snoozePresetMinute={nowMinute}
|
||||
snoozeWakeLabelText={item.snoozeWakeLabelText}
|
||||
project={projectByKey.get(scopeKey) ?? null}
|
||||
@@ -915,9 +953,21 @@ function ThreadNavigationSidebarPane(
|
||||
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}
|
||||
@@ -1038,13 +1088,18 @@ function ThreadNavigationSidebarPane(
|
||||
},
|
||||
[
|
||||
archiveThread,
|
||||
arrangedPinnedKeys,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
movePinnedThread,
|
||||
openPendingTask,
|
||||
pinReorderEnvironmentIds,
|
||||
pinThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
projectTitleByProjectKey,
|
||||
@@ -1064,6 +1119,7 @@ function ThreadNavigationSidebarPane(
|
||||
nowMinute,
|
||||
toggleSettledShelf,
|
||||
toggleSnoozedShelf,
|
||||
unpinThread,
|
||||
unsettleThread,
|
||||
unsnoozeThread,
|
||||
updateGroupDisplay,
|
||||
@@ -1134,6 +1190,13 @@ 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",
|
||||
@@ -1184,17 +1247,6 @@ 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>
|
||||
@@ -1285,9 +1337,19 @@ function ThreadNavigationSidebarPane(
|
||||
</Svg>
|
||||
</View>
|
||||
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
|
||||
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
Threads
|
||||
</Text>
|
||||
{/* 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>
|
||||
}
|
||||
/>
|
||||
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
|
||||
<ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
|
||||
<SidebarFilterButton
|
||||
@@ -1316,16 +1378,6 @@ 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,6 +8,10 @@ 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";
|
||||
@@ -190,6 +194,20 @@ 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();
|
||||
@@ -766,6 +784,7 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
|
||||
@@ -0,0 +1,678 @@
|
||||
import type {
|
||||
ModelSelection,
|
||||
ProviderInteractionMode,
|
||||
ProviderOptionDescriptor,
|
||||
ProviderOptionSelection,
|
||||
RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getProviderOptionCurrentLabel,
|
||||
getProviderOptionCurrentValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
Modal,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
Switch,
|
||||
useWindowDimensions,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { ProviderIcon } from "../../components/ProviderIcon";
|
||||
import { cn } from "../../lib/cn";
|
||||
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
|
||||
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
|
||||
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
|
||||
|
||||
/**
|
||||
* The everyday harnesses stay expanded; every other provider (OpenRouter
|
||||
* catalogs and friends) folds behind its header so a 300-model catalog can't
|
||||
* bury the list.
|
||||
*/
|
||||
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
|
||||
|
||||
/**
|
||||
* Desktop-oriented effort keywords that don't belong in the phone picker.
|
||||
* Prompt-injected values (ultrathink and friends) are filtered from the
|
||||
* descriptor metadata; ultracode is a real option but a workflow trigger, not
|
||||
* a reasoning level. A value set elsewhere still displays, it just isn't
|
||||
* offered.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
const RUNTIME_MODE_CHOICES: ReadonlyArray<{
|
||||
readonly mode: RuntimeMode;
|
||||
readonly label: string;
|
||||
readonly shortLabel: string;
|
||||
}> = [
|
||||
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
|
||||
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
|
||||
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
|
||||
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
|
||||
];
|
||||
|
||||
/**
|
||||
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
|
||||
* covering model, provider options, runtime mode, and plan mode in one label.
|
||||
*/
|
||||
export function threadSettingsSummaryLabel(input: {
|
||||
readonly modelLabel: string;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly interactionMode: ProviderInteractionMode;
|
||||
}): string {
|
||||
const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
|
||||
return [
|
||||
input.modelLabel,
|
||||
...providerOptionValueLabels(input.optionDescriptors),
|
||||
...(runtime ? [runtime.shortLabel] : []),
|
||||
...(input.interactionMode === "plan" ? ["Plan"] : []),
|
||||
].join(" · ");
|
||||
}
|
||||
|
||||
function selectableChoices(descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>) {
|
||||
const injected = new Set(descriptor.promptInjectedValues ?? []);
|
||||
return descriptor.options.filter(
|
||||
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
|
||||
);
|
||||
}
|
||||
|
||||
function ModelRow(props: {
|
||||
readonly option: ModelOption;
|
||||
readonly selected: boolean;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const primaryFg = useThemeColor("--color-primary-foreground");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: props.selected }}
|
||||
onPress={props.onPress}
|
||||
// Selected rows get the same primary treatment as the submenu rows.
|
||||
// Subtle backgrounds (bg-subtle-strong) get overridden by the OS
|
||||
// selection chrome on iOS 26, so use the explicit high-contrast style
|
||||
// everywhere instead.
|
||||
className={cn(
|
||||
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
|
||||
props.selected ? "bg-primary" : "bg-transparent",
|
||||
)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-sm font-t3-medium",
|
||||
props.selected ? "text-primary-foreground" : "text-foreground",
|
||||
)}
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.option.label}
|
||||
</Text>
|
||||
{props.option.isDefault ? (
|
||||
<View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
|
||||
<Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
|
||||
</View>
|
||||
) : null}
|
||||
{props.option.isLegacy ? (
|
||||
<View className="rounded-md bg-subtle px-1.5 py-0.5">
|
||||
<Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
|
||||
</View>
|
||||
) : null}
|
||||
<View className="flex-1" />
|
||||
{props.selected ? (
|
||||
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Provider section header with the harness logo. Secondary providers render
|
||||
* as a tappable fold (count + chevron while collapsed); primary providers
|
||||
* and the group holding the current selection are static headers.
|
||||
*/
|
||||
function ProviderHeader(props: {
|
||||
readonly driver: string | undefined;
|
||||
readonly label: string;
|
||||
readonly collapsible: boolean;
|
||||
readonly collapsed: boolean;
|
||||
readonly modelCount: number;
|
||||
readonly onToggle: () => void;
|
||||
}) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole={props.collapsible ? "button" : "header"}
|
||||
accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
|
||||
accessibilityLabel={
|
||||
props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
|
||||
}
|
||||
disabled={!props.collapsible}
|
||||
onPress={props.onToggle}
|
||||
className={cn(
|
||||
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
|
||||
props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
|
||||
)}
|
||||
>
|
||||
<ProviderIcon provider={props.driver} size={15} />
|
||||
<Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
|
||||
{props.label}
|
||||
</Text>
|
||||
{props.collapsible ? (
|
||||
<>
|
||||
<View className="flex-1" />
|
||||
{props.collapsed ? (
|
||||
<Text className="text-2xs font-t3-medium text-foreground-muted">
|
||||
{props.modelCount}
|
||||
</Text>
|
||||
) : null}
|
||||
<SymbolView
|
||||
name={props.collapsed ? "chevron.down" : "chevron.up"}
|
||||
size={11}
|
||||
tintColor={iconSubtle}
|
||||
type="monochrome"
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/** Compact row that opens a single-choice submenu panel. */
|
||||
function DisclosureRow(props: {
|
||||
readonly label: string;
|
||||
readonly value: string | undefined;
|
||||
readonly disabled?: boolean;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const iconSubtle = useThemeColor("--color-icon-subtle");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={props.disabled}
|
||||
onPress={props.onPress}
|
||||
className={cn(
|
||||
"flex-row items-center gap-2 px-5 py-3 active:opacity-70",
|
||||
props.disabled && "opacity-40",
|
||||
)}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
|
||||
<View className="flex-1" />
|
||||
{props.value ? (
|
||||
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
|
||||
{props.value}
|
||||
</Text>
|
||||
) : null}
|
||||
<SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
/** Single option inside a submenu panel. */
|
||||
function ChoiceRow(props: {
|
||||
readonly label: string;
|
||||
readonly selected: boolean;
|
||||
readonly onPress: () => void;
|
||||
}) {
|
||||
const primaryFg = useThemeColor("--color-primary-foreground");
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: props.selected }}
|
||||
onPress={props.onPress}
|
||||
className={cn(
|
||||
"mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
|
||||
props.selected ? "bg-primary" : "bg-transparent",
|
||||
)}
|
||||
>
|
||||
<Text
|
||||
className={cn(
|
||||
"shrink text-sm font-t3-medium",
|
||||
props.selected ? "text-primary-foreground" : "text-foreground",
|
||||
)}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
<View className="flex-1" />
|
||||
{props.selected ? (
|
||||
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
|
||||
function SwitchRow(props: {
|
||||
readonly label: string;
|
||||
readonly value: boolean;
|
||||
readonly disabled?: boolean;
|
||||
readonly onValueChange: (value: boolean) => void;
|
||||
}) {
|
||||
const activeTrack = String(useThemeColor("--color-switch-active"));
|
||||
const track = String(useThemeColor("--color-secondary-border"));
|
||||
return (
|
||||
<View
|
||||
className={cn(
|
||||
"flex-row items-center justify-between px-5 py-2.5",
|
||||
props.disabled && "opacity-40",
|
||||
)}
|
||||
>
|
||||
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
|
||||
<Switch
|
||||
disabled={props.disabled}
|
||||
ios_backgroundColor={track}
|
||||
onValueChange={props.onValueChange}
|
||||
trackColor={{ false: track, true: activeTrack }}
|
||||
value={props.value}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
type SubmenuPage =
|
||||
| { readonly kind: "descriptor"; readonly id: string }
|
||||
| { readonly kind: "runtime" };
|
||||
|
||||
/**
|
||||
* Unified thread settings: the sheet is the provider-grouped model list
|
||||
* (primary harnesses expanded, other providers folded, legacy behind the
|
||||
* top-right pill) with a Save button, plus compact disclosure rows whose
|
||||
* single-choice submenus stack in a small panel over the sheet so it never
|
||||
* changes size. Model changes stage until Save — while staged, the settings
|
||||
* rows edit the staged model's options and Save applies everything together.
|
||||
*
|
||||
* Callers control which harnesses are offered via providerGroups: an
|
||||
* existing thread must pass only its own provider's group, since a session
|
||||
* can't switch harness mid-thread.
|
||||
*
|
||||
* Rendered through an RN Modal (not the root OverlayPortal) so it also
|
||||
* presents above natively-presented form sheets like the new-task draft.
|
||||
* Callers must dismiss the keyboard when opening — the iOS keyboard window
|
||||
* would otherwise cover the lower half of the sheet.
|
||||
*/
|
||||
export function ThreadSettingsSheet(props: {
|
||||
readonly visible: boolean;
|
||||
/**
|
||||
* "save" = the Save/Done button (the user is finished configuring);
|
||||
* "dismiss" = backdrop, grabber, or system back. Hosts only restore the
|
||||
* keyboard for "save" so a stray tap outside a control never pops it.
|
||||
*/
|
||||
readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
|
||||
readonly onDismissed: () => void;
|
||||
readonly providerGroups: ReadonlyArray<ProviderGroup>;
|
||||
readonly selectedModel: ModelSelection | null;
|
||||
readonly onSelectModel: (option: ModelOption) => void;
|
||||
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
|
||||
readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
|
||||
}) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const { height: windowHeight } = useWindowDimensions();
|
||||
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
|
||||
const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
|
||||
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
|
||||
const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
|
||||
const wasPresentedRef = useRef(false);
|
||||
const notifyDismissed = useCallback(() => {
|
||||
if (!wasPresentedRef.current) {
|
||||
return;
|
||||
}
|
||||
wasPresentedRef.current = false;
|
||||
props.onDismissed();
|
||||
}, [props.onDismissed]);
|
||||
|
||||
// Every open starts fresh: no staged model, no submenu, legacy hidden,
|
||||
// secondary providers folded. The sheet stays mounted between opens, so
|
||||
// state would otherwise stick around.
|
||||
useEffect(() => {
|
||||
if (props.visible) {
|
||||
wasPresentedRef.current = true;
|
||||
setShowLegacyToggle(false);
|
||||
setExpandedProviders(new Set());
|
||||
setPendingModel(null);
|
||||
setSubmenu(null);
|
||||
} else if (Platform.OS === "android" && wasPresentedRef.current) {
|
||||
// React Native only emits Modal.onDismiss on iOS. Android uses no exit
|
||||
// animation below, so the post-commit effect is its dismissal boundary.
|
||||
notifyDismissed();
|
||||
}
|
||||
}, [notifyDismissed, props.visible]);
|
||||
|
||||
const isApplied = (option: ModelOption) =>
|
||||
option.selection.instanceId === props.selectedModel?.instanceId &&
|
||||
option.selection.model === props.selectedModel.model;
|
||||
// The list highlights the staged pick; Save turns it into the applied one.
|
||||
const isDisplayed = (option: ModelOption) =>
|
||||
pendingModel ? option.key === pendingModel.key : isApplied(option);
|
||||
|
||||
// While a model is staged, the settings rows describe and edit the staged
|
||||
// model's options (kept on its pending selection); Save applies model and
|
||||
// options together. Otherwise they edit the applied selection directly.
|
||||
const displayedDescriptors = pendingModel
|
||||
? pendingModel.capabilities
|
||||
? getProviderOptionDescriptors({
|
||||
caps: pendingModel.capabilities,
|
||||
selections: pendingModel.selection.options,
|
||||
})
|
||||
: []
|
||||
: props.optionDescriptors;
|
||||
|
||||
const hasLegacyModels = props.providerGroups.some((group) =>
|
||||
group.models.some((model) => model.isLegacy),
|
||||
);
|
||||
// Legacy stays hidden unless the pill is toggled this open; a highlighted
|
||||
// legacy model is exempted from the filter instead of forcing the whole
|
||||
// legacy list visible.
|
||||
const showLegacy = showLegacyToggle;
|
||||
|
||||
// Stable settings rows: the union of descriptors across the primary
|
||||
// harnesses' current models (plus whatever the displayed model advertises)
|
||||
// always renders, with unsupported rows disabled instead of vanishing when
|
||||
// the selection changes. Keyed by label, not id — Claude and Codex use
|
||||
// different ids for the same "Reasoning" concept.
|
||||
const descriptorTemplate = (() => {
|
||||
const seen = new Map<string, { type: "select" | "boolean" }>();
|
||||
for (const group of props.providerGroups) {
|
||||
const driver = group.models[0]?.providerDriver;
|
||||
if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
|
||||
continue;
|
||||
}
|
||||
for (const model of group.models) {
|
||||
if (model.isLegacy) {
|
||||
continue;
|
||||
}
|
||||
for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
|
||||
if (!seen.has(descriptor.label)) {
|
||||
seen.set(descriptor.label, { type: descriptor.type });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const descriptor of displayedDescriptors) {
|
||||
if (!seen.has(descriptor.label)) {
|
||||
seen.set(descriptor.label, { type: descriptor.type });
|
||||
}
|
||||
}
|
||||
return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
|
||||
})();
|
||||
|
||||
const handleSave = () => {
|
||||
if (pendingModel) {
|
||||
void Haptics.selectionAsync();
|
||||
props.onSelectModel(pendingModel);
|
||||
}
|
||||
props.onClose("save");
|
||||
};
|
||||
|
||||
const handleOptionChange = (id: string, value: string | boolean) => {
|
||||
const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
|
||||
if (!next) {
|
||||
return;
|
||||
}
|
||||
if (pendingModel) {
|
||||
setPendingModel({
|
||||
...pendingModel,
|
||||
selection: { ...pendingModel.selection, options: next },
|
||||
});
|
||||
} else {
|
||||
props.onUpdateOptionSelections(next);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleProvider = (providerKey: string) => {
|
||||
setExpandedProviders((current) => {
|
||||
const next = new Set(current);
|
||||
if (!next.delete(providerKey)) {
|
||||
next.add(providerKey);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const activeDescriptor =
|
||||
submenu?.kind === "descriptor"
|
||||
? displayedDescriptors.find(
|
||||
(descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
const submenuContent =
|
||||
submenu?.kind === "runtime"
|
||||
? {
|
||||
title: "Runtime",
|
||||
rows: RUNTIME_MODE_CHOICES.map((choice) => ({
|
||||
id: choice.mode,
|
||||
label: choice.label,
|
||||
selected: choice.mode === props.runtimeMode,
|
||||
onPress: () => {
|
||||
void Haptics.selectionAsync();
|
||||
props.onUpdateRuntimeMode(choice.mode);
|
||||
setSubmenu(null);
|
||||
},
|
||||
})),
|
||||
}
|
||||
: activeDescriptor?.type === "select"
|
||||
? {
|
||||
title: activeDescriptor.label,
|
||||
rows: selectableChoices(activeDescriptor).map((choice) => ({
|
||||
id: choice.id,
|
||||
label: choice.label,
|
||||
selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
|
||||
onPress: () => {
|
||||
void Haptics.selectionAsync();
|
||||
handleOptionChange(activeDescriptor.id, choice.id);
|
||||
setSubmenu(null);
|
||||
},
|
||||
})),
|
||||
}
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Modal
|
||||
transparent
|
||||
statusBarTranslucent
|
||||
navigationBarTranslucent
|
||||
animationType={Platform.OS === "ios" ? "fade" : "none"}
|
||||
visible={props.visible}
|
||||
onDismiss={notifyDismissed}
|
||||
onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
|
||||
>
|
||||
<View className="flex-1 justify-end">
|
||||
<Pressable
|
||||
accessibilityLabel="Close thread settings"
|
||||
className="absolute inset-0 bg-backdrop"
|
||||
onPress={() => props.onClose("dismiss")}
|
||||
/>
|
||||
<View
|
||||
className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
|
||||
style={{ maxHeight: windowHeight * 0.85 }}
|
||||
>
|
||||
{/* The grabber doubles as the accessible close control: the dim
|
||||
backdrop above a tall sheet is a sliver, and VoiceOver can't
|
||||
reach it at all. */}
|
||||
<Pressable
|
||||
accessibilityLabel="Close thread settings"
|
||||
accessibilityRole="button"
|
||||
onPress={() => props.onClose("dismiss")}
|
||||
className="items-center pb-1 pt-2.5"
|
||||
>
|
||||
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
|
||||
</Pressable>
|
||||
{hasLegacyModels ? (
|
||||
<View className="flex-row justify-end px-4 pb-1.5">
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ selected: showLegacy }}
|
||||
hitSlop={8}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
setShowLegacyToggle(!showLegacy);
|
||||
}}
|
||||
className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
|
||||
>
|
||||
<Text className="text-2xs font-t3-medium text-foreground-muted">
|
||||
{showLegacy ? "Hide legacy models" : "Show legacy models"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
) : null}
|
||||
{/* Only the model list scrolls. Provider catalogs can run to
|
||||
hundreds of models (OpenRouter), so the rows below stay pinned
|
||||
and reachable instead of living at the end of that scroll. */}
|
||||
<ScrollView
|
||||
style={{ flexShrink: 1 }}
|
||||
contentContainerStyle={{ paddingBottom: 8 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
>
|
||||
{props.providerGroups.map((group) => {
|
||||
const driver = group.models[0]?.providerDriver;
|
||||
const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
|
||||
const visibleModels = showLegacy
|
||||
? group.models
|
||||
: group.models.filter((model) => !model.isLegacy || isDisplayed(model));
|
||||
if (visibleModels.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const containsSelection = group.models.some(isDisplayed);
|
||||
const collapsible = !isPrimary && !containsSelection;
|
||||
const collapsed = collapsible && !expandedProviders.has(group.providerKey);
|
||||
return (
|
||||
<View key={group.providerKey}>
|
||||
<ProviderHeader
|
||||
driver={driver}
|
||||
label={group.providerLabel}
|
||||
collapsible={collapsible}
|
||||
collapsed={collapsed}
|
||||
modelCount={visibleModels.length}
|
||||
onToggle={() => toggleProvider(group.providerKey)}
|
||||
/>
|
||||
{collapsed
|
||||
? null
|
||||
: visibleModels.map((option) => (
|
||||
<ModelRow
|
||||
key={option.key}
|
||||
option={option}
|
||||
selected={isDisplayed(option)}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
// Re-tapping the applied model cancels staging.
|
||||
setPendingModel((current) =>
|
||||
pendingModelAfterPress({
|
||||
current,
|
||||
pressed: option,
|
||||
pressedIsApplied: isApplied(option),
|
||||
}),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
})}
|
||||
</ScrollView>
|
||||
|
||||
<View className="mx-5 h-px bg-border" />
|
||||
|
||||
<View style={{ paddingBottom: insets.bottom + 12 }}>
|
||||
{descriptorTemplate.map((entry) => {
|
||||
const live = displayedDescriptors.find(
|
||||
(descriptor) => descriptor.label === entry.label,
|
||||
);
|
||||
if ((live?.type ?? entry.type) === "select") {
|
||||
return (
|
||||
<DisclosureRow
|
||||
key={entry.label}
|
||||
label={entry.label}
|
||||
value={live ? getProviderOptionCurrentLabel(live) : undefined}
|
||||
disabled={!live}
|
||||
onPress={() => {
|
||||
if (live) {
|
||||
setSubmenu({ kind: "descriptor", id: live.id });
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SwitchRow
|
||||
key={entry.label}
|
||||
label={entry.label}
|
||||
value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
|
||||
disabled={!live}
|
||||
onValueChange={(value) => {
|
||||
if (live) {
|
||||
handleOptionChange(live.id, value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
<DisclosureRow
|
||||
label="Runtime"
|
||||
value={
|
||||
RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
|
||||
}
|
||||
onPress={() => setSubmenu({ kind: "runtime" })}
|
||||
/>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={handleSave}
|
||||
className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
|
||||
>
|
||||
<Text className="text-sm font-t3-bold text-primary-foreground">
|
||||
{pendingModel ? "Save" : "Done"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</View>
|
||||
|
||||
{/* Submenus stack over the sheet instead of replacing its content,
|
||||
so the main sheet keeps its size while drilling in and out. */}
|
||||
{submenuContent ? (
|
||||
<View className="absolute inset-0 justify-end">
|
||||
<Pressable
|
||||
accessibilityLabel={`Close ${submenuContent.title}`}
|
||||
className="absolute inset-0 bg-backdrop"
|
||||
onPress={() => setSubmenu(null)}
|
||||
/>
|
||||
<View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
|
||||
<Pressable
|
||||
accessibilityLabel={`Close ${submenuContent.title}`}
|
||||
accessibilityRole="button"
|
||||
onPress={() => setSubmenu(null)}
|
||||
className="items-center pb-1 pt-2.5"
|
||||
>
|
||||
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
|
||||
</Pressable>
|
||||
<Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
|
||||
{submenuContent.title}
|
||||
</Text>
|
||||
<ScrollView
|
||||
style={{ maxHeight: windowHeight * 0.5 }}
|
||||
contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
|
||||
showsVerticalScrollIndicator={false}
|
||||
bounces={false}
|
||||
>
|
||||
{submenuContent.rows.map((row) => (
|
||||
<ChoiceRow
|
||||
key={row.id}
|
||||
label={row.label}
|
||||
selected={row.selected}
|
||||
onPress={row.onPress}
|
||||
/>
|
||||
))}
|
||||
</ScrollView>
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -25,9 +25,9 @@ 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 {
|
||||
@@ -59,6 +59,12 @@ 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";
|
||||
|
||||
@@ -109,10 +115,7 @@ export function branchBadgeLabel(input: {
|
||||
}
|
||||
|
||||
type NewTaskFlowContextValue = {
|
||||
readonly logicalProjects: ReadonlyArray<{
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
}>;
|
||||
readonly projectScopes: ReadonlyArray<HomeProjectScope>;
|
||||
readonly selectedEnvironmentId: EnvironmentId | null;
|
||||
readonly selectedProjectKey: string | null;
|
||||
readonly selectedModelKey: string | null;
|
||||
@@ -145,7 +148,10 @@ type NewTaskFlowContextValue = {
|
||||
readonly reset: () => void;
|
||||
readonly setProject: (project: EnvironmentProject) => void;
|
||||
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
|
||||
readonly setSelectedModelKey: (key: string | null) => void;
|
||||
readonly setSelectedModelKey: (
|
||||
key: string | null,
|
||||
options?: ReadonlyArray<ProviderOptionSelection>,
|
||||
) => void;
|
||||
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
|
||||
readonly selectBranch: (branch: VcsRef) => void;
|
||||
readonly setStartFromOrigin: (value: boolean) => void;
|
||||
@@ -175,32 +181,20 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const projects = useProjects();
|
||||
const threads = useThreadShells();
|
||||
const { savedConnectionsById } = useSavedRemoteConnections();
|
||||
|
||||
const repositoryGroups = useMemo(
|
||||
() => groupProjectsByRepository({ projects, threads }),
|
||||
[projects, threads],
|
||||
);
|
||||
const logicalProjects = useMemo(
|
||||
const groupingSettings = useMobileProjectGroupingSettings();
|
||||
const projectScopes = useMemo(
|
||||
() =>
|
||||
pipe(
|
||||
repositoryGroups,
|
||||
Arr.map((group) => {
|
||||
const primaryProject = group.projects[0]?.project;
|
||||
if (!primaryProject) {
|
||||
return null;
|
||||
}
|
||||
return { key: group.key, project: primaryProject };
|
||||
sortHomeProjectScopes({
|
||||
scopes: buildHomeProjectScopes({
|
||||
projects,
|
||||
environmentId: null,
|
||||
projectGroupingMode: groupingSettings.sidebarProjectGroupingMode,
|
||||
}),
|
||||
Arr.filter(
|
||||
(
|
||||
entry,
|
||||
): entry is {
|
||||
readonly key: string;
|
||||
readonly project: EnvironmentProject;
|
||||
} => entry !== null,
|
||||
),
|
||||
),
|
||||
[repositoryGroups],
|
||||
threads,
|
||||
pendingTasks: [],
|
||||
projectSortOrder: "updated_at",
|
||||
}),
|
||||
[groupingSettings.sidebarProjectGroupingMode, projects, threads],
|
||||
);
|
||||
|
||||
const [selectedEnvironmentIdOverride, setSelectedEnvironmentId] = useState<EnvironmentId | null>(
|
||||
@@ -369,14 +363,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
|
||||
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
|
||||
|
||||
// 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.
|
||||
// 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.
|
||||
const draftModelSelection = resolveSelectableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProjectDraft.modelSelection ?? null,
|
||||
);
|
||||
const projectDefaultModelSelection = resolveSelectableModelSelection(
|
||||
const projectDefaultModelSelection = resolveDefaultableModelSelection(
|
||||
selectedEnvironmentServerConfig,
|
||||
selectedProject?.defaultModelSelection ?? null,
|
||||
);
|
||||
@@ -414,7 +410,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
|
||||
);
|
||||
const setSelectedModelKey = useCallback(
|
||||
(key: string | null) => {
|
||||
// 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>) => {
|
||||
if (!key || !selectedProjectDraftKey) {
|
||||
return;
|
||||
}
|
||||
@@ -423,7 +421,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
return;
|
||||
}
|
||||
updateComposerDraftSettings(selectedProjectDraftKey, {
|
||||
modelSelection: option.selection,
|
||||
modelSelection: options ? { ...option.selection, options } : option.selection,
|
||||
});
|
||||
},
|
||||
[modelOptions, selectedProjectDraftKey],
|
||||
@@ -846,7 +844,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
|
||||
const value = useMemo<NewTaskFlowContextValue>(
|
||||
() => ({
|
||||
logicalProjects,
|
||||
projectScopes,
|
||||
selectedEnvironmentId,
|
||||
selectedProjectKey,
|
||||
selectedModelKey,
|
||||
@@ -912,7 +910,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
|
||||
finishEditingPendingTask,
|
||||
interactionMode,
|
||||
loadBranches,
|
||||
logicalProjects,
|
||||
projectScopes,
|
||||
modelOptions,
|
||||
prompt,
|
||||
providerGroups,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,34 @@
|
||||
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" };
|
||||
}
|
||||
@@ -204,6 +204,8 @@ 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;
|
||||
}) {
|
||||
@@ -291,7 +293,9 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
|
||||
) : (
|
||||
<View className="bg-screen">
|
||||
<View className="px-5 py-2.5">{rowContent}</View>
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
{props.showTrailingDivider !== false ? (
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
@@ -305,6 +309,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly variant: "card" | "slim";
|
||||
/** Snoozed-shelf row: shows its wake time and offers Wake. */
|
||||
readonly snoozed?: boolean;
|
||||
/** Pinned-block row: shows the pin glyph and offers Unpin. */
|
||||
readonly pinned?: boolean;
|
||||
/** Preformatted against the parent minute tick so this memoized row's
|
||||
countdown keeps moving. */
|
||||
readonly snoozeWakeLabelText?: string;
|
||||
@@ -325,6 +331,8 @@ 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;
|
||||
@@ -337,11 +345,23 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => void;
|
||||
/** False on environments whose server predates thread.settle/unsettle:
|
||||
swipe + menu fall back to Archive instead of failing on use. */
|
||||
readonly settlementSupported: boolean;
|
||||
/** False on servers that predate thread.snooze/unsnooze. */
|
||||
readonly snoozeSupported: boolean;
|
||||
/** False on servers that predate thread.pin/unpin. */
|
||||
readonly pinningSupported: boolean;
|
||||
/** False on servers that predate thread.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
readonly onMovePinnedThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
|
||||
/** Position flags for the pinned block so the menu disables the move that
|
||||
would fall off the end of the list. */
|
||||
readonly canMovePinnedUp?: boolean;
|
||||
readonly canMovePinnedDown?: boolean;
|
||||
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
|
||||
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
|
||||
/** Reports this row's live PR state up so the partition can auto-settle
|
||||
@@ -368,9 +388,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onUnsnoozeThread,
|
||||
onUnsettleThread,
|
||||
onArchiveThread,
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onMovePinnedThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
const pinnedRow = props.pinned === true;
|
||||
|
||||
const pr = useThreadPr(thread, props.projectCwd ?? props.project?.workspaceRoot ?? null);
|
||||
const prState = pr?.state ?? null;
|
||||
@@ -383,6 +407,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const drawerColor = useThemeColor("--color-drawer");
|
||||
const pressedBackgroundColor = useThemeColor("--color-subtle");
|
||||
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
|
||||
const pinTintColor = useThemeColor("--color-foreground-muted");
|
||||
const sidebarPane = props.pane === "sidebar";
|
||||
const selected = props.selected === true;
|
||||
|
||||
@@ -398,6 +423,16 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
);
|
||||
const handleUnsnooze = useCallback(() => onUnsnoozeThread(thread), [onUnsnoozeThread, thread]);
|
||||
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
|
||||
@@ -434,6 +469,42 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
})),
|
||||
[snoozePresets],
|
||||
);
|
||||
// Pinned cards keep the full lifecycle menu; only the pin item flips to
|
||||
// Unpin. (Settling a pinned thread clears the pin server-side; snoozing
|
||||
// hides the card until wake with the pin intact.)
|
||||
const pinMenuItem = useMemo<MenuAction[]>(
|
||||
() =>
|
||||
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 snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{ id: "settle", title: "Settle", image: "checkmark" },
|
||||
@@ -443,15 +514,24 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
image: "clock",
|
||||
subactions: snoozePresetActions,
|
||||
},
|
||||
...pinMenuItem,
|
||||
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
|
||||
],
|
||||
[snoozePresetActions],
|
||||
[pinMenuItem, snoozePresetActions],
|
||||
);
|
||||
const cardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
|
||||
[pinMenuItem],
|
||||
);
|
||||
const handleMenuAction = useCallback(
|
||||
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
|
||||
if (nativeEvent.event === "settle") handleSettle();
|
||||
if (nativeEvent.event === "unsettle") handleUnsettle();
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
@@ -468,8 +548,12 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
handleUnpin,
|
||||
handleUnsettle,
|
||||
handleUnsnooze,
|
||||
snoozePresets,
|
||||
@@ -560,6 +644,9 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
>
|
||||
{props.projectTitle ?? props.project?.title ?? ""}
|
||||
</Text>
|
||||
{pinnedRow ? (
|
||||
<SymbolView name="pin" size={11} tintColor={pinTintColor} type="monochrome" />
|
||||
) : null}
|
||||
<Text
|
||||
className={cn(
|
||||
"text-xs tabular-nums",
|
||||
@@ -690,7 +777,9 @@ 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>
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
{props.showTrailingDivider !== false ? (
|
||||
<View className="ml-5 h-px bg-border-subtle" />
|
||||
) : null}
|
||||
</View>
|
||||
)}
|
||||
</Pressable>
|
||||
@@ -805,7 +894,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
? SLIM_MENU_ACTIONS
|
||||
: swipeActions.secondary === "snooze"
|
||||
? snoozableCardMenuActions
|
||||
: CARD_MENU_ACTIONS
|
||||
: cardMenuActions
|
||||
}
|
||||
onPressAction={handleMenuAction}
|
||||
shouldOpenOnLongPress
|
||||
|
||||
Loaded 100 of 578 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user