Compare commits

...
48 changed files with 1493 additions and 164 deletions

No files matched your search

+13 -10
View File
@@ -1,6 +1,6 @@
---
name: test-t3-app
description: Launch and test the T3 Code web app in isolated development environments, including first-try browser authentication with one-time pairing URLs, pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, recover from an expired or consumed pairing token, isolate dev state, or prepare test data in state.sqlite.
description: Launch and test the T3 Code web app in isolated development environments, including reusable worktree-scoped dev authentication, real pairing-token recovery, worktree-safe state directories, dev server lifecycle, and direct SQLite inspection or fixture seeding. Use when an agent needs to run T3 locally, test UI behavior in a browser, exercise real pairing behavior, isolate dev state, or prepare test data in state.sqlite.
---
# Test T3 App
@@ -14,25 +14,25 @@ Use this skill for the web client. For iOS Simulator, Android Emulator, or physi
- Use the repository's ignored `.t3` directory for reusable worktree-local state.
- Use `mktemp -d /tmp/t3code-test.XXXXXX` for disposable state and retain the printed absolute path.
3. Start the full web stack with `vp run dev --home-dir <base-dir>`.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and pairing URL from its output.
4. Keep the terminal session alive and read the selected server port, web port, base directory, and explicitly labeled `reusable web pairing URL` from the dev-runner output.
Treat a base directory as disposable only when it was created or deliberately selected for the current test. Never delete or directly seed the shared `~/.t3` directory. Prefer starting with a new temporary base directory over clearing state of uncertain ownership.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing: an automatically opened page can consume the one-time bootstrap token before the controlled browser uses it.
The dev runner disables browser auto-open by default. Do not pass `--browser` during automated testing so the controlled browser remains the only client surface.
## Authenticate the browser on the first navigation
## Authenticate the browser
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
1. Wait for the dev runner's explicitly labeled `reusable web pairing URL`. The server also prints a real one-time pairing URL during startup; do not confuse the two.
2. Use the controlled in-app browser or browser-automation surface available to the agent. Do not use a system-browser launch command during automated testing.
3. Open that complete URL exactly once as the controlled browser's first navigation. Preserve the fragment and token verbatim.
3. Open the complete reusable URL as the controlled browser's first navigation. Preserve the fragment and token verbatim.
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.
The reusable development credential is deterministically derived from the canonical worktree path and is intentionally limited to loopback servers. It may be opened repeatedly by browsers testing the same running worktree. Do not mistake it for a production secret or configure it on a remotely reachable server.
## Recover a consumed or expired pairing token
## Exercise real pairing or recover a one-time token
Create another token against the same database and web URL as the running dev server:
When the behavior under test is pairing itself, create a real one-time token against the same database and web URL as the running dev server:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
@@ -47,6 +47,8 @@ Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>
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. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Real pairing URLs remain secret, short-lived, and single-use. Do not copy them into final responses, screenshots, committed files, or durable logs.
## Inspect or seed SQLite state
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
@@ -64,7 +66,8 @@ Stop the dev process with its terminal interrupt. Preserve the isolated base dir
## Troubleshoot predictably
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
- If the reusable dev URL is rejected, confirm the runner and server use the same worktree and that the backend is loopback-only.
- If a real one-time URL was consumed, issue a new token instead of retrying it.
- If the pairing URL is no longer visible, create a replacement token with both `--dev-url` and `--base-url`.
- If the replacement token is rejected, verify that the CLI and server use the identical absolute base directory and web URL.
- If the UI shows unexpected data, verify that every command uses the identical explicit base directory before editing anything.
+31 -18
View File
@@ -50,11 +50,21 @@ Running `project add` before the backend starts gives it exclusive offline datab
Use direct SQLite mutation only for disposable projection fixtures. Follow `test-t3-app` and stop the backend before writing.
Start a headless backend after seeding:
For an iOS Simulator or Android Emulator, start the backend through the worktree-aware dev runner after seeding:
```bash
vp run dev:server \
--host 127.0.0.1 \
--home-dir <base-dir>
```
Keep the process alive and retain the selected server port plus the explicitly labeled reusable iOS and Android pairing URLs. They contain the worktree-scoped development credential and can be retried against this loopback server.
For a physical device, use the real-pairing path because the reusable development credential is refused on non-loopback hosts:
```bash
node apps/server/src/bin.ts serve \
--host 127.0.0.1 \
--host 0.0.0.0 \
--port <server-port> \
--base-dir <base-dir> \
--no-browser
@@ -64,7 +74,7 @@ Use these client origins:
- iOS Simulator: `http://127.0.0.1:<server-port>`
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
- Physical device: use the host's reachable LAN origin
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
@@ -123,7 +133,21 @@ adb -s <emulator-serial> shell am start -W \
Do not start, stop, erase, or reconfigure an emulator owned by another task. Track and later stop only processes owned by this test.
## Pair each client once
## Connect a simulator or emulator
After the development client is running the correct Metro bundle, open the matching reusable URL printed by `vp run dev:server`:
```bash
xcrun simctl openurl <simulator-udid> '<printed-reusable-ios-pairing-url>'
adb -s <emulator-serial> shell am start -W \
-a android.intent.action.VIEW \
-d '<printed-reusable-android-pairing-url>' \
com.t3tools.t3code.dev
```
Run only the command for the selected platform. The `connections/new` route automatically sends the embedded credential through the normal onboarding exchange; verify that it closes and the expected seeded projects appear. The reusable development URL may be reopened after resetting the client connection.
## Pair a physical device or test real pairing
Issue a fresh credential against the running backend's exact base directory:
@@ -137,21 +161,9 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
```bash
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
adb -s <emulator-serial> shell am start -W \
-a android.intent.action.VIEW \
-d 't3code-dev://connections/new' \
com.t3tools.t3code.dev
```
Run only the command for the selected platform.
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
Real pairing credentials are secret, short-lived, and single-use. Create a different credential for every physical device or real-pairing test client. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
## Drive and observe the affected flow
@@ -182,7 +194,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
- **A simulator or emulator cannot reconnect:** reopen the platform-specific reusable URL and confirm the backend is still loopback-only.
- **A physical or real-pairing client cannot pair:** pairing tokens are single-use; issue another token.
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
+370
View File
@@ -0,0 +1,370 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>T3 Code — Agent-Friendly Development Authentication</title>
<style>
:root {
color-scheme: dark;
--bg: #000;
--text: #fff;
--muted: #a3a3a3;
--surface: #101010;
--surface-2: #171717;
--line: #292929;
--green: #55e6a5;
--blue: #67b7ff;
--amber: #f4c65d;
--red: #ff7d7d;
--radius: 14px;
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
background: var(--bg);
color: var(--text);
font: 15px/1.6 ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}
main { width: min(1120px, calc(100% - 32px)); margin: 0 auto; padding: 64px 0 96px; }
h1, h2, h3 { margin: 0; line-height: 1.15; letter-spacing: -0.025em; }
h1 { max-width: 850px; font-size: clamp(2.4rem, 7vw, 5.4rem); }
h2 { font-size: clamp(1.5rem, 3vw, 2.25rem); }
h3 { font-size: 1rem; letter-spacing: 0; }
p { margin: 0; }
code {
color: #dff7eb;
font: 0.9em ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
pre {
margin: 0;
overflow: auto;
padding: 16px;
border: 1px solid var(--line);
border-radius: 10px;
background: #080808;
color: #dff7eb;
font: 13px/1.65 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
}
section { margin-top: 72px; }
.eyebrow {
margin-bottom: 18px;
color: var(--green);
font: 700 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.lede { max-width: 760px; margin-top: 24px; color: #d4d4d4; font-size: 1.15rem; }
.meta { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 28px; }
.pill {
padding: 7px 11px;
border: 1px solid var(--line);
border-radius: 999px;
background: var(--surface);
color: var(--muted);
font-size: 12px;
}
.pill strong { color: var(--text); }
.callout {
margin-top: 32px;
padding: 22px;
border: 1px solid #245d45;
border-radius: var(--radius);
background: #07150f;
}
.callout strong { color: var(--green); }
.section-head { display: grid; gap: 10px; max-width: 740px; margin-bottom: 26px; }
.section-head p { color: var(--muted); }
.grid { display: grid; gap: 16px; }
.grid.three { grid-template-columns: repeat(3, 1fr); }
.grid.two { grid-template-columns: repeat(2, 1fr); }
.card {
padding: 20px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
}
.card p { margin-top: 9px; color: var(--muted); }
.card .number {
display: grid;
place-items: center;
width: 30px;
height: 30px;
margin-bottom: 18px;
border-radius: 50%;
background: var(--text);
color: var(--bg);
font-weight: 800;
}
.command-grid { display: grid; grid-template-columns: 170px 1fr; gap: 1px; overflow: hidden; border: 1px solid var(--line); border-radius: var(--radius); background: var(--line); }
.command-grid > div { padding: 14px 16px; background: var(--surface); }
.command-grid .label { color: var(--muted); }
.diagram {
overflow-x: auto;
padding: 20px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
}
.diagram svg { display: block; min-width: 840px; width: 100%; height: auto; }
.steps { counter-reset: step; display: grid; gap: 14px; }
.step {
position: relative;
padding: 20px 20px 20px 66px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
}
.step::before {
counter-increment: step;
content: counter(step);
position: absolute;
top: 18px;
left: 20px;
display: grid;
place-items: center;
width: 28px;
height: 28px;
border-radius: 8px;
background: var(--surface-2);
color: var(--green);
font-weight: 800;
}
.step p { margin-top: 7px; color: var(--muted); }
.file-list { display: grid; gap: 8px; }
.file {
display: grid;
grid-template-columns: minmax(230px, 0.8fr) 1.2fr;
gap: 18px;
padding: 14px 16px;
border-bottom: 1px solid var(--line);
}
.file:last-child { border-bottom: 0; }
.file span { color: var(--muted); }
.checklist { display: grid; gap: 10px; margin: 0; padding: 0; list-style: none; }
.checklist li { position: relative; padding-left: 30px; color: #d4d4d4; }
.checklist li::before { content: "✓"; position: absolute; left: 0; color: var(--green); font-weight: 800; }
.warning { border-color: #5b4820; background: #161105; }
.warning strong { color: var(--amber); }
.not-doing { color: var(--red); }
footer { margin-top: 80px; padding-top: 22px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }
@media (max-width: 820px) {
main { padding-top: 40px; }
section { margin-top: 52px; }
.grid.three, .grid.two { grid-template-columns: 1fr; }
.command-grid, .file { grid-template-columns: 1fr; }
.command-grid .label { padding-bottom: 6px; }
.file { gap: 4px; }
}
</style>
</head>
<body>
<main>
<header>
<div class="eyebrow">Implementation plan · T3 Code</div>
<h1>Development auth that agents never have to think about.</h1>
<p class="lede">
Derive a reusable development key from the canonical worktree path, print it in ordinary
pairing URLs, and let the existing browser and mobile pairing flows do the rest.
</p>
<div class="meta">
<span class="pill"><strong>Scope:</strong> web, iOS Simulator, Android Emulator</span>
<span class="pill"><strong>Boundary:</strong> explicit, loopback-only development mode</span>
<span class="pill"><strong>Steady state:</strong> existing sessions and WebSocket tickets</span>
</div>
<div class="callout">
<strong>Core decision:</strong> the path-derived value is a development instance key, not a secret.
It may appear in development pairing URLs. Its value is unlimited reuse, not secrecy.
</div>
</header>
<section>
<div class="section-head">
<div class="eyebrow">Target experience</div>
<h2>Keep the commands agents already use</h2>
<p>The runner prepares the server and prints reusable web, iOS, and Android connection URLs; the testing skills continue to own browsers, Metro, simulators, and emulators.</p>
</div>
<div class="command-grid" role="table" aria-label="Development commands">
<div class="label">Web stack</div><div><code>vp run dev --home-dir &lt;base-dir&gt;</code></div>
<div class="label">Mobile backend</div><div><code>vp run dev:server --home-dir &lt;base-dir&gt; --host 127.0.0.1</code></div>
<div class="label">Mobile client</div><div><span class="label">Reuse/start Metro and drive the selected device with </span><code>test-t3-mobile</code></div>
<div class="label">Physical device</div><div><span class="label">Use existing real pairing; the development key is never accepted on a LAN bind.</span></div>
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Architecture</div>
<h2>A bootstrap, not a bypass</h2>
<p>The only new server behavior is a reusable, loopback-only grant. Existing pairing screens and token exchanges remain the client implementation.</p>
</div>
<div class="diagram">
<svg viewBox="0 0 1000 330" role="img" aria-labelledby="diagram-title diagram-desc">
<title id="diagram-title">Development authentication flow</title>
<desc id="diagram-desc">The dev runner derives a key, seeds it on the server, prints an ordinary reusable pairing URL, and the existing client pairing flow exchanges it for a normal session.</desc>
<defs>
<marker id="arrow" markerWidth="9" markerHeight="9" refX="8" refY="4.5" orient="auto">
<path d="M0,0 L9,4.5 L0,9 Z" fill="#67b7ff" />
</marker>
</defs>
<rect x="30" y="80" width="210" height="150" rx="16" fill="#171717" stroke="#3a3a3a" />
<text x="55" y="116" fill="#55e6a5" font-size="14" font-weight="700">DEV RUNNER</text>
<text x="55" y="151" fill="#fff" font-size="18" font-weight="700">Canonical Git root</text>
<text x="55" y="180" fill="#a3a3a3" font-size="14">realpath → SHA-256</text>
<text x="55" y="207" fill="#a3a3a3" font-size="14">print reusable pair URLs</text>
<rect x="395" y="25" width="230" height="120" rx="16" fill="#171717" stroke="#3a3a3a" />
<text x="420" y="60" fill="#67b7ff" font-size="14" font-weight="700">SERVER</text>
<text x="420" y="91" fill="#fff" font-size="17" font-weight="700">Reusable dev grant</text>
<text x="420" y="120" fill="#a3a3a3" font-size="14">administrative bootstrap scopes</text>
<rect x="395" y="185" width="230" height="120" rx="16" fill="#171717" stroke="#3a3a3a" />
<text x="420" y="220" fill="#f4c65d" font-size="14" font-weight="700">CLIENT</text>
<text x="420" y="251" fill="#fff" font-size="17" font-weight="700">Existing pair flow</text>
<text x="420" y="280" fill="#a3a3a3" font-size="14">browser or mobile deep link</text>
<rect x="775" y="80" width="195" height="150" rx="16" fill="#07150f" stroke="#245d45" />
<text x="800" y="116" fill="#55e6a5" font-size="14" font-weight="700">STEADY STATE</text>
<text x="800" y="151" fill="#fff" font-size="17" font-weight="700">Normal session</text>
<text x="800" y="180" fill="#a3a3a3" font-size="14">cookie / bearer / DPoP</text>
<text x="800" y="207" fill="#a3a3a3" font-size="14">existing WS tickets</text>
<path d="M240 125 H380" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
<path d="M240 190 C300 190 320 245 380 245" fill="none" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
<path d="M625 245 C700 245 690 185 760 185" fill="none" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
<path d="M625 86 H760" stroke="#67b7ff" stroke-width="2" marker-end="url(#arrow)" />
<text x="654" y="72" fill="#a3a3a3" font-size="12">accept key</text>
<text x="658" y="266" fill="#a3a3a3" font-size="12">issue session</text>
</svg>
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Implementation</div>
<h2>Four small changes</h2>
</div>
<div class="steps">
<article class="step">
<h3>Derive and print one stable development key</h3>
<p>Resolve the canonical Git worktree root and compute <code>sha256("t3-dev:" + realpath(root))</code>. The runner exports <code>T3CODE_DEV_AUTH=1</code> and <code>T3CODE_DEV_AUTH_KEY</code> to its server child, then prints a reusable web pairing URL plus separate iOS and Android connection deep links containing the same key.</p>
</article>
<article class="step">
<h3>Seed a reusable server bootstrap grant</h3>
<p>Read the two environment variables in server configuration. When explicitly enabled on a loopback bind, seed the key with administrative bootstrap scopes and unlimited exchanges for the process lifetime. Refuse dev auth for wildcard or non-loopback hosts.</p>
</article>
<article class="step">
<h3>Use existing clients with one tiny mobile adapter</h3>
<p>Web requires no changes: opening <code>/pair#token=…</code> already creates its cookie session. Mobile accepts the printed host and credential on the existing <code>connections/new</code> route and forwards them to current connection onboarding.</p>
</article>
<article class="step">
<h3>Simplify the testing skills</h3>
<p>The web skill opens the reusable URL exactly as it opens today’s one-time URL. The mobile skill keeps responsibility for Metro reuse, device selection, and platform-specific origins, then opens the printed deep link. Real one-time pairing remains the physical-device and auth-test path.</p>
</article>
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Likely touchpoints</div>
<h2>Keep the change narrow</h2>
</div>
<div class="card file-list">
<div class="file"><code>scripts/dev-runner.ts</code><span>Derive/export the key and print reusable web/mobile connection information. Do not orchestrate devices.</span></div>
<div class="file"><code>apps/server/src/cli/config.ts</code><span>Read the explicit dev-auth configuration.</span></div>
<div class="file"><code>apps/server/src/config.ts</code><span>Carry the dev-auth key and enabled state.</span></div>
<div class="file"><code>apps/server/src/auth/PairingGrantStore.ts</code><span>Seed the reusable grant using the existing desktop pattern and enforce loopback-only use.</span></div>
<div class="file"><code>apps/server/src/auth/utils.ts</code><span>Namespace development cookies by server port.</span></div>
<div class="file"><code>apps/mobile/src/Stack.tsx</code><span>Accept host and credential parameters on the existing connections route.</span></div>
<div class="file"><code>apps/mobile/src/connection/onboarding.ts</code><span>Feed the development deep link into existing pairing onboarding.</span></div>
<div class="file"><code>.agents/skills/test-t3-app/SKILL.md</code><span>Open the reusable dev pairing URL; keep one-time recovery for real-auth tests.</span></div>
<div class="file"><code>.agents/skills/test-t3-mobile/SKILL.md</code><span>Use dev:server output for simulators/emulators; keep real pairing for physical devices.</span></div>
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Guardrails</div>
<h2>Deliberately unsafe, tightly contained</h2>
</div>
<div class="grid three">
<article class="card">
<h3>Explicit activation</h3>
<p>The server accepts the key only when <code>T3CODE_DEV_AUTH=1</code>. Production defaults never infer it from the filesystem.</p>
</article>
<article class="card">
<h3>Loopback only</h3>
<p>The server refuses this guessable key on wildcard, LAN, Tailnet, or other non-loopback binds. Physical-device verification uses real pairing.</p>
</article>
<article class="card">
<h3>Real auth coexists</h3>
<p>Existing startup pairing output and <code>auth pairing create</code> remain available. No special <code>--auth real</code> mode is needed.</p>
</article>
</div>
<div class="callout warning">
<strong>The key is intentionally public.</strong> It may appear in terminal output and development URLs. Never substitute <code>T3_MCP_BEARER_TOKEN</code>, which authorizes agent MCP access.
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Verification</div>
<h2>Acceptance checklist</h2>
</div>
<div class="grid two">
<article class="card">
<h3>Focused automated coverage</h3>
<ul class="checklist">
<li>Same canonical worktree produces the same key.</li>
<li>Different worktrees produce different keys.</li>
<li>The dev grant supports repeated exchange.</li>
<li>A mismatched or absent key is rejected.</li>
<li>Non-loopback dev auth is rejected.</li>
<li>Production behavior is unchanged.</li>
<li>Parallel dev cookies do not collide.</li>
<li>Mobile deep-link registration is idempotent.</li>
</ul>
</article>
<article class="card">
<h3>Integrated proof</h3>
<ul class="checklist">
<li>Run one isolated web environment and open its printed reusable pairing URL.</li>
<li>Open that URL again in a fresh browser context and confirm both exchanges succeed.</li>
<li>Run one representative iOS Simulator or Android Emulator environment.</li>
<li>Start/reuse Metro with the mobile skill and open the printed connection deep link.</li>
<li>Confirm seeded projects load from the intended backend.</li>
<li>Confirm a LAN-bound backend falls back to real one-time pairing.</li>
<li>Stop all owned processes and clean disposable state.</li>
</ul>
</article>
</div>
</section>
<section>
<div class="section-head">
<div class="eyebrow">Non-goals</div>
<h2>What this plan avoids</h2>
</div>
<div class="card">
<ul class="checklist">
<li><span class="not-doing">No</span> custom authorization header on every request.</li>
<li><span class="not-doing">No</span> alternate WebSocket authentication protocol.</li>
<li><span class="not-doing">No</span> persisted development secret or token recovery workflow.</li>
<li><span class="not-doing">No</span> Vite, web-auth bootstrap, or mobile bundle configuration changes.</li>
<li><span class="not-doing">No</span> new runner flag for device selection or lifecycle.</li>
<li><span class="not-doing">No</span> changes to desktop, whose reusable bootstrap already works.</li>
<li><span class="not-doing">No</span> weakening of production pairing, scopes, sessions, or DPoP.</li>
<li><span class="not-doing">No</span> automatic native rebuild when a compatible dev client already exists.</li>
</ul>
</div>
</section>
<footer>
Proposed implementation order: runner key and URLs → loopback-only reusable server grant → mobile route adapter → skill updates → focused integrated verification.
</footer>
</main>
</body>
</html>
@@ -2,7 +2,7 @@ import { CameraView, useCameraPermissions } from "expo-camera";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useState } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -17,6 +17,7 @@ import { buildPairingUrl, parsePairingUrl } from "./pairing";
type ConnectionsNewRouteParams = {
readonly mode?: string;
readonly pairingUrl?: string | readonly string[];
};
export function ConnectionsNewRouteScreen({
@@ -37,6 +38,7 @@ export function ConnectionsNewRouteScreen({
const [showScanner, setShowScanner] = useState(params.mode === "scan_qr");
const [cameraPermission, requestCameraPermission] = useCameraPermissions();
const [scannerLocked, setScannerLocked] = useState(false);
const lastAutomaticPairingUrl = useRef<string | null>(null);
const headerIconColor = useThemeColor("--color-icon");
@@ -62,6 +64,40 @@ export function ConnectionsNewRouteScreen({
setCodeInput(value);
}, []);
const connectPairingUrl = useCallback(
async (pairingUrl: string) => {
const { host, code } = parsePairingUrl(pairingUrl);
setHostInput(host);
setCodeInput(code);
setIsSubmitting(true);
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
} else {
setIsSubmitting(false);
}
},
[navigation, onChangeConnectionPairingUrl, onConnectPress],
);
useEffect(() => {
const routePairingUrl = Array.isArray(params.pairingUrl)
? params.pairingUrl[0]
: params.pairingUrl;
if (!routePairingUrl?.trim() || lastAutomaticPairingUrl.current === routePairingUrl) {
return;
}
lastAutomaticPairingUrl.current = routePairingUrl;
void connectPairingUrl(routePairingUrl);
}, [connectPairingUrl, params.pairingUrl]);
const openScanner = useCallback(async () => {
if (cameraPermission?.granted) {
setScannerLocked(false);
@@ -117,21 +153,8 @@ export function ConnectionsNewRouteScreen({
);
const handleSubmit = useCallback(async () => {
setIsSubmitting(true);
const pairingUrl = buildPairingUrl(hostInput, codeInput);
onChangeConnectionPairingUrl(pairingUrl);
const result = await onConnectPress(pairingUrl);
if (AsyncResult.isSuccess(result)) {
if (navigation.canGoBack()) {
navigation.goBack();
} else {
navigation.dispatch(StackActions.replace("Home"));
}
} else {
setIsSubmitting(false);
}
}, [codeInput, hostInput, onChangeConnectionPairingUrl, onConnectPress, navigation]);
await connectPairingUrl(buildPairingUrl(hostInput, codeInput));
}, [codeInput, connectPairingUrl, hostInput]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -58,6 +58,8 @@ import { type VcsRef } from "@t3tools/client-runtime/state/vcs";
type WorkspaceMode = "local" | "worktree";
const EMPTY_BRANCH_REFS: ReadonlyArray<VcsRef> = [];
function pendingTaskDraftKey(messageId: string): string {
return `pending-task:${messageId}`;
}
@@ -348,7 +350,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? "local";
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
const startFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin ?? false;
// Keep the user's explicit choice separate from the resolved display value:
// only the explicit flag is ever written back to the draft, so the resolved
// value keeps tracking the server setting when the config loads late.
const draftStartFromOrigin = selectedProjectDraft.workspaceSelection?.startFromOrigin;
const startFromOrigin =
draftStartFromOrigin ??
selectedEnvironmentServerConfig?.settings.newWorktreesStartFromOrigin ??
true;
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
@@ -368,6 +377,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedModel =
selectedProjectDraft.modelSelection ??
selectedProject?.defaultModelSelection ??
modelOptions.find((option) => option.isDefault)?.selection ??
modelOptions[0]?.selection ??
null;
const selectedModelKey = selectedModel
@@ -475,13 +485,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
);
const branchState = useBranches(branchTarget);
const branchesLoading = branchState.isPending;
const allBranchRefs = branchState.data?.refs ?? EMPTY_BRANCH_REFS;
const availableBranches = useMemo(
() =>
pipe(
branchState.data?.refs ?? [],
allBranchRefs,
Arr.filter((branch) => !branch.isRemote),
),
[branchState.data?.refs],
[allBranchRefs],
);
const filteredBranches = useMemo(() => {
@@ -543,11 +554,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode,
branch: selectedBranchName,
worktreePath: selectedWorktreePath,
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedBranchName, selectedProjectDraftKey, selectedWorktreePath, startFromOrigin],
[draftStartFromOrigin, selectedBranchName, selectedProjectDraftKey, selectedWorktreePath],
);
const selectBranch = useCallback(
@@ -560,11 +571,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
mode: workspaceMode,
branch: branch.name,
worktreePath: normalizeSelectedWorktreePath(selectedProject, branch),
startFromOrigin,
...(draftStartFromOrigin !== undefined ? { startFromOrigin: draftStartFromOrigin } : {}),
},
});
},
[selectedProject, selectedProjectDraftKey, startFromOrigin, workspaceMode],
[draftStartFromOrigin, selectedProject, selectedProjectDraftKey, workspaceMode],
);
const setStartFromOrigin = useCallback(
@@ -597,14 +608,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
// availableBranches filters out — search the unfiltered refs for it.
const preferredBranch =
allBranchRefs.find((branch) => branch.isDefault) ??
availableBranches.find((branch) => branch.current) ??
availableBranches.find((branch) => branch.isDefault) ??
null;
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -696,7 +709,12 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
workspaceMode: mode,
branch: workspaceSelection?.branch ?? null,
worktreePath: mode === "worktree" ? null : (workspaceSelection?.worktreePath ?? null),
...(workspaceSelection?.startFromOrigin ? { startFromOrigin: true } : {}),
// The draft only carries the flag when the user touched it; fall
// back to the resolved default (server settings) so queued tasks
// drain with the same origin mode the composer displayed.
...((workspaceSelection?.startFromOrigin ?? startFromOrigin)
? { startFromOrigin: true }
: {}),
},
createdAt: metadata.createdAt,
};
@@ -707,6 +725,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
selectedModel,
selectedProject,
selectedProjectDraftKey,
startFromOrigin,
],
);
+3
View File
@@ -15,6 +15,7 @@ export type ModelOption = {
readonly providerKey: string;
readonly providerLabel: string;
readonly providerDriver: string;
readonly isDefault: boolean;
readonly capabilities: ModelCapabilities | null;
readonly selection: ModelSelection;
};
@@ -78,6 +79,7 @@ export function buildModelOptions(
providerKey: provider.instanceId,
providerLabel,
providerDriver: provider.driver,
isDefault: model.isDefault === true,
capabilities: model.capabilities,
selection: normalizeSelectionOptions(
{
@@ -107,6 +109,7 @@ export function buildModelOptions(
providerKey: fallbackModelSelection.instanceId,
providerLabel,
providerDriver: fallbackModelSelection.instanceId,
isDefault: false,
capabilities: null,
selection: fallbackModelSelection,
});
@@ -80,6 +80,24 @@ it.layer(NodeServices.layer)("EnvironmentAuthPolicy.layer", (it) => {
),
);
it.effect("namespaces loopback web cookies by port when development auth is enabled", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
const descriptor = yield* policy.getDescriptor();
expect(descriptor.sessionCookieName).toBe("t3_session_13773");
}).pipe(
Effect.provide(
makeEnvironmentAuthPolicyLayer({
mode: "web",
host: "127.0.0.1",
port: 13_773,
devAuthKey: "development-auth-key",
}),
),
),
);
it.effect("uses remote-reachable policy for wildcard web hosts", () =>
Effect.gen(function* () {
const policy = yield* EnvironmentAuthPolicy.EnvironmentAuthPolicy;
@@ -1,11 +1,11 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { isLoopbackHost, isWildcardHost } from "@t3tools/shared/networkHost";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ServerConfig from "../config.ts";
import { resolveSessionCookieName } from "./utils.ts";
import { isLoopbackHost, isWildcardHost } from "../startupAccess.ts";
export class EnvironmentAuthPolicy extends Context.Service<
EnvironmentAuthPolicy,
@@ -16,7 +16,8 @@ export class EnvironmentAuthPolicy extends Context.Service<
export const make = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const isRemoteReachable = isWildcardHost(config.host) || !isLoopbackHost(config.host);
const effectiveHost = config.host ?? "127.0.0.1";
const isRemoteReachable = isWildcardHost(effectiveHost) || !isLoopbackHost(effectiveHost);
const policy =
config.mode === "desktop"
@@ -41,6 +42,7 @@ export const make = Effect.gen(function* () {
sessionCookieName: resolveSessionCookieName({
mode: config.mode,
port: config.port,
devAuthEnabled: config.devAuthKey !== undefined,
}),
};
+40 -2
View File
@@ -13,7 +13,9 @@ import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
import * as PairingGrantStore from "./PairingGrantStore.ts";
const makeServerConfigLayer = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
overrides?: Partial<
Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "devAuthKey">
>,
) =>
Layer.effect(
ServerConfig.ServerConfig,
@@ -29,7 +31,9 @@ const makeServerConfigLayer = (
);
const makePairingGrantStoreLayer = (
overrides?: Partial<Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken">>,
overrides?: Partial<
Pick<ServerConfig.ServerConfig["Service"], "desktopBootstrapToken" | "devAuthKey">
>,
) =>
PairingGrantStore.layer.pipe(
Layer.provide(SqlitePersistenceMemory),
@@ -194,6 +198,40 @@ it.layer(NodeServices.layer)("PairingGrantStore.layer", (it) => {
),
);
it.effect("seeds the development credential as a reusable administrative grant", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
const first = yield* bootstrapCredentials.consume("development-auth-key");
yield* TestClock.adjust(Duration.days(2));
const second = yield* bootstrapCredentials.consume("development-auth-key");
expect(first.method).toBe("desktop-bootstrap");
expect(first.subject).toBe("development-bootstrap");
expect(first.scopes).toEqual([
"orchestration:read",
"orchestration:operate",
"terminal:operate",
"review:write",
"relay:read",
"access:read",
"access:write",
"relay:write",
]);
expect(second.method).toBe("desktop-bootstrap");
expect(second.subject).toBe("development-bootstrap");
expect(second.scopes).toEqual(first.scopes);
}).pipe(
Effect.provide(
Layer.merge(
makePairingGrantStoreLayer({
devAuthKey: "development-auth-key",
}),
TestClock.layer(),
),
),
),
);
it.effect("lists and revokes active pairing links", () =>
Effect.gen(function* () {
const bootstrapCredentials = yield* PairingGrantStore.PairingGrantStore;
+13 -2
View File
@@ -242,7 +242,8 @@ const DEFAULT_ONE_TIME_TOKEN_TTL_MINUTES = Duration.minutes(5);
// gets logged anywhere by accident) means a page reload past the 5-min
// window can still recover by re-bootstrapping rather than locking
// the user out of the backend.
const DESKTOP_BOOTSTRAP_TTL_HOURS = Duration.hours(24);
const DESKTOP_BOOTSTRAP_TTL = Duration.hours(24);
const DEVELOPMENT_BOOTSTRAP_EXPIRES_AT = DateTime.makeUnsafe("9999-12-31T23:59:59.999Z");
const PAIRING_TOKEN_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
const PAIRING_TOKEN_LENGTH = 12;
const PAIRING_TOKEN_REJECTION_LIMIT =
@@ -304,7 +305,7 @@ export const make = Effect.gen(function* () {
scopes: AuthAdministrativeScopes,
subject: "desktop-bootstrap",
expiresAt: DateTime.add(now, {
milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL_HOURS),
milliseconds: Duration.toMillis(DESKTOP_BOOTSTRAP_TTL),
}),
// Unbounded uses so the renderer can re-exchange the seed for a
// fresh bearer session after a page reload (or after the prior
@@ -315,6 +316,16 @@ export const make = Effect.gen(function* () {
});
}
if (config.devAuthKey) {
yield* seedGrant(config.devAuthKey, {
method: "desktop-bootstrap",
scopes: AuthAdministrativeScopes,
subject: "development-bootstrap",
expiresAt: DEVELOPMENT_BOOTSTRAP_EXPIRES_AT,
remainingUses: "unbounded",
});
}
const listActive: PairingGrantStore["Service"]["listActive"] = Effect.fn(
"PairingGrantStore.listActive",
)(
+1
View File
@@ -470,6 +470,7 @@ export const make = Effect.gen(function* () {
const cookieName = resolveSessionCookieName({
mode: serverConfig.mode,
port: serverConfig.port,
devAuthEnabled: serverConfig.devAuthKey !== undefined,
});
const emitUpsert = (clientSession: AuthClientSession) =>
+2 -1
View File
@@ -13,8 +13,9 @@ const SESSION_COOKIE_NAME = "t3_session";
export function resolveSessionCookieName(input: {
readonly mode: "web" | "desktop";
readonly port: number;
readonly devAuthEnabled: boolean;
}): string {
if (input.mode !== "desktop") {
if (input.mode !== "desktop" && !input.devAuthEnabled) {
return SESSION_COOKIE_NAME;
}
+1
View File
@@ -87,6 +87,7 @@ const makeCliTestServerConfig = (baseDir: string) =>
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
+177
View File
@@ -120,6 +120,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
@@ -190,6 +191,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: true,
@@ -263,6 +265,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: false,
startupPresentation: "browser",
desktopBootstrapToken: "desktop-bootstrap-token",
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
@@ -337,6 +340,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: "desktop-token",
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
@@ -465,6 +469,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: "desktop-token",
devAuthKey: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
tailscaleServeEnabled: false,
@@ -534,6 +539,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
@@ -597,6 +603,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
noBrowser: true,
startupPresentation: "headless",
desktopBootstrapToken: undefined,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
@@ -604,4 +611,174 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
});
}),
);
it.effect("enables the reusable development credential on loopback", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-" });
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(13_773),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:5733")),
noBrowser: Option.some(true),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_DEV_AUTH: "true",
T3CODE_DEV_AUTH_KEY: "development-auth-key",
},
}),
),
NetService.layer,
),
),
);
expect(resolved.devAuthKey).toBe("development-auth-key");
}),
);
it.effect("requires a reusable development credential when dev auth is enabled", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-missing-" });
const error = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(13_773),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.some(true),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: { T3CODE_DEV_AUTH: "true" },
}),
),
NetService.layer,
),
),
Effect.flip,
);
expect(error._tag).toBe("MissingDevAuthKeyError");
expect(error.message).toContain("T3CODE_DEV_AUTH_KEY is required");
}),
);
it.effect("rejects reusable development credentials on non-loopback hosts", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-dev-auth-lan-" });
for (const host of [undefined, "0.0.0.0", "127.attacker.example"]) {
const error = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(13_773),
host: Option.fromUndefinedOr(host),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.some(true),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_DEV_AUTH: "true",
T3CODE_DEV_AUTH_KEY: "development-auth-key",
},
}),
),
NetService.layer,
),
),
Effect.flip,
);
expect(error._tag).toBe("NonLoopbackDevAuthHostError");
if (error._tag === "NonLoopbackDevAuthHostError") {
expect(error.host).toBe(host);
expect(error.message).toContain("requires an explicit loopback address");
}
}
}),
);
it.effect("rejects reusable development credentials with Tailscale Serve", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({
prefix: "t3-cli-dev-auth-tailscale-",
});
const error = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(13_773),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.some(true),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.some(true),
tailscaleServePort: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_DEV_AUTH: "true",
T3CODE_DEV_AUTH_KEY: "development-auth-key",
},
}),
),
NetService.layer,
),
),
Effect.flip,
);
expect(error._tag).toBe("TailscaleServeDevAuthError");
expect(error.message).toContain("cannot be enabled with Tailscale Serve");
}),
);
});
+44
View File
@@ -1,4 +1,5 @@
import * as NetService from "@t3tools/shared/Net";
import { isLoopbackAddress } from "@t3tools/shared/networkHost";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
import * as Config from "effect/Config";
@@ -17,6 +18,33 @@ import { readBootstrapEnvelope } from "../bootstrap.ts";
import * as ServerConfig from "../config.ts";
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
export class MissingDevAuthKeyError extends Schema.TaggedErrorClass<MissingDevAuthKeyError>()(
"MissingDevAuthKeyError",
{},
) {
override get message(): string {
return "T3CODE_DEV_AUTH_KEY is required when T3CODE_DEV_AUTH is enabled.";
}
}
export class NonLoopbackDevAuthHostError extends Schema.TaggedErrorClass<NonLoopbackDevAuthHostError>()(
"NonLoopbackDevAuthHostError",
{ host: Schema.optional(Schema.String) },
) {
override get message(): string {
return `T3CODE_DEV_AUTH requires an explicit loopback address; received ${this.host ?? "an omitted host"}.`;
}
}
export class TailscaleServeDevAuthError extends Schema.TaggedErrorClass<TailscaleServeDevAuthError>()(
"TailscaleServeDevAuthError",
{},
) {
override get message(): string {
return "T3CODE_DEV_AUTH cannot be enabled with Tailscale Serve.";
}
}
export const modeFlag = Flag.choice("mode", ServerConfig.RuntimeMode.literals).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
Flag.optional,
@@ -104,6 +132,11 @@ const EnvServerConfig = Config.all({
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
devAuthEnabled: Config.boolean("T3CODE_DEV_AUTH").pipe(Config.withDefault(false)),
devAuthKey: Config.string("T3CODE_DEV_AUTH_KEY").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
@@ -335,6 +368,16 @@ export const resolveServerConfig = (
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
const devAuthKey = env.devAuthEnabled ? env.devAuthKey?.trim() : undefined;
if (env.devAuthEnabled && !devAuthKey) {
return yield* new MissingDevAuthKeyError();
}
if (devAuthKey && !isLoopbackAddress(host)) {
return yield* new NonLoopbackDevAuthHostError(host === undefined ? {} : { host });
}
if (devAuthKey && tailscaleServeEnabled) {
return yield* new TailscaleServeDevAuthError();
}
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
const config: ServerConfig.ServerConfig["Service"] = {
@@ -366,6 +409,7 @@ export const resolveServerConfig = (
noBrowser,
startupPresentation,
desktopBootstrapToken,
devAuthKey,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
tailscaleServeEnabled,
+2
View File
@@ -75,6 +75,7 @@ export class ServerConfig extends Context.Service<
readonly noBrowser: boolean;
readonly startupPresentation: StartupPresentation;
readonly desktopBootstrapToken: string | undefined;
readonly devAuthKey: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
readonly tailscaleServeEnabled: boolean;
@@ -185,6 +186,7 @@ const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
devAuthKey: undefined,
staticDir: undefined,
devUrl,
noBrowser: false,
@@ -41,6 +41,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
port: 0,
host: undefined,
desktopBootstrapToken: undefined,
devAuthKey: undefined,
staticDir: undefined,
devUrl: undefined,
noBrowser: false,
@@ -1711,6 +1711,133 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("consumes undeclared and UX-internal system subtypes without warning rows", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEvents: Array<ProviderRuntimeEvent> = [];
const runtimeEventsFiber = yield* Stream.runForEach(adapter.streamEvents, (event) =>
Effect.sync(() => runtimeEvents.push(event)),
).pipe(Effect.forkChild);
yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
// Undeclared wire-only roster snapshot + every typed UX-internal
// subtype and top-level type consumed silently: none may surface as
// unknown-subtype warnings.
for (const message of [
{
type: "system",
subtype: "background_tasks_changed",
tasks: [{ task_id: "t1", task_type: "local_agent", description: "Say hi" }],
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "task_updated",
task_id: "t1",
patch: { status: "running" },
session_id: "session",
uuid: "tu",
},
{ type: "system", subtype: "commands_changed", session_id: "session", uuid: "cc" },
{ type: "system", subtype: "model_refusal_fallback", session_id: "session", uuid: "mrf" },
{ type: "system", subtype: "local_command_output", session_id: "session", uuid: "lco" },
{ type: "system", subtype: "plugin_install", session_id: "session", uuid: "pi" },
{ type: "system", subtype: "memory_recall", session_id: "session", uuid: "mr" },
{ type: "system", subtype: "elicitation_complete", session_id: "session", uuid: "ec" },
{ type: "prompt_suggestion", suggestion: "try this", session_id: "session", uuid: "ps" },
{
type: "system",
subtype: "notification",
key: "context",
text: "low priority note",
priority: "low",
session_id: "session",
uuid: "notif",
},
]) {
harness.query.emit(message as unknown as SDKMessage);
}
// High-priority notifications DO surface as a warning row.
harness.query.emit({
type: "system",
subtype: "notification",
key: "limit",
text: "context window nearly full",
priority: "high",
session_id: "session",
uuid: "notif-high",
} as unknown as SDKMessage);
// session_state_changed maps to the matching session states.
for (const [state, uuid] of [
["running", "ssc-run"],
["requires_action", "ssc-req"],
["idle", "ssc-idle"],
]) {
harness.query.emit({
type: "system",
subtype: "session_state_changed",
state,
session_id: "session",
uuid,
} as unknown as SDKMessage);
}
// api_retry maps to a session heartbeat, not a warning row.
harness.query.emit({
type: "system",
subtype: "api_retry",
attempt: 3,
max_retries: 10,
retry_delay_ms: 1000,
error_status: 502,
error: { type: "api_error" },
session_id: "session",
uuid: "retry",
} as unknown as SDKMessage);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
const warnings = runtimeEvents.filter((event) => event.type === "runtime.warning");
// Exactly one warning: the high-priority notification. Nothing else.
assert.deepEqual(
warnings.map((event) => event.payload.message),
["context window nearly full"],
);
const sessionStates = runtimeEvents
.filter((event) => event.type === "session.state.changed")
.map((event) =>
event.type === "session.state.changed"
? `${event.payload.state}:${event.payload.reason ?? ""}`
: "",
)
.filter(
(entry) => entry.startsWith("running:session_state") || entry.includes("session_state"),
);
assert.deepEqual(sessionStates, [
"running:session_state:running",
"waiting:session_state:requires_action",
"ready:session_state:idle",
]);
const heartbeat = runtimeEvents.find(
(event) =>
event.type === "session.state.changed" &&
typeof event.payload.reason === "string" &&
event.payload.reason.startsWith("api_retry:"),
);
assert.equal(heartbeat?.type, "session.state.changed");
runtimeEventsFiber.interruptUnsafe();
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("emits thread token usage updates from Claude task progress", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -3045,7 +3172,7 @@ describe("ClaudeAdapterLive", () => {
attachments: [],
});
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6"]);
assert.deepEqual(harness.query.setModelCalls, ["claude-opus-4-6[1m]"]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3143,10 +3270,11 @@ describe("ClaudeAdapterLive", () => {
yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello again",
modelSelection: {
instanceId: ProviderInstanceId.make("claudeAgent"),
model: "claude-opus-4-6",
},
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "contextWindow", value: "200k" }],
),
attachments: [],
});
@@ -77,6 +77,7 @@ import {
isClaudeUltracodeEffort,
normalizeClaudeCliEffort,
resolveClaudeApiModelId,
resolveClaudeContextWindow,
resolveClaudeEffort,
} from "./ClaudeProvider.ts";
import {
@@ -341,24 +342,18 @@ function selectedClaudeContextWindow(
switch (modelSelection?.model) {
case "claude-opus-4-8":
case "claude-opus-4-7":
// Always 1M at the API; these models expose no contextWindow option.
return 1_000_000;
}
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
if (optionValue === "1m") {
return 1_000_000;
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return 1_000_000;
case "200k":
return 200_000;
default:
return undefined;
}
if (optionValue === "200k") {
return 200_000;
}
const caps = getClaudeModelCapabilities(modelSelection?.model);
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
);
if (hasContextWindowOption) {
return 200_000;
}
return undefined;
}
function finiteNonNegativeInteger(value: unknown): number | undefined {
@@ -2590,6 +2585,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
};
// Undeclared-but-real subtypes (absent from the SDK's union, so they can't
// be switch cases): consumed intentionally without emitting, otherwise
// they fall through to the unknown-subtype warning and surface as spurious
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
}
switch (message.subtype) {
case "init":
yield* offerRuntimeEvent({
@@ -2702,6 +2708,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
yield* emitThreadTokenUsage(
context,
@@ -2746,6 +2757,52 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
case "thinking_tokens":
return;
case "api_retry":
// Transport-level retry heartbeat. Surfacing each attempt as a
// warning row spammed the work log (10 rows during a 502 storm);
// the terminal result/error path reports the actual failure. Keep
// the session visibly alive instead.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state: "running",
reason: `api_retry:${message.attempt}/${message.max_retries}`,
},
});
return;
case "session_state_changed":
// Authoritative turn-over signal from the CLI.
yield* offerRuntimeEvent({
...base,
type: "session.state.changed",
payload: {
state:
message.state === "running"
? "running"
: message.state === "requires_action"
? "waiting"
: "ready",
reason: `session_state:${message.state}`,
},
});
return;
case "notification":
// User-facing CLI notification (e.g. context-limit warnings). Only
// high-priority ones warrant a work-log row.
if (message.priority === "high" || message.priority === "immediate") {
yield* emitRuntimeWarning(context, message.text, message);
}
return;
// Inner protocol/UX details with no T3 surface today — consumed
// deliberately so they don't masquerade as unknown-subtype warnings.
case "model_refusal_fallback":
case "local_command_output":
case "plugin_install":
case "commands_changed":
case "memory_recall":
case "elicitation_complete":
return;
case "permission_denied":
yield* offerRuntimeEvent({
...base,
@@ -2765,13 +2822,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
message,
);
return;
default:
default: {
// Exhaustiveness guard: every subtype in the SDK's typed union is
// handled above, so `message` narrows to never here — a new SDK
// release adding a subtype fails this typecheck instead of silently
// warning at runtime. The runtime fallback still catches undeclared
// wire-only subtypes (like background_tasks_changed used to be).
message satisfies never;
const unknownMessage = message as never as { subtype: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude system message '${message.subtype}'`, message),
describeUnknownSdkMessage(`Claude system message '${unknownMessage.subtype}'`, message),
message,
);
return;
}
}
});
@@ -2879,13 +2944,21 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
case "rate_limit_event":
yield* handleSdkTelemetryMessage(context, message);
return;
default:
// Composer prompt suggestions have no T3 surface; consumed deliberately.
case "prompt_suggestion":
return;
default: {
// Exhaustiveness guard (see handleSystemMessage): new SDK top-level
// message types fail typecheck here instead of warning at runtime.
message satisfies never;
const unknownMessage = message as never as { type: string };
yield* emitRuntimeWarning(
context,
describeUnknownSdkMessage(`Claude SDK message '${message.type}'`, message),
describeUnknownSdkMessage(`Claude SDK message '${unknownMessage.type}'`, message),
message,
);
return;
}
}
});
@@ -76,8 +76,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -162,8 +162,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
}),
],
@@ -214,6 +214,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -243,6 +244,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
// Sonnet is 200k-default in Claude Code (1M is opt-in there too).
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
@@ -369,8 +371,22 @@ export function isClaudeUltracodeEffort(effort: string | null | undefined): bool
return effort === "ultracode";
}
export function resolveClaudeContextWindow(
modelSelection: ModelSelection | undefined,
): string | undefined {
const caps = getClaudeModelCapabilities(modelSelection?.model);
const raw = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
const descriptors = getProviderOptionDescriptors({
caps,
...(raw ? { selections: [{ id: "contextWindow", value: raw }] } : {}),
});
const descriptor = descriptors.find((candidate) => candidate.id === "contextWindow");
const value = getProviderOptionCurrentValue(descriptor);
return typeof value === "string" ? value : undefined;
}
export function resolveClaudeApiModelId(modelSelection: ModelSelection): string {
switch (getModelSelectionStringOptionValue(modelSelection, "contextWindow")) {
switch (resolveClaudeContextWindow(modelSelection)) {
case "1m":
return `${modelSelection.model}[1m]`;
default:
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
import { applyPreferredCodexDefaultModel, mapCodexModelCapabilities } from "./CodexProvider.ts";
it("maps current Codex model capability fields", () => {
const capabilities = mapCodexModelCapabilities({
@@ -102,3 +102,45 @@ it("uses standard routing when the catalog has no default service tier", () => {
},
]);
});
it("marks the most preferred available model as default", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(
models.map((model) => ({ slug: model.slug, isDefault: model.isDefault })),
[
{ slug: "gpt-5.6-terra", isDefault: true },
{ slug: "gpt-5.4", isDefault: undefined },
],
);
});
it("prefers sol over terra when both are available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-terra", name: "GPT-5.6-Terra", isCustom: false, capabilities: null },
{ slug: "gpt-5.6-sol", name: "GPT-5.6-Sol", isCustom: false, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.6-sol");
});
it("keeps Codex's own default when no preferred model is available", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.5", name: "GPT-5.5", isCustom: false, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
it("ignores custom models that shadow a preferred slug", () => {
const models = applyPreferredCodexDefaultModel([
{ slug: "gpt-5.6-sol", name: "gpt-5.6-sol", isCustom: true, capabilities: null },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, isDefault: true, capabilities: null },
]);
assert.deepStrictEqual(models.find((model) => model.isDefault)?.slug, "gpt-5.4");
});
@@ -22,7 +22,7 @@ import type {
ServerProviderModel,
ServerProviderSkill,
} from "@t3tools/contracts";
import { ServerSettingsError } from "@t3tools/contracts";
import { PREFERRED_DEFAULT_CODEX_MODELS, ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { resolveSpawnCommand } from "@t3tools/shared/shell";
@@ -189,10 +189,36 @@ function parseCodexModelListResponse(
slug: model.model,
name: toDisplayName(model),
isCustom: false,
...(model.isDefault ? { isDefault: true } : {}),
capabilities: mapCodexModelCapabilities(model),
}));
}
/**
* Prefer our own default-model ranking when one of the preferred slugs is in
* the live catalog; otherwise keep whatever Codex itself flagged as default.
*/
export function applyPreferredCodexDefaultModel(
models: ReadonlyArray<ServerProviderModel>,
): ReadonlyArray<ServerProviderModel> {
const preferredSlug = PREFERRED_DEFAULT_CODEX_MODELS.find((slug) =>
models.some((model) => model.slug === slug && !model.isCustom),
);
if (!preferredSlug) {
return models;
}
return models.map((model) => {
if (model.slug === preferredSlug) {
return model.isDefault ? model : { ...model, isDefault: true };
}
if (!model.isDefault) {
return model;
}
const { isDefault: _isDefault, ...rest } = model;
return rest;
});
}
function appendCustomCodexModels(
models: ReadonlyArray<ServerProviderModel>,
customModels: ReadonlyArray<string>,
@@ -376,7 +402,9 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
return {
account: accountResponse,
version,
models: appendCustomCodexModels(models, input.customModels ?? []),
models: applyPreferredCodexDefaultModel(
appendCustomCodexModels(models, input.customModels ?? []),
),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
});
+1
View File
@@ -378,6 +378,7 @@ const buildAppUnderTest = (options?: {
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: defaultDesktopBootstrapToken,
devAuthKey: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
tailscaleServeEnabled: false,
+2 -19
View File
@@ -1,6 +1,7 @@
import * as NodeOS from "node:os";
import { QrCode } from "@t3tools/shared/qrCode";
import { formatHostForUrl, isLoopbackHost, isWildcardHost } from "@t3tools/shared/networkHost";
import * as Effect from "effect/Effect";
import { HttpServer } from "effect/unstable/http";
@@ -15,25 +16,7 @@ export interface HeadlessServeAccessInfo {
type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
export const isLoopbackHost = (host: string | undefined): boolean => {
if (!host || host.length === 0) {
return true;
}
return (
host === "localhost" ||
host === "127.0.0.1" ||
host === "::1" ||
host === "[::1]" ||
host.startsWith("127.")
);
};
export const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
export { formatHostForUrl, isLoopbackHost, isWildcardHost };
const normalizeHost = (host: string): string =>
host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
@@ -596,6 +596,26 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
}),
);
it.effect("marks the origin default ref as default when no local copy exists", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
const { initialBranch } = yield* initRepoWithCommit(cwd);
yield* git(remote, ["init", "--bare"]);
yield* git(cwd, ["remote", "add", "origin", remote]);
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
yield* git(cwd, ["remote", "set-head", "origin", initialBranch]);
yield* git(cwd, ["checkout", "-b", "feature/only-local"]);
yield* git(cwd, ["branch", "-D", initialBranch]);
const driver = yield* GitVcsDriver.GitVcsDriver;
const refs = yield* driver.listRefs({ cwd });
const remoteDefault = refs.refs.find((ref) => ref.name === `origin/${initialBranch}`);
assert.equal(remoteDefault?.isRemote, true);
assert.equal(remoteDefault?.isDefault, true);
}),
);
it.effect("creates, checks out, renames, and lists refs", () =>
Effect.gen(function* () {
const cwd = yield* makeTmpDir();
+14 -2
View File
@@ -2217,7 +2217,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
name: refName.name,
current: false,
isRemote: true,
isDefault: false,
// origin/HEAD's target is the repo default even when no local
// copy of the default branch exists.
isDefault:
defaultBranch !== null &&
parsedRemoteRef?.remoteName === "origin" &&
parsedRemoteRef.branchName === defaultBranch,
worktreePath: null,
};
if (parsedRemoteRef) {
@@ -2232,9 +2237,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
})
: [];
const allBranches = input.includeMatchingRemoteRefs
const combinedBranches = input.includeMatchingRemoteRefs
? [...localBranches, ...remoteBranches]
: dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]);
// Keep current/default refs on the first page even when the default
// only exists as origin/<default> (remote refs sort after all locals).
const allBranches = combinedBranches.toSorted((a, b) => {
const aPriority = a.current ? 0 : a.isDefault ? 1 : 2;
const bPriority = b.current ? 0 : b.isDefault ? 1 : 2;
return aPriority - bPriority;
});
const branchesForKind =
input.refKind === "local"
? allBranches.filter((ref) => !ref.isRemote)
@@ -3,7 +3,7 @@ import type {
EnvironmentId,
PreviewUrlResolution,
} from "@t3tools/contracts";
import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { isPreviewLocalHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { readPreparedConnection } from "~/state/session";
@@ -101,7 +101,7 @@ export function resolveBrowserNavigationTarget(
// Preserve the existing direct-navigation behavior so the preview host
// reports malformed URL errors through its normal navigation path.
}
if (parsed && isLoopbackHost(parsed.hostname)) {
if (parsed && isPreviewLocalHost(parsed.hostname)) {
const environmentUrl = readEnvironmentUrl(environmentId);
if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) {
return resolveEnvironmentPortTarget(
@@ -12,6 +12,7 @@ import {
resolveBranchToolbarValue,
resolveLockedWorkspaceLabel,
shouldIncludeBranchPickerItem,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.make("environment-local");
@@ -119,6 +120,44 @@ describe("resolveEnvironmentOptionLabel", () => {
});
});
describe("shouldShowEnvironmentIndicator", () => {
it("shows the indicator whenever multiple environments are pickable", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: true,
}),
).toBe(true);
});
it("shows a sole remote environment so the user knows where the project runs", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: false },
canPickEnvironment: false,
}),
).toBe(true);
});
it("hides a sole primary (this-device) environment", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: { isPrimary: true },
canPickEnvironment: false,
}),
).toBe(false);
});
it("hides the indicator when the active environment is unknown", () => {
expect(
shouldShowEnvironmentIndicator({
activeEnvironment: null,
canPickEnvironment: false,
}),
).toBe(false);
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
@@ -42,6 +42,17 @@ export function resolveEnvironmentOptionLabel(input: {
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
// A remote (non-primary) environment is always surfaced, even when it is the
// only environment available: with a single connected machine there is nothing
// to pick, but the user still needs to see where the project runs.
export function shouldShowEnvironmentIndicator(input: {
activeEnvironment: Pick<EnvironmentOption, "isPrimary"> | null;
canPickEnvironment: boolean;
}): boolean {
if (input.canPickEnvironment) return true;
return input.activeEnvironment !== null && !input.activeEnvironment.isPrimary;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
+14 -4
View File
@@ -20,6 +20,7 @@ import {
resolveEnvModeLabel,
resolveEffectiveEnvMode,
resolveLockedWorkspaceLabel,
shouldShowEnvironmentIndicator,
} from "./BranchToolbar.logic";
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
import { BranchToolbarEnvironmentSelector } from "./BranchToolbarEnvironmentSelector";
@@ -60,6 +61,7 @@ interface MobileRunContextSelectorProps {
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[] | undefined;
showEnvironmentPicker: boolean;
showEnvironmentIndicator: boolean;
onEnvironmentChange: ((environmentId: EnvironmentId) => void) | undefined;
effectiveEnvMode: EnvMode;
activeWorktreePath: string | null;
@@ -72,6 +74,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
environmentId,
availableEnvironments,
showEnvironmentPicker,
showEnvironmentIndicator,
onEnvironmentChange,
effectiveEnvMode,
activeWorktreePath,
@@ -94,7 +97,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
: resolveCurrentWorkspaceLabel(activeWorktreePath);
const isLocked = envLocked || envModeLocked;
const EnvironmentIcon = activeEnvironment?.isPrimary ? MonitorIcon : CloudIcon;
const icon = showEnvironmentPicker ? (
const icon = showEnvironmentIndicator ? (
// Button's base styles apply `-mx-0.5` to descendant SVGs, which eats 4px
// out of whatever gap we set. mx-0! cancels that so gap-0.5 reads as 2px.
<span className="inline-flex shrink-0 items-center gap-0.5">
@@ -108,7 +111,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
<>
{icon}
<span className="min-w-0 truncate">
{showEnvironmentPicker ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
{showEnvironmentIndicator ? (activeEnvironment?.label ?? "Run on") : workspaceLabel}
</span>
</>
);
@@ -234,6 +237,12 @@ export const BranchToolbar = memo(function BranchToolbar({
const showEnvironmentPicker = Boolean(
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange,
);
const activeEnvironmentOption =
availableEnvironments?.find((env) => env.environmentId === environmentId) ?? null;
const showEnvironmentIndicator = shouldShowEnvironmentIndicator({
activeEnvironment: activeEnvironmentOption,
canPickEnvironment: showEnvironmentPicker,
});
const isMobile = useIsMobile();
if (!hasActiveThread || !activeProject) return null;
@@ -247,6 +256,7 @@ export const BranchToolbar = memo(function BranchToolbar({
environmentId={environmentId}
availableEnvironments={availableEnvironments}
showEnvironmentPicker={showEnvironmentPicker}
showEnvironmentIndicator={showEnvironmentIndicator}
onEnvironmentChange={onEnvironmentChange}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
@@ -254,13 +264,13 @@ export const BranchToolbar = memo(function BranchToolbar({
/>
) : (
<div className="flex min-w-0 shrink-0 items-center gap-1">
{showEnvironmentPicker && availableEnvironments && onEnvironmentChange && (
{showEnvironmentIndicator && availableEnvironments && (
<>
<BranchToolbarEnvironmentSelector
envLocked={envLocked}
environmentId={environmentId}
availableEnvironments={availableEnvironments}
onEnvironmentChange={onEnvironmentChange}
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
</>
@@ -422,17 +422,32 @@ export function BranchToolbarBranchSelector({
});
};
// Default the worktree base to the repo default branch (origin/HEAD), only
// falling back to the checked-out branch when no default is known.
const defaultBranchName = useMemo(
() => refs.find((refName) => refName.isDefault)?.name ?? null,
[refs],
);
const worktreeBaseBranchCandidate = isInitialBranchesLoadPending
? null
: (defaultBranchName ?? currentGitBranch);
useEffect(() => {
if (
effectiveEnvMode !== "worktree" ||
activeWorktreePath ||
activeThreadBranch ||
!currentGitBranch
!worktreeBaseBranchCandidate
) {
return;
}
setThreadBranch(currentGitBranch, null);
}, [activeThreadBranch, activeWorktreePath, currentGitBranch, effectiveEnvMode, setThreadBranch]);
setThreadBranch(worktreeBaseBranchCandidate, null);
}, [
activeThreadBranch,
activeWorktreePath,
effectiveEnvMode,
setThreadBranch,
worktreeBaseBranchCandidate,
]);
// ---------------------------------------------------------------------------
// Combobox / list plumbing
@@ -17,7 +17,9 @@ interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
environmentId: EnvironmentId;
availableEnvironments: readonly EnvironmentOption[];
onEnvironmentChange: (environmentId: EnvironmentId) => void;
// Absent when there is only one environment to show: the indicator still
// renders (as a static label) so remote projects are always identifiable.
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvironmentSelector({
@@ -39,7 +41,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
[availableEnvironments],
);
if (envLocked) {
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeEnvironment?.isPrimary ? (
+8 -12
View File
@@ -1159,6 +1159,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
environmentUnavailable !== null ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
@@ -1697,7 +1698,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const shouldBlurMobileComposerOnSubmit = useCallback(() => {
if (!isMobileViewport) return false;
if (isSendBusy || isConnecting || phase === "running") return false;
if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") {
return false;
}
if (activePendingProgress) {
return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers);
}
@@ -1706,6 +1709,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activePendingProgress,
activePendingResolvedAnswers,
composerSendState.hasSendableContent,
environmentUnavailable,
isConnecting,
isMobileViewport,
isSendBusy,
@@ -1892,8 +1896,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
projectSelectionRequired
) {
return false;
}
@@ -2101,8 +2104,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
isComposerModelPickerOpen,
readComposerSnapshot,
@@ -2144,7 +2145,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
className={cn(
"chat-composer-glass rounded-[20px] border transition-[background-color] duration-200 has-focus-visible:border-ring/45",
isDragOverComposer ? "border-primary/70 bg-accent/45" : "border-border",
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2502,12 +2503,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
}
disabled={
isConnecting ||
isComposerApprovalState ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
}
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
/>
{showMobilePendingAnswerActions ? (
<div
@@ -1,5 +1,5 @@
import type { DiscoveredLocalServer } from "@t3tools/contracts";
import { isLoopbackHost } from "@t3tools/shared/preview";
import { isPreviewLocalHost } from "@t3tools/shared/preview";
import { useMemo } from "react";
import type { EnvironmentId } from "@t3tools/contracts";
@@ -124,7 +124,7 @@ function parseLocalUrl(raw: string): { host: string; port: number; url: string }
try {
const parsed = new URL(raw);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
if (!isLoopbackHost(parsed.hostname)) return null;
if (!isPreviewLocalHost(parsed.hostname)) return null;
const port = parsed.port
? Number.parseInt(parsed.port, 10)
: parsed.protocol === "http:"
+4
View File
@@ -75,6 +75,7 @@ export interface AppModelOption {
shortName?: string;
subProvider?: string;
isCustom: boolean;
isDefault?: boolean;
}
function toAppModelOption(model: ServerProvider["models"][number]): AppModelOption {
@@ -85,6 +86,7 @@ function toAppModelOption(model: ServerProvider["models"][number]): AppModelOpti
};
if (model.shortName) option.shortName = model.shortName;
if (model.subProvider) option.subProvider = model.subProvider;
if (model.isDefault) option.isDefault = true;
return option;
}
@@ -247,7 +249,9 @@ export function resolveAppModelSelectionForInstance(
const options = getAppModelOptionsForInstance(settings, entry);
return (
resolveSelectableModel(entry.driverKind, selectedModel, options) ??
options.find((option) => option.isDefault)?.slug ??
options[0]?.slug ??
entry.models.find((model) => model.isDefault)?.slug ??
entry.models[0]?.slug ??
null
);
+1
View File
@@ -92,6 +92,7 @@ export function getDefaultServerModel(
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => model.isDefault && !model.isCustom)?.slug ??
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider] ??
@@ -1,5 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import {
DEFAULT_MODEL,
EnvironmentId,
ProjectId,
CommandId,
@@ -139,7 +140,7 @@ describe("add project shared logic", () => {
createWorkspaceRootIfMissing: true,
defaultModelSelection: {
instanceId: "codex",
model: "gpt-5.4",
model: DEFAULT_MODEL,
},
});
});
+12 -2
View File
@@ -133,8 +133,18 @@ const CURSOR_DRIVER_KIND = ProviderDriverKind.make("cursor");
const GROK_DRIVER_KIND = ProviderDriverKind.make("grok");
const OPENCODE_DRIVER_KIND = ProviderDriverKind.make("opencode");
export const DEFAULT_MODEL = "gpt-5.4";
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL = "gpt-5.6-sol";
/**
* Codex default-model preference, most preferred first. The provider snapshot
* marks the first of these present in the live `model/list` response as
* default; when none are available, Codex's own `isDefault` flag wins.
*/
export const PREFERRED_DEFAULT_CODEX_MODELS: ReadonlyArray<string> = [
"gpt-5.6-sol",
"gpt-5.6-terra",
];
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.6-luna";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
+1
View File
@@ -64,6 +64,7 @@ export const ServerProviderModel = Schema.Struct({
shortName: Schema.optional(TrimmedNonEmptyString),
subProvider: Schema.optional(TrimmedNonEmptyString),
isCustom: Schema.Boolean,
isDefault: Schema.optional(Schema.Boolean),
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
+4 -4
View File
@@ -88,14 +88,14 @@ describe("ServerSettings.providerInstances (slice-2 invariant)", () => {
});
describe("ServerSettings worktree defaults", () => {
it("defaults start-from-origin off for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(false);
it("defaults start-from-origin on for legacy configs", () => {
expect(decodeServerSettings({}).newWorktreesStartFromOrigin).toBe(true);
});
it("accepts start-from-origin updates", () => {
expect(
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: true }).newWorktreesStartFromOrigin,
).toBe(true);
decodeServerSettingsPatch({ newWorktreesStartFromOrigin: false }).newWorktreesStartFromOrigin,
).toBe(false);
});
});
+1 -1
View File
@@ -382,7 +382,7 @@ export const ServerSettings = Schema.Struct({
Schema.withDecodingDefault(Effect.succeed("local" as const satisfies ThreadEnvMode)),
),
newWorktreesStartFromOrigin: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
Schema.withDecodingDefault(Effect.succeed(true)),
),
addProjectBaseDirectory: TrimmedString.pipe(Schema.withDecodingDefault(Effect.succeed(""))),
textGenerationModelSelection: ModelSelection.pipe(
+4
View File
@@ -51,6 +51,10 @@
"types": "./src/Net.ts",
"import": "./src/Net.ts"
},
"./networkHost": {
"types": "./src/networkHost.ts",
"import": "./src/networkHost.ts"
},
"./DrainableWorker": {
"types": "./src/DrainableWorker.ts",
"import": "./src/DrainableWorker.ts"
+31
View File
@@ -0,0 +1,31 @@
import { describe, expect, it } from "vite-plus/test";
import { isLoopbackAddress, isLoopbackHost } from "./networkHost.ts";
describe("isLoopbackAddress", () => {
it.each(["127.0.0.1", "127.0.0.2", "::1", "[::1]"])(
"accepts the loopback address literal %s",
(host) => {
expect(isLoopbackAddress(host)).toBe(true);
},
);
it.each([
undefined,
"",
"localhost",
"127.attacker.example",
"127.0.0.256",
"127.00.0.1",
"0.0.0.0",
])("rejects the unsafe or non-literal host %s", (host) => {
expect(isLoopbackAddress(host)).toBe(false);
});
});
describe("isLoopbackHost", () => {
it("retains localhost for callers that model effective server binds", () => {
expect(isLoopbackHost("localhost")).toBe(true);
expect(isLoopbackHost(undefined)).toBe(false);
});
});
+22
View File
@@ -0,0 +1,22 @@
export const isLoopbackAddress = (host: string | undefined): boolean => {
if (!host) return false;
if (host === "::1" || host === "[::1]") return true;
const octets = host.split(".");
return (
octets.length === 4 &&
octets[0] === "127" &&
octets.every(
(octet) => /^(?:0|[1-9]\d{0,2})$/u.test(octet) && Number.parseInt(octet, 10) <= 255,
)
);
};
export const isLoopbackHost = (host: string | undefined): boolean =>
host === "localhost" || isLoopbackAddress(host);
export const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
+4 -4
View File
@@ -1,8 +1,8 @@
import { describe, expect, it } from "vite-plus/test";
import {
isLoopbackHost,
isPreviewableUrl,
isPreviewLocalHost,
newPreviewTabId,
normalizePreviewUrl,
PreviewUrlNormalizationError,
@@ -17,13 +17,13 @@ describe("newPreviewTabId", () => {
});
});
describe("isLoopbackHost", () => {
describe("isPreviewLocalHost", () => {
it.each(["localhost", "127.0.0.1", "0.0.0.0", "::1", "[::1]"])("%s is loopback", (host) => {
expect(isLoopbackHost(host)).toBe(true);
expect(isPreviewLocalHost(host)).toBe(true);
});
it.each(["example.com", "192.168.1.10", "10.0.0.1", ""])("%s is not loopback", (host) => {
expect(isLoopbackHost(host)).toBe(false);
expect(isPreviewLocalHost(host)).toBe(false);
});
});
+12 -7
View File
@@ -18,20 +18,25 @@ export function newPreviewTabId(): string {
return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
}
const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
const PREVIEW_LOCAL_HOSTS: ReadonlySet<string> = new Set([
"localhost",
"127.0.0.1",
"0.0.0.0",
"::1",
]);
/** Internal — used by `lsof` parsing where the host string is wire-formatted. */
export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
...LOOPBACK_HOSTS,
...PREVIEW_LOCAL_HOSTS,
"*",
"[::]",
"[::1]",
]);
const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
const PREVIEW_LOCAL_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
export function isLoopbackHost(host: string): boolean {
if (LOOPBACK_HOSTS.has(host)) return true;
export function isPreviewLocalHost(host: string): boolean {
if (PREVIEW_LOCAL_HOSTS.has(host)) return true;
if (host === "[::1]") return true;
return false;
}
@@ -41,7 +46,7 @@ export function isPreviewableUrl(rawUrl: string): boolean {
try {
const parsed = new URL(rawUrl);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
return isLoopbackHost(parsed.hostname);
return isPreviewLocalHost(parsed.hostname);
} catch {
return false;
}
@@ -83,7 +88,7 @@ export function normalizePreviewUrl(rawUrl: string): string {
if (trimmed.length === 0) {
throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
}
const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
const useHttp = PREVIEW_LOCAL_PREFIX_PATTERN.test(trimmed);
const candidate = trimmed.includes("://")
? trimmed
: `${useHttp ? "http" : "https"}://${trimmed}`;
+72
View File
@@ -13,7 +13,9 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkPortAvailabilityOnHosts,
createDevAccessUrls,
createDevRunnerEnv,
deriveDevAuthKey,
findFirstAvailableOffset,
getDevRunnerModeArgs,
resolveModePortOffsets,
@@ -125,6 +127,42 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
);
});
describe("development authentication", () => {
it.effect("derives a stable opaque key from the canonical worktree root", () =>
Effect.sync(() => {
const first = deriveDevAuthKey("/tmp/t3-worktree-a");
const repeated = deriveDevAuthKey("/tmp/t3-worktree-a");
const other = deriveDevAuthKey("/tmp/t3-worktree-b");
assert.match(first, /^[a-f0-9]{64}$/);
assert.equal(first, repeated);
assert.notEqual(first, other);
assert.notInclude(first, "t3-worktree-a");
}),
);
it.effect("prints reusable web and platform-specific mobile pairing urls", () =>
Effect.sync(() => {
const urls = createDevAccessUrls({
mode: "dev",
serverPort: 13_773,
webUrl: "http://localhost:5733",
credential: "development-key",
});
assert.equal(urls.web, "http://localhost:5733/pair#token=development-key");
assert.include(
decodeURIComponent(urls.ios),
"pairingUrl=http://127.0.0.1:13773/pair#token=development-key",
);
assert.include(
decodeURIComponent(urls.android),
"pairingUrl=http://10.0.2.2:13773/pair#token=development-key",
);
}),
);
});
describe("createDevRunnerEnv", () => {
it.effect("leaves the shared home implicit and disables browser auto-open", () =>
Effect.gen(function* () {
@@ -144,6 +182,36 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_HOME, undefined);
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_HOST, "127.0.0.1");
assert.equal(env.T3CODE_DEV_AUTH, "1");
assert.match(env.T3CODE_DEV_AUTH_KEY ?? "", /^[a-f0-9]{64}$/);
}),
);
it.effect("only provisions reusable auth on the Android-compatible loopback bind", () =>
Effect.gen(function* () {
for (const host of ["127.0.0.2", "::1", "127.attacker.example"]) {
const env = yield* createDevRunnerEnv({
mode: "dev:server",
baseEnv: {
T3CODE_DEV_AUTH: "1",
T3CODE_DEV_AUTH_KEY: "inherited-key",
},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_HOST, host);
assert.equal(env.T3CODE_DEV_AUTH, undefined);
assert.equal(env.T3CODE_DEV_AUTH_KEY, undefined);
}
}),
);
@@ -213,6 +281,8 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_LOG_WS_EVENTS, "1");
assert.equal(env.T3CODE_HOST, "0.0.0.0");
assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:7331/");
assert.equal(env.T3CODE_DEV_AUTH, undefined);
assert.equal(env.T3CODE_DEV_AUTH_KEY, undefined);
}),
);
@@ -316,6 +386,8 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_NO_BROWSER, undefined);
assert.equal(env.T3CODE_HOST, undefined);
assert.equal(env.VITE_WS_URL, "ws://127.0.0.1:4222");
assert.equal(env.T3CODE_DEV_AUTH, undefined);
assert.equal(env.T3CODE_DEV_AUTH_KEY, undefined);
}),
);
+82 -7
View File
@@ -1,6 +1,8 @@
#!/usr/bin/env node
import * as NodeCrypto from "node:crypto";
import * as NodeOS from "node:os";
import * as NodeURL from "node:url";
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -26,7 +28,7 @@ const BASE_SERVER_PORT = 13773;
const BASE_WEB_PORT = 5733;
const MAX_HASH_OFFSET = 3000;
const MAX_PORT = 65535;
const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
const DEV_LOOPBACK_HOST = "127.0.0.1";
const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "0.0.0.0", "::1", "::"] as const;
export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) =>
@@ -56,6 +58,48 @@ export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
return MODE_ARGS[mode];
}
export function deriveDevAuthKey(worktreeRoot: string): string {
// This is a stable public identity, not a secret. Dev auth deliberately assumes a
// single-user development machine and is rejected unless the server binds to loopback.
return NodeCrypto.createHash("sha256").update(`t3-dev:${worktreeRoot}`).digest("hex");
}
export function createDevAccessUrls(input: {
readonly mode: DevMode;
readonly serverPort: number;
readonly webUrl: string;
readonly credential: string;
}): {
readonly web: string | undefined;
readonly ios: string;
readonly android: string;
} {
const pairingUrl = (host: string) => {
const url = new URL(`http://${host}:${input.serverPort}/pair`);
url.hash = new URLSearchParams([["token", input.credential]]).toString();
return url.toString();
};
const mobileUrl = (pairing: string) => {
const url = new URL("t3code-dev://connections/new");
url.searchParams.set("pairingUrl", pairing);
return url.toString();
};
const web =
input.mode === "dev"
? (() => {
const url = new URL("/pair", input.webUrl);
url.hash = new URLSearchParams([["token", input.credential]]).toString();
return url.toString();
})()
: undefined;
return {
web,
ios: mobileUrl(pairingUrl("127.0.0.1")),
android: mobileUrl(pairingUrl("10.0.2.2")),
};
}
export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
"DevRunnerConfigurationError",
{
@@ -243,18 +287,21 @@ export function createDevRunnerEnv({
devUrl,
}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
return Effect.gen(function* () {
const path = yield* Path.Path;
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
const worktreeRoot = path.resolve(NodeURL.fileURLToPath(new URL("..", import.meta.url)));
const isDesktopMode = mode === "dev:desktop";
const serverHost = mode === "dev" || mode === "dev:server" ? (host ?? DEV_LOOPBACK_HOST) : host;
const output: NodeJS.ProcessEnv = {
...baseEnv,
PORT: String(webPort),
VITE_DEV_SERVER_URL:
devUrl?.toString() ??
`http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
`http://${isDesktopMode ? DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
};
if (configuredBaseDir !== undefined) {
@@ -269,15 +316,25 @@ export function createDevRunnerEnv({
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_HTTP_URL = `http://${DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_WS_URL = `ws://${DEV_LOOPBACK_HOST}:${serverPort}`;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;
delete output.T3CODE_HOST;
}
if (!isDesktopMode && host !== undefined) {
output.T3CODE_HOST = host;
const devAuthEnabled =
(mode === "dev" || mode === "dev:server") && serverHost === DEV_LOOPBACK_HOST;
if (devAuthEnabled) {
output.T3CODE_DEV_AUTH = "1";
output.T3CODE_DEV_AUTH_KEY = deriveDevAuthKey(worktreeRoot);
} else {
delete output.T3CODE_DEV_AUTH;
delete output.T3CODE_DEV_AUTH_KEY;
}
if (!isDesktopMode && serverHost !== undefined) {
output.T3CODE_HOST = serverHost;
}
if (!isDesktopMode) {
@@ -307,7 +364,7 @@ export function createDevRunnerEnv({
}
if (isDesktopMode) {
output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
output.HOST = DEV_LOOPBACK_HOST;
delete output.T3CODE_DESKTOP_WS_URL;
}
@@ -529,6 +586,24 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
);
if (env.T3CODE_DEV_AUTH === "1" && env.T3CODE_DEV_AUTH_KEY) {
const urls = createDevAccessUrls({
mode: input.mode,
serverPort: Number(env.T3CODE_PORT),
webUrl: env.VITE_DEV_SERVER_URL!,
credential: env.T3CODE_DEV_AUTH_KEY,
});
if (urls.web) {
yield* Effect.logInfo(`[dev-runner] reusable web pairing URL: ${urls.web}`);
}
yield* Effect.logInfo(`[dev-runner] reusable iOS pairing URL: ${urls.ios}`);
yield* Effect.logInfo(`[dev-runner] reusable Android pairing URL: ${urls.android}`);
} else if (input.mode === "dev" || input.mode === "dev:server") {
yield* Effect.logInfo(
`[dev-runner] reusable dev authentication disabled for host ${input.host ?? "unknown"}; use --host ${DEV_LOOPBACK_HOST} or a regular pairing credential`,
);
}
if (input.dryRun) {
return;
}