Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge a47c24e6f8 refactor(server): schema-decode Windows process diagnostics
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:09:04 +00:00
Cursor AgentandJulius Marminge 3168972c0a test(server): assert normalized filesystem errors
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:07:48 +00:00
Cursor AgentandJulius Marminge d8e264ee18 refactor(server): use Effect filesystem for workspace reads
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 16:07:28 +00:00
53e3c98a55 feat(web): themed sidebar header art for nightly and dev builds (#4130)
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-19 12:35:58 +02:00
Julius Marmingeandcodex 4f11740510 Add isolated app testing workflow (#4121)
Co-authored-by: codex <[email protected]>
2026-07-19 11:57:58 +02:00
Taras 1735e27d9e Add terminal selection copy action (#2904) 2026-07-19 00:05:09 +02:00
Julius Marminge ebe8afb1df Refresh splash screen and favicon branding (#4120) 2026-07-18 15:44:06 +02:00
Utkarsh PatilandJulius Marminge bf76535fe4 fix(desktop): Validate WSL node version against engine range after probe success (#3621)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 11:54:13 +00:00
5c66110e26 [fix/feat:ui] Make selected menu checks blue (#3234)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-18 13:50:33 +02:00
Maxwell Young da3c2030f7 [codex] canonicalize client timestamps (#4112) 2026-07-18 13:40:34 +02:00
Noah ZepnerandJulius Marminge 0506508e9b Allow failed remote environments to be removed (#4084)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:31:10 +02:00
Guilherme VieiraandJulius Marminge b859a575d1 fix(web): handle macOS Home and End in composer (#2508)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:23:57 +02:00
ssandJulius Marminge e63403fe92 [fix/feat:ui] Preserve open-in editor brand colors (#3225)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:22:37 +02:00
ssandJulius Marminge c0e161af06 [fix/feat:ui] Show default option badge (#3232)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:21:50 +02:00
d0b9f8d40d [codex] Route OpenCode missing-session errors through Effect (#3608)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:52 +02:00
Jake LeventhalandJulius Marminge d8b12ae801 Fix sending messages during active turns (#3919)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:19:14 +02:00
Jake LeventhalandJulius Marminge 31caa5652b Fix reopening existing Diff tab (#3973)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:18:18 +02:00
Aditya Mer e350c0a07b Add Grok to marketing site provider list (#3484) 2026-07-18 11:18:17 +00:00
Jake LeventhalandJulius Marminge 38e0bb07bb Default diffs to working changes (#3974)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:17:30 +02:00
Chris Michael Guzman 765e1b5fc0 perf(client): defer active thread cache writes (#4006) 2026-07-18 13:16:38 +02:00
AlexandJulius Marminge 03e20c875c fix(mobile): restore iOS home screen branding (#4025)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:14:59 +02:00
Julius Marmingeandcodex 2318e00270 fix(web): avoid duplicate mention text on paste
Co-authored-by: codex <[email protected]>
2026-07-18 13:05:45 +02:00
Yordis PrietoandJulius Marminge 4cfec8c128 feat: file explorer mention actions and zoom-aware context menus (#4054)
Signed-off-by: Yordis Prieto <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-18 13:05:26 +02:00
1bd2fa25e2 feat: draft hero landing on the index route (#4055)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Signed-off-by: Yordis Prieto <[email protected]>
2026-07-18 12:45:45 +02:00
5ca32661b7 fix(web): increase contrast of question option descriptions (#3867)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:53:50 +02:00
Julius Marminge 8b33799523 Preserve T3 Code identity in macOS development launcher (#4102) 2026-07-17 23:39:29 +02:00
Julius Marminge 24f9c2a08e Share MCP OAuth locks across Codex shadow homes (#4104) 2026-07-17 23:26:53 +02:00
31ca9e5531 fix(server): skip undecodable provider runtime rows when listing sessions (#3951)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 21:26:22 +00:00
73bf127d71 [codex] Fix provider update checks restore defaults (#3531)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:25:21 +02:00
43e2aeab38 [codex] fix: tolerate invalid latest user message timestamps (#3521)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:52 +02:00
b655a9f183 [codex] fix: guard invalid web timestamps (#3515)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:24:10 +02:00
Matt Van HornandJulius Marminge 4e3f2f04d5 fix(server): thread cwd through Claude capability probe (#2048) (#2124)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:22:19 +02:00
1047dac0c5 fix(terminal): strip AppImage runtime env from spawned terminals (#3108)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:21:19 +02:00
JamesandJulius Marminge 143b9c9280 fix(ux): spamming cmd + , no longer stack opening settings (#2757)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:20:28 +02:00
cf58cadd02 feat(server): include runtime model and effort in Codex developer instructions (#3948)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 23:15:53 +02:00
6a17629670 [codex] fix mobile composer Enter behavior (#3930)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-07-17 23:14:45 +02:00
7b8d12618b fix(web): inset Windows desktop scrollbars from resize edge (#4097)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:52:42 +00:00
Maxwell YoungandJulius Marminge bcd640bf4d [codex] prevent ACP assistant ID collisions after restarts (#3932)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:51:16 +02:00
b49a2e677c Remove unused code parameter from describePreviewError (#3970)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 19:50:33 +00:00
ed81c156da fix(server): image upload crashed dispatchCommand with a stack overflow (#3952)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:52 +02:00
Kriday DaveandJulius Marminge 7dc75127c2 Fix duplicate keybinding rule when replacing with an existing rule (#3969)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 21:47:35 +02:00
Fazal Kadivar e057e2e985 fix: prevent initial right-click from selecting a context menu item (#3877) 2026-07-17 21:42:13 +02:00
Olivier Melcher a7f6d97b94 Allow preview panel to grow on wide displays (#4044) 2026-07-17 18:40:24 +00:00
Kriday DaveandJulius Marminge f9a4f59930 Fix documented task-runner commands (bun run -> vp) (#3965)
Co-authored-by: Julius Marminge <[email protected]>
2026-07-17 20:35:24 +02:00
BunnyGamezsc 7f1cb61031 fix(cursor): default binary path to cursor-agent (avoid path conflict w/ grok) (#4094) 2026-07-17 18:01:02 +00:00
Kriday Dave c49d424e3a Normalize protocol-relative remote host input as https (#3971) 2026-07-17 18:59:42 +02:00
Manuel De Ceglie 4804a9824f fix(marketing): correct Cursor icon color (#4090) 2026-07-17 18:56:59 +02:00
Manuel De Ceglie 0748134cec Update marketing GitHub star count (#4088) 2026-07-17 18:56:35 +02:00
Julius Marmingeandcodex 6e9987cf17 Refresh app icons across release variants (#4080)
Co-authored-by: codex <[email protected]>
2026-07-17 18:51:14 +02:00
196 changed files with 6058 additions and 864 deletions

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
---
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.
---
# Test T3 App
## Start an isolated web environment
1. Run commands from the repository root.
2. Choose a base directory that belongs only to the current worktree or test:
- 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.
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.
## Authenticate the browser on the first navigation
1. Wait for the server log that says authentication is required and includes a URL ending in `/pair#token=...`.
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.
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.
## Recover a consumed or expired pairing token
Create another 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 \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
## Inspect or seed SQLite state
Read [references/sqlite-fixtures.md](references/sqlite-fixtures.md) before changing the database.
- Use `node apps/server/scripts/t3-sqlite-state.ts query` for schema discovery and read-only checks.
- Stop the dev server before using `node apps/server/scripts/t3-sqlite-state.ts exec`, then restart it with the same base directory.
- Seed projection tables only for disposable UI fixtures. Use application commands and APIs when testing business behavior or projection correctness.
- Use the auth CLI, not direct `auth_*` table edits, for pairing and sessions.
The helper refuses to write to the shared `~/.t3` directory by default and creates a database backup before each mutation.
## Finish the test
Stop the dev process with its terminal interrupt. Preserve the isolated base directory when it contains useful reproduction evidence; otherwise remove only a path that was created for this test after resolving and verifying the exact target. A fresh isolated base directory is the safest reset when authentication, migrations, or fixture state becomes ambiguous.
## Troubleshoot predictably
- If the browser shows an unauthenticated pairing screen, issue a new token instead of retrying the consumed URL.
- 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.
- If ports move because another instance is running, trust the current dev-runner output rather than assuming ports `13773` and `5733`.
@@ -0,0 +1,4 @@
interface:
display_name: "T3 App Testing"
short_description: "Launch and seed isolated T3 test environments"
default_prompt: "Use $test-t3-app to launch an isolated T3 development environment and test it in the browser."
@@ -0,0 +1,58 @@
# SQLite fixtures
Load this reference only when inspecting or seeding local T3 state directly.
## Select the correct database
When `--base-dir` or `--home-dir` is explicit, runtime state lives under `<base-dir>/userdata` and the database path is `<base-dir>/userdata/state.sqlite`. The `<base-dir>/dev` state directory is only the fallback for an implicit development home, preventing an ordinary `vp run dev` from touching production state.
Start the target runtime once before seeding so all migrations have run. Use an isolated base directory. Stop the server before writes to avoid racing application state or an active projection.
## Use the helper
List tables:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"
```
Inspect current columns before writing a fixture:
```bash
node apps/server/scripts/t3-sqlite-state.ts query \
--base-dir <base-dir> \
--sql "PRAGMA table_info(projection_threads)"
```
Apply a SQL fixture from a file:
```bash
node apps/server/scripts/t3-sqlite-state.ts exec \
--base-dir <base-dir> \
--file /tmp/t3-seed.sql
```
Use one statement per invocation for both `query` and `exec`; the helper wraps writes in a transaction and prints the backup path after a successful mutation. Use a single insert with multiple value rows when a fixture needs several records.
## Seed projection data carefully
The web UI primarily reads these projection tables:
- `projection_projects`
- `projection_threads`
- `projection_thread_messages`
- `projection_thread_activities`
- `projection_thread_sessions`
- `projection_turns`
- `projection_pending_approvals`
- `projection_thread_proposed_plans`
Inspect `PRAGMA table_info(<table>)` and the current migrations under `apps/server/src/persistence/Migrations/` before constructing inserts. Keep identifiers unique, timestamps as ISO strings, JSON columns valid, and related project/thread/turn IDs consistent.
For a substantial current example, inspect `seedDatabase` in `scripts/mobile-showcase-environment.ts`. Adapt its column set to the target database instead of assuming copied SQL remains current.
Direct projection writes are appropriate for ephemeral visual states, edge-case counts, long titles, activity lists, and similar UI fixtures. They do not create a coherent orchestration event history. Do not modify `orchestration_events` unless the test specifically exercises projector internals, and do not use direct projection writes to claim backend business behavior works.
Use the app's commands or APIs for behavior tests. Use `node apps/server/src/bin.ts auth ...` for auth state rather than editing `auth_pairing_links` or `auth_sessions`.
+9 -24
View File
@@ -2,27 +2,14 @@
## Task Completion Requirements
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
- If changing native mobile code, `vp run lint:mobile` must also pass.
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
## Core Priorities
1. Performance first.
2. Reliability first.
3. Keep behavior predictable under load and during failures (session restarts, reconnects, partial streams).
If a tradeoff is required, choose correctness and robustness over short-term convenience.
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
- Keep local verification focused on the files and packages changed. Run the smallest relevant test set; do not run the full workspace test suite as a routine completion step.
- Use `vp test run <test-files>` for focused built-in Vite+ tests. Use `vp run test` only when the affected package specifically requires its `test` script.
- Backend changes must include and run focused tests for the changed behavior.
- Run targeted formatting, lint, and type checks for the affected scope when available.
- Do not run repo-wide `vp check`, `vp run typecheck`, `vp run test`, or equivalent full-suite commands locally unless the user explicitly requests them. CI is responsible for the full verification suite.
- After frontend feature development or any user-visible frontend behavior change, the primary agent must use the `test-t3-app` skill once after integrating the work. Launch one isolated environment, authenticate through the printed pairing URL, and verify the affected flow in the controlled browser.
- Subagents must not independently launch dev servers or repeat integrated browser verification unless their delegated task explicitly requires it.
- Stop dev servers, watchers, and other long-running verification processes when the focused verification is complete.
## Package Roles
@@ -35,7 +22,6 @@ Long term maintainability is a core priority. If you add new functionality, firs
## Reference Repos
- Open-source Codex repo: https://github.com/openai/codex
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
@@ -47,8 +33,7 @@ agents.
- Prefer examples and patterns from the vendored source code over generated guesses or web search results.
- Do not edit files under `.repos/` unless explicitly asked.
- Do not import from `.repos/`; application code must continue importing from normal package dependencies.
- Manage vendored subtrees with `bun run sync:repos`; use `bun run sync:repos --repo <id>` to sync one
configured repository.
- Manage vendored subtrees with `vpr sync:repos`; use `vpr sync:repos --repo <id>` to sync one configured repository.
- When updating a dependency with a configured vendored subtree, sync that subtree in the same change so
`.repos/` matches the installed dependency version.
- When writing Effect code, read `.repos/effect-smol/LLMS.md` first and inspect `.repos/effect-smol/` for
+34 -9
View File
@@ -20,7 +20,7 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 12;
const LAUNCHER_VERSION = 14;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const developmentMacIconPngPath = NodePath.join(
repoRoot,
@@ -220,11 +220,12 @@ function ensureDevelopmentIconIcns(runtimeDir) {
}
}
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
function patchMainBundleInfoPlist(appBundlePath, iconPath, executableName) {
const infoPlistPath = NodePath.join(appBundlePath, "Contents", "Info.plist");
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleName", APP_DISPLAY_NAME);
setPlistString(infoPlistPath, "CFBundleIdentifier", APP_BUNDLE_ID);
setPlistString(infoPlistPath, "CFBundleExecutable", executableName);
setPlistString(infoPlistPath, "CFBundleIconFile", "icon.icns");
setPlistJson(infoPlistPath, "CFBundleURLTypes", [
{
@@ -277,11 +278,25 @@ function readJson(path) {
}
}
export function resolveMacLauncherPaths(appBundlePath, displayName = APP_DISPLAY_NAME) {
const executableDir = NodePath.join(appBundlePath, "Contents", "MacOS");
const launcherExecutableName = `${displayName} Launcher`;
return {
launcherExecutableName,
launcherBinaryPath: NodePath.join(executableDir, launcherExecutableName),
runtimeElectronBinaryPath: NodePath.join(executableDir, "Electron"),
};
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = NodePath.resolve(NodePath.dirname(electronBinaryPath), "../..");
const runtimeDir = NodePath.join(desktopDir, ".electron-runtime");
const targetAppBundlePath = NodePath.join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = NodePath.join(targetAppBundlePath, "Contents", "MacOS", "Electron");
const developmentPaths = resolveMacLauncherPaths(targetAppBundlePath);
const runtimeElectronBinaryPath = developmentPaths.runtimeElectronBinaryPath;
const launcherBinaryPath = isDevelopment
? developmentPaths.launcherBinaryPath
: runtimeElectronBinaryPath;
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
@@ -298,7 +313,8 @@ function buildMacLauncher(electronBinaryPath) {
const currentMetadata = readJson(metadataPath);
if (
NodeFS.existsSync(targetBinaryPath) &&
NodeFS.existsSync(launcherBinaryPath) &&
(!isDevelopment || NodeFS.existsSync(runtimeElectronBinaryPath)) &&
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
@@ -306,10 +322,10 @@ function buildMacLauncher(electronBinaryPath) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
NodeFS.rmSync(targetAppBundlePath, { recursive: true, force: true });
@@ -321,15 +337,24 @@ function buildMacLauncher(electronBinaryPath) {
recursive: true,
verbatimSymlinks: true,
});
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
patchMainBundleInfoPlist(
targetAppBundlePath,
iconPath,
isDevelopment ? developmentPaths.launcherExecutableName : "Electron",
);
patchHelperBundleInfoPlists(targetAppBundlePath);
if (isDevelopment) {
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
// Keep Electron's native executable inside the branded bundle. Launching the
// node_modules copy makes macOS associate the process (and Dock label) with
// Electron.app even though this bundle's Info.plist has the T3 Code name.
// Its conventional executable name also keeps Electron's default-app runtime
// in development mode instead of making app.isPackaged report true.
writeDevelopmentLauncherScript(launcherBinaryPath, runtimeElectronBinaryPath);
}
NodeFS.writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
return launcherBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
@@ -1,6 +1,10 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript, resolveElectronBinaryPath } from "./electron-launcher.mjs";
import {
makeDevelopmentLauncherScript,
resolveElectronBinaryPath,
resolveMacLauncherPaths,
} from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
@@ -45,4 +49,33 @@ describe("electron development launcher", () => {
);
assert.deepEqual(calls, ["ensure", "require:electron"]);
});
it("keeps the native Electron executable name inside the branded macOS bundle", () => {
const paths = resolveMacLauncherPaths(
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app",
"T3 Code (Dev)",
);
assert.equal(paths.launcherExecutableName, "T3 Code (Dev) Launcher");
assert.equal(
paths.launcherBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/T3 Code (Dev) Launcher",
);
assert.equal(
paths.runtimeElectronBinaryPath,
"/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron",
);
const script = makeDevelopmentLauncherScript({
electronBinaryPath: paths.runtimeElectronBinaryPath,
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {},
});
assert.include(
script,
"exec '/repo/apps/desktop/.electron-runtime/T3 Code (Dev).app/Contents/MacOS/Electron'",
);
assert.notInclude(script, "node_modules/electron");
});
});
@@ -53,13 +53,16 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, true);
assert.equal(environment.appDataDirectory, "/Users/alice/Library/Application Support");
assert.equal(environment.baseDir, "/tmp/t3");
assert.equal(environment.stateDir, "/tmp/t3/dev");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/dev/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/dev/client-settings.json");
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.desktopSettingsPath, "/tmp/t3/userdata/desktop-settings.json");
assert.equal(environment.clientSettingsPath, "/tmp/t3/userdata/client-settings.json");
assert.equal(
environment.savedEnvironmentRegistryPath,
"/tmp/t3/userdata/saved-environments.json",
);
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -78,7 +81,7 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("derives production state paths under userdata", () =>
it.effect("stores production state under userdata in an explicit home", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
{},
@@ -95,6 +98,19 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
{},
{ VITE_DEV_SERVER_URL: "http://localhost:5173" },
);
const production = yield* makeEnvironment();
assert.equal(development.stateDir, "/Users/alice/.t3/dev");
assert.equal(production.stateDir, "/Users/alice/.t3/userdata");
}),
);
it.effect("uses a configured app user model id override", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment(
+6 -2
View File
@@ -147,7 +147,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const baseDir = Option.getOrElse(config.t3Home, () => path.join(homeDirectory, ".t3"));
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const branding = resolveDesktopAppBranding({
@@ -155,7 +156,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(baseDir, isDevelopment ? "dev" : "userdata");
const stateDir = path.join(
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const resourcesPath = input.resourcesPath;
+12 -2
View File
@@ -31,6 +31,12 @@ const TestLayer = ElectronMenu.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
const makeWindow = (zoomFactor = 1): Electron.BrowserWindow =>
({
id: 7,
webContents: { getZoomFactor: () => zoomFactor },
}) as unknown as Electron.BrowserWindow;
describe("ElectronMenu", () => {
beforeEach(() => {
buildFromTemplateMock.mockReset();
@@ -70,7 +76,7 @@ describe("ElectronMenu", () => {
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(),
items: [{ id: "copy", label: "Copy" }],
position: Option.none(),
});
@@ -81,20 +87,24 @@ describe("ElectronMenu", () => {
it.effect("resolves with none when the menu closes without a click", () =>
Effect.gen(function* () {
let popupOptions: Electron.PopupOptions | undefined;
buildFromTemplateMock.mockImplementation(() => ({
popup: (options: Electron.PopupOptions) => {
popupOptions = options;
options.callback?.();
},
}));
const electronMenu = yield* ElectronMenu.ElectronMenu;
const selectedItemId = yield* electronMenu.showContextMenu({
window: {} as Electron.BrowserWindow,
window: makeWindow(2),
items: [{ id: "copy", label: "Copy" }],
position: Option.some({ x: 10.8, y: 20.2 }),
});
assert.isTrue(Option.isNone(selectedItemId));
assert.equal(popupOptions?.x, 21);
assert.equal(popupOptions?.y, 40);
assert.deepEqual(buildFromTemplateMock.mock.calls[0]?.[0][0], {
label: "Copy",
enabled: true,
+13 -3
View File
@@ -94,13 +94,20 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
return normalizedItems;
}
// Renderer positions arrive in CSS pixels; popup() expects window points, so
// page zoom must be factored in or menus drift proportionally to their
// distance from the window origin.
const normalizePosition = (
position: Option.Option<ElectronMenuPosition>,
zoomFactor: number,
): Option.Option<ElectronMenuPosition> =>
Option.filter(
position,
({ x, y }) => Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0,
).pipe(Option.map(({ x, y }) => ({ x: Math.floor(x), y: Math.floor(y) })));
({ x, y }) =>
Number.isFinite(x) && Number.isFinite(y) && x >= 0 && y >= 0 && Number.isFinite(zoomFactor),
).pipe(
Option.map(({ x, y }) => ({ x: Math.floor(x * zoomFactor), y: Math.floor(y * zoomFactor) })),
);
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
@@ -214,7 +221,10 @@ export const make = Effect.gen(function* () {
try {
const menu = Electron.Menu.buildFromTemplate(buildTemplate(normalizedItems, complete));
const popupPosition = normalizePosition(input.position);
const popupPosition = normalizePosition(
input.position,
input.window.webContents.getZoomFactor(),
);
const popupOptions = Option.match(popupPosition, {
onNone: (): Electron.PopupOptions => ({
window: input.window,
@@ -16,6 +16,7 @@ import {
formatNodePtyProbeFailureReason,
formatWslShellTransportFailureReason,
parseNodePath,
parseNodeVersion,
parseResolvedPath,
parseToolchainReport,
probeWslDistros,
@@ -173,6 +174,29 @@ describe("parseNodePath", () => {
});
});
describe("parseNodeVersion", () => {
it("extracts the node version from a nodeVersion: line", () => {
expect(parseNodeVersion("nodeVersion:24.10.0")).toBe("24.10.0");
});
it("returns null when the version value is empty", () => {
expect(parseNodeVersion("nodeVersion:")).toBeNull();
});
it("returns null when there is no nodeVersion line at all", () => {
expect(parseNodeVersion("nodePath:/usr/bin/node\nresolvedPath:/usr/bin")).toBeNull();
});
it("ignores surrounding noise and trims whitespace", () => {
const stdout = [
"some preamble noise",
" nodeVersion:22.16.0 ",
"nodePath:/usr/bin/node",
].join("\n");
expect(parseNodeVersion(stdout)).toBe("22.16.0");
});
});
describe("parseResolvedPath", () => {
it("preserves spaces and apostrophes in the resolved login-shell PATH", () => {
const resolvedPath = "/home/test user/bin:/opt/test's tools/bin:/usr/bin:/bin";
+42 -4
View File
@@ -32,7 +32,11 @@ export interface EnsureWslNodePtyOptions {
}
export type EnsureWslNodePtyResult =
| { readonly ok: true; readonly nodePath: string; readonly resolvedPath: string }
| {
readonly ok: true;
readonly nodePath: string;
readonly resolvedPath: string;
}
| {
readonly ok: false;
readonly reason: string;
@@ -222,6 +226,7 @@ export const formatNodePtyProbeFailureReason = (exitCode: number): string | null
const NODE_PTY_PROBE_SCRIPT = (
linuxServerDir: string,
) => `printf 'nodePath:%s\\n' "$(command -v node 2>/dev/null)"
printf 'nodeVersion:%s\\n' "$(node -p 'process.versions.node' 2>/dev/null)"
printf 'resolvedPath:%s\\n' "$PATH"
cd ${shellQuote(linuxServerDir)} && node <<'NODE' >/dev/null 2>&1
// The server bundle externalizes its deps to node_modules, and the WSL Node
@@ -318,6 +323,16 @@ export const parseNodePath = (stdout: string): string | null => {
return path ?? null;
};
export const parseNodeVersion = (stdout: string): string | null => {
const version = stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.startsWith("nodeVersion:"))
.map((line) => line.slice("nodeVersion:".length).trim())
.find((value) => value.length > 0);
return version ?? null;
};
// Captures the login-shell PATH after the shared resolver has loaded version
// managers. Preserve the value byte-for-byte apart from a Windows-style CR so
// paths containing spaces or apostrophes can be forwarded as one env argv.
@@ -404,7 +419,11 @@ const ensureNodePtyImpl = (
const transportFailureReason = formatWslShellTransportFailureReason(probe.transportFailure);
if (transportFailureReason !== null) {
return { ok: false, reason: transportFailureReason, fatal: false } as const;
return {
ok: false,
reason: transportFailureReason,
fatal: false,
} as const;
}
// No node at all, even after the shared resolver repaired PATH. Surface
@@ -457,12 +476,31 @@ const ensureNodePtyImpl = (
} as const;
}
if (probe.exitCode === 0) return { ok: true, nodePath, resolvedPath } as const;
if (probe.exitCode === 0) {
const rawVersion = parseNodeVersion(probe.stdout);
if (
rawVersion !== null &&
options.nodeEngineRange &&
!satisfiesSemverRange(rawVersion, options.nodeEngineRange.trim())
) {
const range = options.nodeEngineRange.trim();
return {
ok: false,
reason: `WSL Node.js ${rawVersion} does not satisfy the server's required engine range (${range}). Install a compatible version, and restart the desktop app.`,
fatal: true,
} as const;
}
return { ok: true, nodePath, resolvedPath } as const;
}
if (options.allowBuild !== true) {
const packagedProbeFailure = formatNodePtyProbeFailureReason(probe.exitCode);
if (packagedProbeFailure !== null) {
return { ok: false, reason: packagedProbeFailure, fatal: true } as const;
return {
ok: false,
reason: packagedProbeFailure,
fatal: true,
} as const;
}
}
@@ -1 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" fill="#EDECEC" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

Before

Width:  |  Height:  |  Size: 649 B

After

Width:  |  Height:  |  Size: 665 B

@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none">
<path fill="#F5F5F5" d="M9.26905 15.284L17.2479 9.36086C17.6391 9.07047 18.1981 9.18374 18.3845 9.63478C19.3655 12.0135 18.9272 14.8721 16.9755 16.8349C15.0238 18.7976 12.3082 19.228 9.8261 18.2477L7.1146 19.5102C11.0037 22.1834 15.7263 21.5223 18.6774 18.5525C21.0182 16.1985 21.7432 12.9897 21.0653 10.0961L21.0714 10.1023C20.0884 5.85143 21.3131 4.15233 23.8218 0.677913C23.8812 0.595532 23.9406 0.513151 24 0.428711L20.6987 3.74866V3.73836L9.267 15.2861" />
<path fill="#F5F5F5" d="M7.62249 16.7237C4.83113 14.0422 5.3124 9.89222 7.69417 7.49905C9.45541 5.72786 12.341 5.00497 14.86 6.06768L17.5653 4.81138C17.0779 4.45714 16.4533 4.07613 15.7365 3.80839C12.4966 2.46764 8.6178 3.13492 5.98413 5.78141C3.45081 8.32904 2.65415 12.2463 4.02219 15.5889C5.04412 18.0871 3.36889 19.8541 1.68137 21.6377C1.08337 22.2699 0.483318 22.9022 0 23.5716L7.62045 16.7257" />
</svg>

After

Width:  |  Height:  |  Size: 948 B

+1 -1
View File
@@ -1,6 +1,6 @@
export const GITHUB_REPOSITORY_URL = "https://github.com/pingdotgg/t3code";
export const MARKETING_STATS = {
githubStars: "12k+",
githubStars: "14k+",
users: "100,000",
} as const;
+41 -9
View File
@@ -33,6 +33,9 @@ const mobileEndorsementRows = [
<span class="hero-float-mark hf-cursor" title="Cursor">
<img src="/harnesses/cursor_light.svg" alt="" />
</span>
<span class="hero-float-mark hf-grok" title="Grok">
<img src="/harnesses/grok-dark.svg" alt="" />
</span>
</div>
<div class="container hero-inner">
@@ -41,7 +44,7 @@ const mobileEndorsementRows = [
</h1>
<p class="hero-sub">
Orchestrate Claude Code, Codex, OpenCode and Cursor from one surface.
Orchestrate Claude Code, Codex, OpenCode, Cursor, and Grok from one surface.
Bring your own subscription. Fork the whole thing.
</p>
@@ -173,7 +176,7 @@ const mobileEndorsementRows = [
<h2>Bring your own sub</h2>
<p>
T3 Code doesn't resell tokens. Plug in Claude Code, Codex, OpenCode,
or Cursor with the credentials you already have — we orchestrate
Cursor, or Grok with the credentials you already have — we orchestrate
them, you keep your plan.
</p>
</div>
@@ -207,6 +210,13 @@ const mobileEndorsementRows = [
<div class="harness-tag">cursor-agent</div>
</div>
</div>
<div class="harness">
<div class="harness-mark"><img src="/harnesses/grok-dark.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Grok CLI</div>
<div class="harness-tag">grok login</div>
</div>
</div>
</div>
<div class="harness-footer">
@@ -615,8 +625,9 @@ const mobileEndorsementRows = [
.hero-float-mark.hf-claude { background: radial-gradient(circle at 30% 25%, rgba(217, 119, 87, 0.22), rgba(20, 20, 24, 0.92) 65%); top: 8%; left: 7%; animation-delay: 0s; transform: rotate(-8deg); }
.hero-float-mark.hf-codex { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 6%; right: 7%; animation-delay: -2.5s; transform: rotate(6deg); }
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 32%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
.hero-float-mark.hf-opencode { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.06), rgba(20, 20, 24, 0.92) 65%); top: 30%; left: 5%; animation-delay: -5s; transform: rotate(4deg); }
.hero-float-mark.hf-cursor { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 30%; right: 5%; animation-delay: -7s; transform: rotate(-5deg); }
.hero-float-mark.hf-grok { background: radial-gradient(circle at 30% 25%, rgba(255, 255, 255, 0.08), rgba(20, 20, 24, 0.92) 65%); top: 52%; left: 6%; animation-delay: -1.2s; transform: rotate(3deg); }
@media (max-width: 1180px) {
.hero-float-mark { width: 76px; height: 76px; border-radius: 20px; }
@@ -625,6 +636,7 @@ const mobileEndorsementRows = [
.hero-float-mark.hf-codex { top: 2%; right: 3%; }
.hero-float-mark.hf-opencode { top: 26%; left: 2%; }
.hero-float-mark.hf-cursor { top: 24%; right: 2%; }
.hero-float-mark.hf-grok { top: 48%; left: 2%; transform: rotate(3deg); }
}
@media (max-width: 820px) {
@@ -659,17 +671,18 @@ const mobileEndorsementRows = [
height: 44px;
}
/* Two above the title, two flanking the call-to-action area. */
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
.hero-float-mark.hf-claude {
top: 44px;
left: 10px;
transform: rotate(-10deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
.hero-float-mark.hf-grok {
top: 240px;
left: 4px;
right: auto;
transform: rotate(-4deg);
}
.hero-float-mark.hf-opencode {
@@ -679,6 +692,12 @@ const mobileEndorsementRows = [
transform: rotate(-6deg);
}
.hero-float-mark.hf-codex {
top: 44px;
right: 10px;
transform: rotate(8deg);
}
.hero-float-mark.hf-cursor {
top: 474px;
right: 4px;
@@ -688,6 +707,14 @@ const mobileEndorsementRows = [
}
@media (max-width: 340px) {
.hero-float-mark.hf-grok {
top: 220px;
left: 0;
width: 52px;
height: 52px;
border-radius: 14px;
}
.hero-float-mark.hf-opencode,
.hero-float-mark.hf-cursor {
top: 580px;
@@ -704,6 +731,7 @@ const mobileEndorsementRows = [
right: 0;
}
.hero-float-mark.hf-grok img,
.hero-float-mark.hf-opencode img,
.hero-float-mark.hf-cursor img {
width: 30px;
@@ -750,7 +778,7 @@ const mobileEndorsementRows = [
.harness-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-columns: repeat(5, 1fr);
gap: 0;
border: 1px solid var(--border);
border-radius: var(--radius);
@@ -1205,6 +1233,10 @@ const mobileEndorsementRows = [
.harness-grid { grid-template-columns: 1fr 1fr; }
.harness { border-right: 0; border-bottom: 1px solid var(--border); }
.harness:nth-child(odd) { border-right: 1px solid var(--border); }
.harness:nth-child(5):last-child {
grid-column: 1 / -1;
border-right: 0;
}
.git-inner { grid-template-columns: 1fr; gap: 40px; }
.open-grid { grid-template-columns: 1fr; }
}
+22 -8
View File
@@ -1,5 +1,6 @@
import type { ExpoConfig } from "expo/config";
import { BRAND_ASSET_PATHS } from "../../scripts/lib/brand-assets.ts";
import { loadRepoEnv } from "../../scripts/lib/public-config.ts";
type AppVariant = "development" | "preview" | "production";
@@ -13,6 +14,8 @@ const isIosPersonalTeamBuild = repoEnv.T3CODE_IOS_PERSONAL_TEAM === "1";
const personalTeamBundleIdentifier = repoEnv.T3CODE_IOS_PERSONAL_TEAM_BUNDLE_ID?.trim();
const IOS_BUNDLE_IDENTIFIER_PATTERN = /^[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+$/;
const fromRepoRoot = (relativePath: string) => `../../${relativePath}`;
if (
isIosPersonalTeamBuild &&
(!personalTeamBundleIdentifier ||
@@ -24,20 +27,31 @@ if (
}
const DEVELOPMENT_ASSETS = {
appIcon: "./assets/splash-icon-dev.png",
iosIcon: "./assets/icon-composer-dev.icon",
splashIcon: "./assets/splash-icon-dev.png",
androidAdaptiveForeground: "./assets/android-icon-dev-foreground.png",
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.developmentIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.developmentUniversalIconPng),
androidAdaptiveBackgroundColor: "#00639B",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#00639B",
} as const;
const PREVIEW_ASSETS = {
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.nightlyIosIconPng),
androidAdaptiveForeground: fromRepoRoot(BRAND_ASSET_PATHS.nightlyLinuxIconPng),
androidAdaptiveBackgroundColor: "#111533",
androidMonochromeIcon: "./assets/android-icon-mark.png",
androidNotificationIcon: "./assets/android-notification-icon.png",
androidNotificationColor: "#7565C7",
} as const;
const RELEASE_ASSETS = {
appIcon: "./assets/splash-icon-prod.png",
iosIcon: "./assets/icon-composer-prod.icon",
splashIcon: "./assets/splash-icon-prod.png",
appIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
iosIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIconComposerProject),
splashIcon: fromRepoRoot(BRAND_ASSET_PATHS.productionIosIconPng),
androidAdaptiveForeground: "./assets/android-icon-mark.png",
androidAdaptiveBackgroundColor: "#000000",
androidMonochromeIcon: "./assets/android-icon-mark.png",
@@ -60,7 +74,7 @@ const VARIANT_CONFIG = {
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
assets: RELEASE_ASSETS,
assets: PREVIEW_ASSETS,
},
production: {
appName: "T3 Code",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 323 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 MiB

@@ -1,3 +0,0 @@
<svg width="77" height="47" viewBox="0 0 77 47" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.56 45.5V8.58H1.69082e-06V-3.09944e-06H39.65V8.58H25.09V45.5H14.56ZM57.8454 46.28C54.6821 46.28 51.5404 45.8683 48.4204 45.045C45.3004 44.1783 42.6571 42.965 40.4904 41.405L44.5854 33.345C46.3188 34.6017 48.3338 35.5983 50.6304 36.335C52.9271 37.0717 55.2454 37.44 57.5854 37.44C60.2288 37.44 62.3088 36.92 63.8254 35.88C65.3421 34.84 66.1004 33.41 66.1004 31.59C66.1004 29.8567 65.4288 28.4917 64.0854 27.495C62.7421 26.4983 60.5754 26 57.5854 26H52.7754V19.045L65.4504 4.68L66.6204 8.45H42.7654V-3.09944e-06H74.6154V6.825L62.0054 21.19L56.6754 18.135H59.7304C65.3204 18.135 69.5454 19.3917 72.4054 21.905C75.2654 24.4183 76.6954 27.6467 76.6954 31.59C76.6954 34.1467 76.0238 36.5517 74.6804 38.805C73.3371 41.015 71.2788 42.8133 68.5054 44.2C65.7321 45.5867 62.1788 46.28 57.8454 46.28Z" fill="white"/>
</svg>

Before

Width:  |  Height:  |  Size: 920 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.0 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 302 KiB

+3 -1
View File
@@ -15,6 +15,7 @@ import { DynamicColorIOS, Platform, Pressable, ScrollView, StyleSheet } from "re
import { useResolveClassNames } from "uniwind";
import { AppText as Text } from "./components/AppText";
import { renderCompactBrandTitle } from "./components/CompactBrandTitle";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
@@ -377,7 +378,8 @@ export const RootStack = createNativeStackNavigator({
...GLASS_HEADER_OPTIONS,
contentStyle: { backgroundColor: "transparent" },
headerBackVisible: false,
title: "Threads",
headerTitle: renderCompactBrandTitle,
title: "T3 Code",
},
}),
Thread: createNativeStackScreen({
+13 -3
View File
@@ -1,13 +1,23 @@
import { Image, View } from "react-native";
import Constants from "expo-constants";
import { Image } from "expo-image";
import { View } from "react-native";
import { AppText as Text } from "./AppText";
const BRAND_MARK_SOURCE = require("../../../../assets/dev/blueprint-ios-1024.png");
const appVariant = Constants.expoConfig?.extra?.appVariant;
const BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
const DEFAULT_STAGE_LABEL =
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) {
const compact = props.compact ?? false;
const iconSize = compact ? 32 : 44;
const stageLabel = props.stageLabel ?? "Alpha";
const stageLabel = props.stageLabel ?? DEFAULT_STAGE_LABEL;
return (
<View className="flex-row items-center gap-3">
@@ -0,0 +1,60 @@
import { View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3Wordmark } from "./T3Wordmark";
import { useThemeColor } from "../lib/useThemeColor";
/**
* Compact brand lockup sized for native navigation bars.
*/
export function CompactBrandTitle() {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const subtleColor = useThemeColor("--color-subtle");
return (
<View
aria-level={1}
accessibilityLabel="T3 Code"
accessible
role="heading"
style={{ alignItems: "center", flexDirection: "row", gap: 6 }}
>
<T3Wordmark color={iconColor} height={11} />
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Medium",
fontSize: 14,
letterSpacing: -0.35,
}}
>
Code
</Text>
<View
style={{
backgroundColor: subtleColor,
borderRadius: 999,
paddingHorizontal: 6,
paddingVertical: 2,
}}
>
<Text
style={{
color: mutedColor,
fontFamily: "DMSans-Bold",
fontSize: 9,
letterSpacing: 0.9,
textTransform: "uppercase",
}}
>
Alpha
</Text>
</View>
</View>
);
}
export function renderCompactBrandTitle() {
return <CompactBrandTitle />;
}
@@ -4,6 +4,7 @@ import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
import { useProjects, useThreadShells } from "../../state/entities";
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
@@ -86,7 +87,9 @@ export function HomeRouteScreen() {
>
<>
{/* Restore the compact title in case the split branch blanked it. */}
<NativeStackScreenOptions options={{ title: "Threads", headerTitle: "Threads" }} />
<NativeStackScreenOptions
options={{ title: "T3 Code", headerTitle: renderCompactBrandTitle }}
/>
<HomeHeader
environments={environments}
searchQuery={searchQuery}
@@ -11,6 +11,7 @@ import {
import type { ReactNode } from "react";
import { Platform, useColorScheme } from "react-native";
import { renderCompactBrandTitle } from "../../components/CompactBrandTitle";
import { nativeHeaderScrollEdgeEffects } from "../../native/StackHeader";
const SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
@@ -34,10 +35,11 @@ const SIDEBAR_SCREEN_OPTIONS: SidebarScreenOptions = {
headerShadowVisible: false,
headerShown: true,
headerStyle: { backgroundColor: "transparent" },
headerTitle: renderCompactBrandTitle,
headerTitleStyle: { fontSize: 18, fontWeight: "800" },
headerTransparent: true,
scrollEdgeEffects: SCROLL_EDGE_EFFECTS,
title: "Threads",
title: "T3 Code",
unstable_navigationItemStyle: "editor",
};
@@ -62,7 +62,7 @@ const promptText = NodeProcess.argv[4] ?? "helo";
const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";
const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";
const targetFast = NodeProcess.env.CURSOR_FAST ?? "";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "agent";
const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "cursor-agent";
const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
+119
View File
@@ -0,0 +1,119 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
import { runSqliteState } from "./t3-sqlite-state.ts";
const createFixtureDatabase = Effect.fn("createSqliteStateFixtureDatabase")(function* (
baseDir: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const stateDir = path.join(baseDir, "userdata");
const databasePath = path.join(stateDir, "state.sqlite");
yield* fs.makeDirectory(stateDir, { recursive: true });
yield* Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`CREATE TABLE fixtures (id INTEGER PRIMARY KEY, label TEXT NOT NULL)`;
yield* sql`INSERT INTO fixtures (id, label) VALUES (1, 'existing')`;
}).pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
});
it.layer(NodeServices.layer)("t3-sqlite-state", (it) => {
it.effect("reports each invalid SQL source with a specific error", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-input-" });
const multipleSources = yield* runSqliteState({
operation: "query",
baseDir,
sql: "SELECT 1",
file: "fixture.sql",
}).pipe(Effect.flip);
assert.equal(multipleSources._tag, "SqliteStateMultipleSqlSourcesError");
assert.equal(multipleSources.message, "Provide only one of --sql or --file.");
const missingSource = yield* runSqliteState({ operation: "query", baseDir }).pipe(
Effect.flip,
);
assert.equal(missingSource._tag, "SqliteStateMissingSqlSourceError");
assert.equal(missingSource.message, "Provide one of --sql or --file.");
const emptySql = yield* runSqliteState({
operation: "query",
baseDir,
sql: " ",
}).pipe(Effect.flip);
assert.equal(emptySql._tag, "SqliteStateEmptySqlError");
assert.equal(emptySql.message, "SQL input is empty.");
}),
);
it.effect("queries an isolated database through Effect SQL", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-query-" });
yield* createFixtureDatabase(baseDir);
const result = yield* runSqliteState({
operation: "query",
baseDir,
sql: "SELECT id, label FROM fixtures",
});
assert.equal(result.operation, "query");
if (result.operation === "query") {
assert.deepStrictEqual(result.rows, [{ id: 1, label: "existing" }]);
}
}),
);
it.effect("backs up isolated state before writes and refuses the shared home", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-sqlite-state-exec-" });
yield* createFixtureDatabase(baseDir);
const mutation = yield* runSqliteState({
operation: "exec",
baseDir,
sql: "INSERT INTO fixtures (id, label) VALUES (2, 'seeded')",
});
assert.equal(mutation.operation, "exec");
if (mutation.operation === "exec") {
assert.equal((yield* fs.stat(mutation.backup)).mode & 0o777, 0o600);
}
const error = yield* runSqliteState(
{
operation: "exec",
baseDir,
sql: "DELETE FROM fixtures",
},
{ sharedHome: baseDir },
).pipe(Effect.flip);
assert.equal(error._tag, "SqliteStateSharedHomeMutationError");
const aliasParent = yield* fs.makeTempDirectoryScoped({
prefix: "t3-sqlite-state-alias-",
});
const aliasBaseDir = path.join(aliasParent, "shared-home-alias");
yield* fs.symlink(baseDir, aliasBaseDir);
const aliasError = yield* runSqliteState(
{
operation: "exec",
baseDir: aliasBaseDir,
sql: "DELETE FROM fixtures",
},
{ sharedHome: baseDir },
).pipe(Effect.flip);
assert.equal(aliasError._tag, "SqliteStateSharedHomeMutationError");
}),
);
});
+285
View File
@@ -0,0 +1,285 @@
#!/usr/bin/env node
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import * as Console from "effect/Console";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { Argument, Command, Flag } from "effect/unstable/cli";
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
export const SqliteStateOperation = Schema.Literals(["query", "exec"]);
export type SqliteStateOperation = typeof SqliteStateOperation.Type;
export class SqliteStateMultipleSqlSourcesError extends Schema.TaggedErrorClass<SqliteStateMultipleSqlSourcesError>()(
"SqliteStateMultipleSqlSourcesError",
{},
) {
override get message(): string {
return "Provide only one of --sql or --file.";
}
}
export class SqliteStateMissingSqlSourceError extends Schema.TaggedErrorClass<SqliteStateMissingSqlSourceError>()(
"SqliteStateMissingSqlSourceError",
{},
) {
override get message(): string {
return "Provide one of --sql or --file.";
}
}
export class SqliteStateEmptySqlError extends Schema.TaggedErrorClass<SqliteStateEmptySqlError>()(
"SqliteStateEmptySqlError",
{},
) {
override get message(): string {
return "SQL input is empty.";
}
}
export class SqliteStateDatabaseMissingError extends Schema.TaggedErrorClass<SqliteStateDatabaseMissingError>()(
"SqliteStateDatabaseMissingError",
{
databasePath: Schema.String,
},
) {
override get message(): string {
return `Database does not exist at '${this.databasePath}'. Start T3 once to run migrations.`;
}
}
export class SqliteStateSharedHomeMutationError extends Schema.TaggedErrorClass<SqliteStateSharedHomeMutationError>()(
"SqliteStateSharedHomeMutationError",
{},
) {
override get message(): string {
return "Refusing to mutate the shared ~/.t3 database. Use an isolated --base-dir.";
}
}
export class SqliteStateSqlFileError extends Schema.TaggedErrorClass<SqliteStateSqlFileError>()(
"SqliteStateSqlFileError",
{
filePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read SQL from '${this.filePath}'.`;
}
}
export class SqliteStateDatabaseError extends Schema.TaggedErrorClass<SqliteStateDatabaseError>()(
"SqliteStateDatabaseError",
{
operation: SqliteStateOperation,
databasePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} SQLite database at '${this.databasePath}'.`;
}
}
const SqliteStateValue = Schema.Union([
Schema.Null,
Schema.String,
Schema.Number,
Schema.Array(Schema.Number),
]);
const SqliteStateRow = Schema.Record(Schema.String, SqliteStateValue);
const SqliteStateQueryResult = Schema.Struct({
operation: Schema.Literal("query"),
database: Schema.String,
rows: Schema.Array(SqliteStateRow),
});
const SqliteStateExecResult = Schema.Struct({
operation: Schema.Literal("exec"),
database: Schema.String,
backup: Schema.String,
});
const SqliteStateResult = Schema.Union([SqliteStateQueryResult, SqliteStateExecResult]);
const encodeSqliteStateResult = Schema.encodeEffect(fromJsonStringPretty(SqliteStateResult));
export type SqliteStateResult = typeof SqliteStateResult.Type;
type RawSqliteValue = null | string | number | bigint | Uint8Array;
type RawSqliteRow = Readonly<Record<string, RawSqliteValue>>;
export interface RunSqliteStateInput {
readonly operation: SqliteStateOperation;
readonly baseDir: string;
readonly sql?: string | undefined;
readonly file?: string | undefined;
}
export interface RunSqliteStateOptions {
readonly sharedHome?: string | undefined;
}
const resolveSqlSource = Effect.fn("resolveSqliteStateSqlSource")(function* (
sql: string | undefined,
file: string | undefined,
) {
if (sql !== undefined && file !== undefined) {
return yield* new SqliteStateMultipleSqlSourcesError();
}
if (sql === undefined && file === undefined) {
return yield* new SqliteStateMissingSqlSourceError();
}
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
let source: string;
if (sql !== undefined) {
source = sql;
} else {
const filePath = path.resolve(file as string);
source = yield* fs
.readFileString(filePath)
.pipe(Effect.mapError((cause) => new SqliteStateSqlFileError({ filePath, cause })));
}
const trimmed = source.trim();
if (trimmed.length === 0) {
return yield* new SqliteStateEmptySqlError();
}
return trimmed;
});
function normalizeSqliteValue(value: RawSqliteValue): typeof SqliteStateValue.Type {
if (typeof value === "bigint") {
const numericValue = Number(value);
return Number.isSafeInteger(numericValue) ? numericValue : value.toString();
}
if (value instanceof Uint8Array) {
return Array.from(value);
}
return value;
}
function normalizeSqliteRow(row: RawSqliteRow): typeof SqliteStateRow.Type {
return Object.fromEntries(
Object.entries(row).map(([key, value]) => [key, normalizeSqliteValue(value)]),
);
}
export const runSqliteState = Effect.fn("runSqliteState")(function* (
input: RunSqliteStateInput,
options: RunSqliteStateOptions = {},
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = path.resolve(input.baseDir);
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
const databasePath = path.join(baseDir, "userdata", "state.sqlite");
const source = yield* resolveSqlSource(input.sql, input.file);
if (!(yield* fs.exists(databasePath))) {
return yield* new SqliteStateDatabaseMissingError({ databasePath });
}
if (input.operation === "exec") {
const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
fs.realPath(baseDir),
fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
]);
if (canonicalBaseDir === canonicalSharedHome) {
return yield* new SqliteStateSharedHomeMutationError();
}
}
const program = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql.unsafe("PRAGMA busy_timeout = 5000").unprepared;
if (input.operation === "query") {
const rows = yield* sql.unsafe<RawSqliteRow>(source).unprepared.pipe(
Effect.provideService(SqlClient.SafeIntegers, true),
Effect.map((rows) => rows.map(normalizeSqliteRow)),
);
return {
operation: "query",
database: databasePath,
rows,
} as const;
}
const timestamp = DateTime.formatIso(yield* DateTime.now).replaceAll(":", "-");
const backupPath = `${databasePath}.backup-${timestamp}`;
yield* sql`VACUUM INTO ${backupPath}`;
yield* fs.chmod(backupPath, 0o600);
yield* sql.withTransaction(sql.unsafe(source).unprepared);
return {
operation: "exec",
database: databasePath,
backup: backupPath,
} as const;
});
return yield* program.pipe(
Effect.provide(
NodeSqliteClient.layer({
filename: databasePath,
readonly: input.operation === "query",
}),
),
Effect.mapError(
(cause) =>
new SqliteStateDatabaseError({
operation: input.operation,
databasePath,
cause,
}),
),
);
});
export const t3SqliteStateCommand = Command.make(
"t3-sqlite-state",
{
operation: Argument.choice("operation", SqliteStateOperation.literals).pipe(
Argument.withDescription("Run a read-only query or a backed-up fixture mutation."),
),
baseDir: Flag.string("base-dir").pipe(
Flag.withDescription("Explicit T3 base directory containing userdata/state.sqlite."),
),
sql: Flag.string("sql").pipe(
Flag.optional,
Flag.withDescription("SQL source supplied directly on the command line."),
),
file: Flag.string("file").pipe(
Flag.optional,
Flag.withDescription("Path to a SQL source file."),
),
},
({ operation, baseDir, sql, file }) =>
runSqliteState({
operation,
baseDir,
sql: Option.getOrUndefined(sql),
file: Option.getOrUndefined(file),
}).pipe(Effect.flatMap(encodeSqliteStateResult), Effect.flatMap(Console.log)),
).pipe(
Command.withDescription(
"Inspect or seed an isolated T3 SQLite database with automatic backups for writes.",
),
);
if (import.meta.main) {
Command.run(t3SqliteStateCommand, { version: "0.0.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain,
);
}
+23 -6
View File
@@ -18,6 +18,9 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "../config.ts";
import { resolveServerConfig } from "./config.ts";
const deriveExplicitServerPaths = (baseDir: string, devUrl: URL | undefined) =>
deriveServerPaths(baseDir, devUrl, { baseDirIsExplicit: true });
const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const makeDesktopBootstrap = (
@@ -60,7 +63,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:5173"),
);
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
@@ -119,6 +125,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServeEnabled: false,
tailscaleServePort: 443,
});
assert.equal(resolved.stateDir, join(baseDir, "userdata"));
}),
);
@@ -126,7 +133,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
@@ -185,6 +195,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
});
assert.equal(resolved.dbPath, join(baseDir, "userdata", "state.sqlite"));
}),
);
@@ -199,7 +210,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServePort: 443,
}),
);
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
@@ -396,7 +410,10 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
tailscaleServePort: 443,
}),
);
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const derivedPaths = yield* deriveExplicitServerPaths(
baseDir,
new URL("http://127.0.0.1:4173"),
);
const resolved = yield* resolveServerConfig(
{
@@ -461,7 +478,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
@@ -529,7 +546,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const derivedPaths = yield* deriveExplicitServerPaths(baseDir, undefined);
const resolved = yield* resolveServerConfig(
{
+11 -7
View File
@@ -31,7 +31,9 @@ export const hostFlag = Flag.string("host").pipe(
Flag.optional,
);
export const baseDirFlag = Flag.string("base-dir").pipe(
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
Flag.withDescription(
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
),
Flag.optional,
);
export const devUrlFlag = Flag.string("dev-url").pipe(
@@ -259,19 +261,21 @@ export const resolveServerConfig = (
resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
() => undefined,
);
const explicitBaseDir = resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
).pipe(Option.filter((value) => value.trim().length > 0));
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.fromUndefinedOr(bootstrap?.t3Home),
),
resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
),
);
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl);
const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
baseDirIsExplicit: Option.isSome(explicitBaseDir),
});
yield* ServerConfig.ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
+9 -1
View File
@@ -45,6 +45,10 @@ export interface ServerDerivedPaths {
readonly secretsDir: string;
}
export interface DeriveServerPathsOptions {
readonly baseDirIsExplicit?: boolean;
}
/**
* ServerConfig - Service tag for server runtime configuration.
*/
@@ -91,9 +95,13 @@ export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerCo
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfig["Service"]["baseDir"],
devUrl: ServerConfig["Service"]["devUrl"],
options: DeriveServerPathsOptions = {},
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const stateDir = join(
baseDir,
devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
);
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
@@ -1,4 +1,4 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -67,6 +67,48 @@ describe("ProcessDiagnostics", () => {
}),
);
it("schema-decodes Windows process arrays and skips invalid records", () => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
`[{"ProcessId":10,"ParentProcessId":1,"Name":"node.exe","CommandLine":"node server.js","Status":"Running","WorkingSetSize":4096,"PercentProcessorTime":12.5},{"ProcessId":"invalid","ParentProcessId":10,"Name":"ignored.exe"}]`,
);
assert.deepStrictEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 12.5,
rssBytes: 4096,
elapsed: "",
command: "node server.js",
},
]);
});
it("accepts a single Windows process and defaults optional metrics", () => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
`{"ProcessId":11,"ParentProcessId":10,"Name":"agent.exe","CommandLine":null}`,
);
assert.deepStrictEqual(rows, [
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
});
it("returns no Windows processes for malformed JSON", () => {
assert.deepStrictEqual(ProcessDiagnostics.parseWindowsProcessRows("{invalid"), []);
});
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -136,6 +136,20 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
Name: Schema.optional(Schema.NullOr(Schema.String)),
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -201,51 +215,56 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
function normalizeWindowsProcessRow(record: WindowsProcessRecord): Option.Option<ProcessRow> {
const commandLine = Option.fromNullishOr(record.CommandLine).pipe(
Option.filter((value) => value.trim().length > 0),
Option.orElse(() =>
Option.fromNullishOr(record.Name).pipe(Option.filter((value) => value.trim().length > 0)),
),
);
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
record.WorkingSetSize !== null &&
record.WorkingSetSize !== undefined &&
Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
record.PercentProcessorTime !== null &&
record.PercentProcessorTime !== undefined &&
Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
if (record.ProcessId <= 0 || record.ParentProcessId < 0) return Option.none();
return Option.map(commandLine, (command) => ({
pid: record.ProcessId,
ppid: record.ParentProcessId,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
status: record.Status && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
command,
}));
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
return Option.match(decodeWindowsProcessJson(output), {
onNone: () => [],
onSome: (parsed) => {
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((value) =>
Option.match(
Option.flatMap(decodeWindowsProcessRecord(value), normalizeWindowsProcessRow),
{
onNone: () => [],
onSome: (row) => [row],
},
),
);
},
});
}
export function buildDescendantEntries(
+57
View File
@@ -32,6 +32,63 @@ describe("imageMime", () => {
});
});
it("rejects payload with characters outside the base64 alphabet", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVs!bG8=")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGVs,bG8=")).toBeNull();
});
it("rejects structurally malformed base64", () => {
// '=' before the trailing padding position
expect(parseBase64DataUrl("data:image/png;base64,AB=CD===")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64,SGV=bG8=")).toBeNull();
// more than two padding characters
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8=====AAA")).toBeNull();
// length not a multiple of 4
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8")).toBeNull();
});
it("accepts base64 with one or two trailing padding characters", () => {
expect(parseBase64DataUrl("data:image/png;base64,SGVsbA==")).toEqual({
mimeType: "image/png",
base64: "SGVsbA==",
});
expect(parseBase64DataUrl("data:image/png;base64,SGVsbG8h")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8h",
});
});
it("rejects empty and whitespace-only payloads", () => {
expect(parseBase64DataUrl("data:image/png;base64,")).toBeNull();
expect(parseBase64DataUrl("data:image/png;base64, \r\n")).toBeNull();
});
it("parses a case-insensitive scheme and mime type", () => {
expect(parseBase64DataUrl("DATA:IMAGE/PNG;BASE64,SGVsbG8=")).toEqual({
mimeType: "image/png",
base64: "SGVsbG8=",
});
});
it("parses a multi-megabyte payload from a deep call stack", () => {
// Regression: matching the payload with a regex borrowed the JS call
// stack, so a ~10 MB image parsed inside fiber execution threw
// "RangeError: Maximum call stack size exceeded".
const dataUrl = `data:image/png;base64,${"A".repeat(14_000_000)}`;
const atDepth = (depth: number): ReturnType<typeof parseBase64DataUrl> =>
depth === 0 ? parseBase64DataUrl(dataUrl) : atDepth(depth - 1);
const findMaxDepth = (depth: number): number => {
try {
return findMaxDepth(depth + 1);
} catch {
return depth;
}
};
const result = atDepth(Math.floor(findMaxDepth(0) * 0.85));
expect(result?.mimeType).toBe("image/png");
expect(result?.base64.length).toBe(14_000_000);
});
it("does not read inherited keys from mime extension map", () => {
expect(inferImageExtension({ mimeType: "constructor" })).toBe(".bin");
});
+63 -8
View File
@@ -29,17 +29,43 @@ export const SAFE_IMAGE_FILE_EXTENSIONS = new Set([
".webp",
]);
// Whether `code` is a character the base64 payload may contain, aside from
// the whitespace handled separately below.
function isBase64Char(code: number): boolean {
return (
(code >= 0x61 && code <= 0x7a) || // a-z
(code >= 0x41 && code <= 0x5a) || // A-Z
(code >= 0x30 && code <= 0x39) || // 0-9
code === 0x2b || // +
code === 0x2f || // /
code === 0x3d // =
);
}
function isBase64Whitespace(code: number): boolean {
return code === 0x0d || code === 0x0a || code === 0x20; // \r \n space
}
// Data URLs carry the full image payload, so this parser must never run a
// regex across the payload: V8's regex engine borrows the JS call stack, and
// matching a multi-megabyte string from a deep call stack (e.g. inside fiber
// execution) throws "Maximum call stack size exceeded".
export function parseBase64DataUrl(
dataUrl: string,
): { readonly mimeType: string; readonly base64: string } | null {
const match = /^data:([^,]+),([a-z0-9+/=\r\n ]+)$/i.exec(dataUrl.trim());
if (!match) return null;
const trimmed = dataUrl.trim();
if (trimmed.slice(0, 5).toLowerCase() !== "data:") return null;
const commaIndex = trimmed.indexOf(",");
if (commaIndex === -1) return null;
const header = trimmed.slice(5, commaIndex);
if (header.length === 0) return null;
const headerParts: Array<string> = [];
for (const part of (match[1] ?? "").split(";")) {
const trimmed = part.trim();
if (trimmed.length > 0) {
headerParts.push(trimmed);
for (const part of header.split(";")) {
const partTrimmed = part.trim();
if (partTrimmed.length > 0) {
headerParts.push(partTrimmed);
}
}
if (headerParts.length < 2) {
@@ -51,8 +77,37 @@ export function parseBase64DataUrl(
}
const mimeType = headerParts[0]?.toLowerCase();
const base64 = match[2]?.replace(/\s+/g, "");
if (!mimeType || !base64) return null;
if (!mimeType) return null;
const payload = trimmed.slice(commaIndex + 1);
const runs: Array<string> = [];
let runStart = -1;
for (let index = 0; index < payload.length; index += 1) {
const code = payload.charCodeAt(index);
if (isBase64Char(code)) {
if (runStart === -1) runStart = index;
continue;
}
if (!isBase64Whitespace(code)) return null;
if (runStart !== -1) {
runs.push(payload.slice(runStart, index));
runStart = -1;
}
}
if (runStart !== -1) {
runs.push(payload.slice(runStart));
}
const base64 = runs.length === 1 ? runs[0]! : runs.join("");
if (base64.length === 0 || base64.length % 4 !== 0) return null;
const firstPad = base64.indexOf("=");
if (firstPad !== -1) {
// '=' is only valid as one or two trailing padding characters; Node's
// decoder would otherwise silently truncate at the first '='.
if (base64.length - firstPad > 2) return null;
for (let index = firstPad; index < base64.length; index += 1) {
if (base64.charCodeAt(index) !== 0x3d) return null;
}
}
return { mimeType, base64 };
}
+22
View File
@@ -411,6 +411,28 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("replacing with a rule that already exists elsewhere does not duplicate it", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
yield* writeKeybindingsConfig(keybindingsConfigPath, [
{ key: "mod+r", command: "script.run-tests.run" },
{ key: "mod+alt+r", command: "script.run-tests.run" },
]);
yield* Effect.gen(function* () {
const keybindings = yield* Keybindings.Keybindings;
return yield* keybindings.upsertKeybindingRule({
key: "mod+alt+r",
command: "script.run-tests.run",
replace: { key: "mod+r", command: "script.run-tests.run" },
});
});
const persisted = yield* readKeybindingsConfig(keybindingsConfigPath);
const persistedView = persisted.map(({ key, command }) => ({ key, command }));
assert.deepEqual(persistedView, [{ key: "mod+alt+r", command: "script.run-tests.run" }]);
}).pipe(Effect.provide(makeKeybindingsLayer())),
);
it.effect("removes only the targeted custom keybinding", () =>
Effect.gen(function* () {
const { keybindingsConfigPath } = yield* ServerConfig.ServerConfig;
+3 -1
View File
@@ -644,7 +644,9 @@ const make = Effect.gen(function* () {
const nextConfig = [
...customConfig.filter((entry) => {
if (replaceTarget) {
return !isSameKeybindingRule(entry, replaceTarget);
return (
!isSameKeybindingRule(entry, replaceTarget) && !isSameKeybindingRule(entry, rule)
);
}
return !isSameKeybindingRule(entry, rule);
}),
@@ -0,0 +1,73 @@
import { describe, expect, it } from "vite-plus/test";
import {
CommandId,
type ClientOrchestrationCommand,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import { canonicalizeClientCommandTimestamps } from "./Normalizer.ts";
const clientCreatedAt = "2031-01-01T00:00:00.000Z";
const serverReceivedAt = "2026-07-18T00:00:00.000Z";
describe("canonicalizeClientCommandTimestamps", () => {
it("replaces a client command timestamp with the server receipt timestamp", () => {
const command: ClientOrchestrationCommand = {
type: "project.create",
commandId: CommandId.make("command-1"),
projectId: ProjectId.make("project-1"),
title: "Clock-safe project",
workspaceRoot: "/tmp/clock-safe-project",
createdAt: clientCreatedAt,
};
expect(canonicalizeClientCommandTimestamps(command, serverReceivedAt)).toEqual({
...command,
createdAt: serverReceivedAt,
});
});
it("replaces both timestamps when the first turn bootstraps a thread", () => {
const command: ClientOrchestrationCommand = {
type: "thread.turn.start",
commandId: CommandId.make("command-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: MessageId.make("message-1"),
role: "user",
text: "Start a thread",
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: ProjectId.make("project-1"),
title: "Clock-safe thread",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: clientCreatedAt,
},
},
createdAt: clientCreatedAt,
};
const result = canonicalizeClientCommandTimestamps(command, serverReceivedAt);
expect(result.type).toBe("thread.turn.start");
if (result.type !== "thread.turn.start") {
throw new Error("Expected a thread.turn.start command");
}
expect(result.createdAt).toBe(serverReceivedAt);
expect(result.bootstrap?.createThread?.createdAt).toBe(serverReceivedAt);
});
});
+49 -14
View File
@@ -1,8 +1,10 @@
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import {
type ClientOrchestrationCommand,
type IsoDateTime,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
@@ -13,8 +15,38 @@ import { ServerConfig } from "../config.ts";
import { parseBase64DataUrl } from "../imageMime.ts";
import * as WorkspacePaths from "../workspace/WorkspacePaths.ts";
export const canonicalizeClientCommandTimestamps = (
command: ClientOrchestrationCommand,
receivedAt: IsoDateTime,
): ClientOrchestrationCommand => {
const canonicalCommand =
"createdAt" in command
? {
...command,
createdAt: receivedAt,
}
: command;
if (canonicalCommand.type !== "thread.turn.start" || !canonicalCommand.bootstrap?.createThread) {
return canonicalCommand;
}
return {
...canonicalCommand,
bootstrap: {
...canonicalCommand.bootstrap,
createThread: {
...canonicalCommand.bootstrap.createThread,
createdAt: receivedAt,
},
},
};
};
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
Effect.gen(function* () {
const receivedAt = DateTime.formatIso(yield* DateTime.now);
const canonicalCommand = canonicalizeClientCommandTimestamps(command, receivedAt);
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
@@ -47,30 +79,33 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
),
);
if (command.type === "project.create") {
if (canonicalCommand.type === "project.create") {
return {
...command,
...canonicalCommand,
workspaceRoot: yield* normalizeProjectWorkspaceRootForCreate(
command.workspaceRoot,
command.createWorkspaceRootIfMissing,
canonicalCommand.workspaceRoot,
canonicalCommand.createWorkspaceRootIfMissing,
),
createWorkspaceRootIfMissing: command.createWorkspaceRootIfMissing === true,
createWorkspaceRootIfMissing: canonicalCommand.createWorkspaceRootIfMissing === true,
} satisfies OrchestrationCommand;
}
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
if (
canonicalCommand.type === "project.meta.update" &&
canonicalCommand.workspaceRoot !== undefined
) {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
...canonicalCommand,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(canonicalCommand.workspaceRoot),
} satisfies OrchestrationCommand;
}
if (command.type !== "thread.turn.start") {
return command as OrchestrationCommand;
if (canonicalCommand.type !== "thread.turn.start") {
return canonicalCommand as OrchestrationCommand;
}
const normalizedAttachments = yield* Effect.forEach(
command.message.attachments,
canonicalCommand.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
@@ -87,7 +122,7 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
});
}
const attachmentId = createAttachmentId(command.threadId);
const attachmentId = createAttachmentId(canonicalCommand.threadId);
if (!attachmentId) {
return yield* new OrchestrationDispatchCommandError({
message: "Failed to create a safe attachment id.",
@@ -135,9 +170,9 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
);
return {
...command,
...canonicalCommand,
message: {
...command.message,
...canonicalCommand.message,
attachments: normalizedAttachments,
},
} satisfies OrchestrationCommand;
@@ -1,7 +1,9 @@
import * as Arr from "effect/Array";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -280,18 +282,30 @@ export const make = Effect.gen(function* () {
),
),
Effect.flatMap((rows) =>
// Skip rows that no longer decode (e.g. written by an older build)
// instead of failing the whole list — one stale row must not disable
// every consumer that enumerates sessions, such as the reaper.
Effect.forEach(rows, (row) =>
decodeRuntimeRow(row).pipe(
Effect.mapError((cause) =>
PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
{ threadId: row.threadId },
),
Effect.map(Option.some),
Effect.catch((cause) =>
Effect.logWarning("provider.session.runtime.row-skipped", {
threadId: row.threadId,
error: PersistenceDecodeError.fromSchemaError(
"ProviderSessionRuntimeRepository.list:decodeRows",
cause,
{ threadId: row.threadId },
).message,
}).pipe(Effect.as(Option.none<ProviderSessionRuntime>())),
),
),
),
),
Effect.map((decoded) =>
Arr.filterMap(decoded, (row) =>
Option.isSome(row) ? Result.succeed(row.value) : Result.failVoid,
),
),
);
const deleteByThreadId: ProviderSessionRuntimeRepository["Service"]["deleteByThreadId"] = (
@@ -182,7 +182,7 @@ describe("persistence error correlation", () => {
}).pipe(Effect.provide(authPairingLinkLayer)),
);
it.effect("correlates provider runtime SQL and per-row decode failures by thread", () =>
it.effect("skips undecodable provider runtime rows and correlates SQL failures by thread", () =>
Effect.gen(function* () {
const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
const sql = yield* SqlClient.SqlClient;
@@ -215,16 +215,24 @@ describe("persistence error correlation", () => {
)
`;
const decodeError = yield* Effect.flip(runtimes.list());
assert.instanceOf(decodeError, PersistenceErrors.PersistenceDecodeError);
assert.deepStrictEqual(decodeError.correlation, { threadId });
assert.equal(
decodeError.message,
`Decode error in ProviderSessionRuntimeRepository.list:decodeRows: ${decodeError.issue}`,
const validThreadId = ThreadId.make("thread-valid");
yield* runtimes.upsert({
threadId: validThreadId,
providerName: "codex",
providerInstanceId: null,
adapterKey: "codex",
runtimeMode: "full-access",
status: "running",
lastSeenAt,
resumeCursor: null,
runtimePayload: null,
});
const listed = yield* runtimes.list();
assert.deepStrictEqual(
listed.map((runtime) => runtime.threadId),
[validThreadId],
);
assert.notInclude(decodeError.issue, runtimePayload);
assert.notInclude(decodeError.message, runtimePayload);
assert.notInclude(decodeError.message, lastSeenAt);
yield* sql`DROP TABLE provider_session_runtime`;
const sqlFailure = yield* Effect.flip(
@@ -1,3 +1,5 @@
import type { ProviderInteractionMode } from "@t3tools/contracts";
const T3_CODE_BROWSER_TOOL_INSTRUCTIONS = `
## T3 Code collaborative browser
@@ -145,3 +147,26 @@ The \`request_user_input\` tool is unavailable in Default mode. If you call it w
In Default mode, strongly prefer making reasonable assumptions and executing the user's request rather than stopping to ask questions. If you absolutely must ask a question because the answer cannot be discovered from local context and a reasonable assumption would be risky, ask the user directly with a concise plain-text question. Never write a multiple choice question as a textual assistant message.
${T3_CODE_BROWSER_TOOL_INSTRUCTIONS}
</collaboration_mode>`;
export interface CodexRuntimeInfo {
readonly model: string;
readonly reasoningEffort: string;
}
// Values come from trusted config, but keep the block single-line regardless.
function toSingleLine(value: string): string {
return value.replaceAll(/\s+/g, " ").trim();
}
export function buildCodexDeveloperInstructions(
interactionMode: ProviderInteractionMode,
runtime: CodexRuntimeInfo,
): string {
const base =
interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS;
return `${base}
<runtime_info>In case you're asked: you are running in T3 Code through the Codex harness, as ${toSingleLine(runtime.model)} with ${toSingleLine(runtime.reasoningEffort)} reasoning effort. No need to mention this otherwise.</runtime_info>`;
}
@@ -119,6 +119,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const path = yield* Path.Path;
const { cwd } = yield* ServerConfig;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
const eventLoggers = yield* ProviderEventLoggers;
@@ -154,11 +155,11 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {
capacity: 1,
timeToLive: CAPABILITIES_PROBE_TTL,
lookup: () =>
probeClaudeCapabilities(effectiveConfig, processEnv).pipe(
probeClaudeCapabilities(effectiveConfig, processEnv, cwd).pipe(
Effect.provideService(Path.Path, path),
),
});
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig);
const capabilitiesCacheKey = yield* makeClaudeCapabilitiesCacheKey(effectiveConfig, cwd);
const checkProvider = checkClaudeProviderStatus(
effectiveConfig,
@@ -34,11 +34,20 @@ it.layer(NodeServices.layer)("ClaudeHome", (it) => {
expect((yield* makeClaudeEnvironment({ homePath })).CLAUDE_CONFIG_DIR).toBe(resolved);
expect(yield* makeClaudeContinuationGroupKey({ homePath })).toBe(`claude:home:${resolved}`);
expect(yield* makeClaudeCapabilitiesCacheKey({ binaryPath: "claude", homePath })).toBe(
`claude\0${resolved}`,
`claude\0${resolved}\0`,
);
}),
);
it.effect("separates capability probes by cwd", () =>
Effect.gen(function* () {
const config = { binaryPath: "claude", homePath: "" };
const first = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-a");
const second = yield* makeClaudeCapabilitiesCacheKey(config, "/repo-b");
expect(first).not.toBe(second);
}),
);
it.effect("keeps continuation compatible across instances with the same Claude HOME", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
@@ -44,8 +44,9 @@ export const makeClaudeContinuationGroupKey = Effect.fn("makeClaudeContinuationG
export const makeClaudeCapabilitiesCacheKey = Effect.fn("makeClaudeCapabilitiesCacheKey")(
function* (
config: Pick<ClaudeSettings, "binaryPath" | "homePath">,
cwd?: string,
): Effect.fn.Return<string, never, Path.Path> {
const resolvedHomePath = yield* resolveClaudeHomePath(config);
return `${config.binaryPath}\0${resolvedHomePath}`;
return `${config.binaryPath}\0${resolvedHomePath}\0${cwd ?? ""}`;
},
);
@@ -114,6 +114,9 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
const sessionsTarget = yield* fileSystem.readLink(path.join(shadowHome, "sessions"));
const configTarget = yield* fileSystem.readLink(path.join(shadowHome, "config.toml"));
const mcpOauthLocksTarget = yield* fileSystem.readLink(
path.join(shadowHome, "mcp-oauth-locks"),
);
const modelsCacheExists = yield* fileSystem.exists(
path.join(shadowHome, "models_cache.json"),
);
@@ -124,12 +127,45 @@ it.layer(NodeServices.layer)("CodexHomeLayout", (it) => {
expect(sessionsTarget).toBe(path.join(sharedHome, "sessions"));
expect(configTarget).toBe(path.join(sharedHome, "config.toml"));
expect(mcpOauthLocksTarget).toBe(path.join(sharedHome, "mcp-oauth-locks"));
expect(modelsCacheExists).toBe(false);
expect(authLinkResult._tag).toBe("Failure");
expect(authContents).toContain("shadow");
}),
);
it.effect("replaces Codex-created local MCP OAuth locks with the shared lock directory", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const sharedHome = yield* makeTempDir("t3code-codex-shared-");
const shadowRoot = yield* makeTempDir("t3code-codex-shadow-root-");
const shadowHome = path.join(shadowRoot, "shadow");
const sharedLocks = path.join(sharedHome, "mcp-oauth-locks");
const shadowLocks = path.join(shadowHome, "mcp-oauth-locks");
yield* writeTextFile(path.join(sharedLocks, "file-store.lock"), "");
yield* writeTextFile(path.join(shadowLocks, "file-store.lock"), "");
const layout = yield* resolveCodexHomeLayout(
decodeCodexSettings({
homePath: sharedHome,
shadowHomePath: shadowHome,
}),
);
yield* materializeCodexShadowHome(layout);
const locksTarget = yield* fileSystem.readLink(shadowLocks);
const sharedLockExists = yield* fileSystem.exists(
path.join(sharedLocks, "file-store.lock"),
);
expect(locksTarget).toBe(sharedLocks);
expect(sharedLockExists).toBe(true);
}),
);
it.effect("accepts Codex-created shadow-local runtime directories", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -26,10 +26,12 @@ const KNOWN_SHARED_DIRECTORIES = [
"plugins",
"cache",
"logs",
"mcp-oauth-locks",
] as const;
const PRIVATE_ENTRY_NAMES = new Set(["auth.json", "models_cache.json"]);
const SHADOW_LOCAL_ENTRY_NAMES = new Set(["log", "memories", "tmp"]);
const REPLACEABLE_SHARED_RUNTIME_DIRECTORIES = new Set(["mcp-oauth-locks"]);
function resolveHomePath(path: Path.Path, value: string | undefined): string {
const expanded =
@@ -225,16 +227,6 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
linkPath: link,
});
if (state._tag === "NotSymlink") {
return yield* new CodexShadowHomeEntryConflictError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
entryName: input.entryName,
linkPath: link,
targetPath: target,
});
}
const createLink = input.fileSystem.symlink(target, link).pipe(
Effect.catchTags({
PlatformError: (cause) =>
@@ -250,6 +242,33 @@ const ensureSymlink = Effect.fn("CodexHomeLayout.ensureSymlink")(function* (inpu
}),
);
if (state._tag === "NotSymlink") {
if (!REPLACEABLE_SHARED_RUNTIME_DIRECTORIES.has(input.entryName)) {
return yield* new CodexShadowHomeEntryConflictError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
entryName: input.entryName,
linkPath: link,
targetPath: target,
});
}
yield* input.fileSystem.remove(link, { recursive: true }).pipe(
Effect.catchTags({
PlatformError: (cause) =>
new CodexShadowHomeFileSystemError({
sharedHomePath: input.sharedHomePath,
effectiveHomePath: input.effectiveHomePath,
operation: "remove",
path: link,
entryName: input.entryName,
cause,
}),
}),
);
return yield* createLink;
}
if (state._tag === "Missing") {
return yield* createLink;
}
@@ -1,5 +1,5 @@
/**
* CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime.
* CursorDriver — `ProviderDriver` for the Cursor Agent (`cursor-agent`) runtime.
*
* Cursor exposes an ACP-based CLI. Model catalog and capability refreshes
* happen during the managed provider status check via Cursor's
@@ -42,7 +42,7 @@ import type { ServerProviderDraft } from "../providerSnapshot.ts";
import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";
import {
makeProviderMaintenanceCapabilities,
makeStaticProviderMaintenanceResolver,
type ProviderMaintenanceCapabilitiesResolver,
resolveProviderMaintenanceCapabilitiesEffect,
} from "../providerMaintenance.ts";
import {
@@ -54,15 +54,16 @@ const decodeCursorSettings = Schema.decodeSync(CursorSettings);
const DRIVER_KIND = ProviderDriverKind.make("cursor");
const SNAPSHOT_REFRESH_INTERVAL = Duration.minutes(5);
const UPDATE = makeStaticProviderMaintenanceResolver(
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
updateExecutable: "agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
}),
);
const UPDATE: ProviderMaintenanceCapabilitiesResolver = {
resolve: (options) =>
makeProviderMaintenanceCapabilities({
provider: DRIVER_KIND,
packageName: null,
updateExecutable: options?.binaryPath?.trim() || "cursor-agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
}),
};
export type CursorDriverEnv =
| ChildProcessSpawner.ChildProcessSpawner
@@ -100,6 +101,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
defaultConfig: (): CursorSettings => decodeCursorSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -132,6 +134,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
const checkProvider = checkCursorProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -84,6 +84,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
defaultConfig: (): GrokSettings => decodeGrokSettings({}),
create: ({ instanceId, displayName, accentColor, environment, enabled, config }) =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const httpClient = yield* HttpClient.HttpClient;
const serverSettings = yield* ServerSettingsService;
@@ -114,6 +115,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {
const checkProvider = checkGrokProviderStatus(effectiveConfig, processEnv).pipe(
Effect.map(stampIdentity),
Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
@@ -583,6 +583,7 @@ function waitForAbortSignal(signal: AbortSignal): Promise<void> {
const probeClaudeCapabilities = (
claudeSettings: ClaudeSettings,
environment?: NodeJS.ProcessEnv,
cwd?: string,
) => {
const abort = new AbortController();
return Effect.gen(function* () {
@@ -602,6 +603,7 @@ const probeClaudeCapabilities = (
settingSources: ["user", "project", "local"],
allowedTools: [],
env: claudeEnvironment,
...(cwd ? { cwd } : {}),
stderr: () => {},
},
});
@@ -4,11 +4,12 @@ import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { describe } from "vite-plus/test";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_MODEL, ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
import {
buildCodexDeveloperInstructions,
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
@@ -118,7 +119,10 @@ describe("buildTurnStartParams", () => {
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
developer_instructions: buildCodexDeveloperInstructions("plan", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
}),
},
},
});
@@ -163,12 +167,31 @@ describe("buildTurnStartParams", () => {
settings: {
model: "gpt-5.3-codex",
reasoning_effort: "medium",
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
developer_instructions: buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
}),
},
},
});
});
it("reports the same fallback model and effort in settings and instructions", () => {
const params = Effect.runSync(
buildTurnStartParams({
threadId: "provider-thread-1",
runtimeMode: "full-access",
prompt: "Go",
interactionMode: "default",
}),
);
const settings = params.collaborationMode?.settings;
NodeAssert.equal(settings?.model, DEFAULT_MODEL);
NodeAssert.equal(settings?.reasoning_effort, "medium");
NodeAssert.ok(settings?.developer_instructions?.includes(`as ${DEFAULT_MODEL} with medium`));
});
it("omits collaboration mode when interaction mode is absent", () => {
const params = Effect.runSync(
buildTurnStartParams({
@@ -194,6 +217,53 @@ describe("buildTurnStartParams", () => {
});
});
describe("buildCodexDeveloperInstructions", () => {
it("appends runtime info after the mode instructions", () => {
const instructions = buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "high",
});
NodeAssert.ok(instructions.startsWith(CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS));
NodeAssert.match(instructions, /T3 Code/);
NodeAssert.match(instructions, /Codex harness/);
NodeAssert.match(instructions, /as gpt-5\.3-codex with high reasoning effort/);
});
it("includes runtime info alongside plan mode instructions", () => {
const instructions = buildCodexDeveloperInstructions("plan", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
});
NodeAssert.ok(instructions.startsWith(CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS));
NodeAssert.match(instructions, /as gpt-5\.3-codex with medium reasoning effort/);
});
it("varies with the model and effort of each turn", () => {
const first = buildCodexDeveloperInstructions("default", {
model: "gpt-5.3-codex",
reasoningEffort: "medium",
});
const second = buildCodexDeveloperInstructions("default", {
model: "gpt-5.4",
reasoningEffort: "high",
});
NodeAssert.notEqual(first, second);
});
it("flattens multiline metadata into single-line runtime info", () => {
const instructions = buildCodexDeveloperInstructions("default", {
model: "gpt\n5.3\ncodex",
reasoningEffort: " high\neffort ",
});
NodeAssert.match(instructions, /as gpt 5\.3 codex with high effort reasoning effort/);
NodeAssert.doesNotMatch(instructions, /<runtime_info>[^<]*\n/);
});
});
describe("T3 browser developer instructions", () => {
it("prefers the product-native preview tools in both collaboration modes", () => {
for (const instructions of [
@@ -37,10 +37,7 @@ import * as EffectCodexSchema from "effect-codex-app-server/schema";
import { buildCodexInitializeParams } from "./CodexProvider.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import {
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
} from "../CodexDeveloperInstructions.ts";
import { buildCodexDeveloperInstructions } from "../CodexDeveloperInstructions.ts";
const decodeV2TurnStartResponse = Schema.decodeUnknownEffect(EffectCodexSchema.V2TurnStartResponse);
const PROVIDER = ProviderDriverKind.make("codex");
@@ -331,15 +328,16 @@ function buildCodexCollaborationMode(input: {
return undefined;
}
const model = normalizeCodexModelSlug(input.model) ?? DEFAULT_MODEL;
const reasoningEffort = input.effort ?? "medium";
return {
mode: input.interactionMode,
settings: {
model,
reasoning_effort: input.effort ?? "medium",
developer_instructions:
input.interactionMode === "plan"
? CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS
: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
reasoning_effort: reasoningEffort,
developer_instructions: buildCodexDeveloperInstructions(input.interactionMode, {
model,
reasoningEffort,
}),
},
};
}
@@ -228,7 +228,7 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
assert.isDefined(delta);
if (delta?.type === "content.delta") {
assert.equal(delta.payload.delta, "hello from mock");
assert.match(String(delta.itemId), /^assistant:mock-session-1:segment:0$/);
assert.match(String(delta.itemId), /^assistant:mock-session-1:runtime:[^:]+:segment:0$/);
}
const assistantCompleted = runtimeEvents.find(
@@ -687,7 +687,10 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
if (contentDelta?.type === "content.delta") {
assert.equal(String(contentDelta.turnId), String(turn.turnId));
assert.equal(contentDelta.payload.delta, "hello from mock");
assert.equal(String(contentDelta.itemId), "assistant:mock-session-1:segment:0");
assert.match(
String(contentDelta.itemId),
/^assistant:mock-session-1:runtime:[^:]+:segment:0$/,
);
}
});
@@ -558,6 +558,7 @@ export function makeCursorAdapter(
: {}),
...acpNativeLoggers,
}).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
@@ -1,6 +1,7 @@
import * as NodeOS from "node:os";
import * as NodeServices from "@effect/platform-node/NodeServices";
import type * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
@@ -28,7 +29,7 @@ const runNode = <A, E>(
effect: Effect.Effect<
A,
E,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
>,
): Promise<A> => Effect.runPromise(effect.pipe(Effect.provide(NodeServices.layer)));
@@ -294,7 +295,7 @@ const parameterizedClaudeModelOptionConfigOptions = [
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
binaryPath: "cursor-agent",
apiEndpoint: "",
customModels: [],
};
@@ -11,6 +11,7 @@ import type {
import { ProviderDriverKind } from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -992,7 +993,7 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | FileSystem.FileSystem | Path.Path
> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = getCursorFallbackModels(cursorSettings);
@@ -596,6 +596,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
: {}),
...acpNativeLoggers,
}).pipe(
Effect.provideService(Crypto.Crypto, crypto),
Effect.provideService(Scope.Scope, sessionScope),
Effect.mapError(
(cause) =>
@@ -7,6 +7,7 @@ import {
} from "@t3tools/contracts";
import type * as EffectAcpSchema from "effect-acp/schema";
import { causeErrorTag } from "@t3tools/shared/observability";
import * as Crypto from "effect/Crypto";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -167,7 +168,11 @@ const runGrokVersionCommand = (
export const checkGrokProviderStatus = Effect.fn("checkGrokProviderStatus")(function* (
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ServerProviderDraft, never, ChildProcessSpawner.ChildProcessSpawner> {
): Effect.fn.Return<
ServerProviderDraft,
never,
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
> {
const checkedAt = DateTime.formatIso(yield* DateTime.now);
const fallbackModels = grokModelsFromSettings(grokSettings.customModels);
@@ -248,6 +248,38 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("fails sendTurn for missing sessions through the typed error channel", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const result = yield* adapter
.sendTurn({
threadId: asThreadId("thread-opencode-missing-send"),
input: "hello",
attachments: [],
})
.pipe(Effect.result);
NodeAssert.equal(result._tag, "Failure");
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
NodeAssert.equal(result.failure.provider, "opencode");
NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-send");
}),
);
it.effect("fails stopSession for missing sessions through the typed error channel", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const result = yield* adapter
.stopSession(asThreadId("thread-opencode-missing-stop"))
.pipe(Effect.result);
NodeAssert.equal(result._tag, "Failure");
NodeAssert.equal(result.failure._tag, "ProviderAdapterSessionNotFoundError");
NodeAssert.equal(result.failure.provider, "opencode");
NodeAssert.equal(result.failure.threadId, "thread-opencode-missing-stop");
}),
);
it.effect("stops a configured-server session without trying to own server lifecycle", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
@@ -228,28 +228,25 @@ function appendTurnItem(
resolveTurnSnapshot(context, turnId).items.push(item);
}
function ensureSessionContext(
const ensureSessionContext = Effect.fn("ensureSessionContext")(function* (
sessions: ReadonlyMap<ThreadId, OpenCodeSessionContext>,
threadId: ThreadId,
): OpenCodeSessionContext {
) {
const session = sessions.get(threadId);
if (!session) {
throw new ProviderAdapterSessionNotFoundError({
return yield* new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
});
}
// `ensureSessionContext` is a sync gate used from both sync helpers and
// Effect bodies. `Ref.getUnsafe` is an atomic read of the backing cell —
// no fiber suspension required, which keeps this callable everywhere.
if (Ref.getUnsafe(session.stopped)) {
throw new ProviderAdapterSessionClosedError({
if (yield* Ref.get(session.stopped)) {
return yield* new ProviderAdapterSessionClosedError({
provider: PROVIDER,
threadId,
});
}
return session;
}
});
function normalizeQuestionRequest(request: QuestionRequest): ReadonlyArray<UserInputQuestion> {
return request.questions.map((question, index) => ({
@@ -1167,7 +1164,7 @@ export function makeOpenCodeAdapter(
);
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = ensureSessionContext(sessions, input.threadId);
const context = yield* ensureSessionContext(sessions, input.threadId);
// A sendTurn while a turn is active is a steer: OpenCode queues the
// prompt into the busy session and the work continues as one turn, so
// the active turn id is reused instead of opening a new turn.
@@ -1291,7 +1288,7 @@ export function makeOpenCodeAdapter(
const interruptTurn: OpenCodeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, turnId) {
const context = ensureSessionContext(sessions, threadId);
const context = yield* ensureSessionContext(sessions, threadId);
yield* runOpenCodeSdk("session.abort", () =>
context.client.session.abort({ sessionID: context.openCodeSessionId }),
).pipe(Effect.mapError(toRequestError));
@@ -1313,7 +1310,7 @@ export function makeOpenCodeAdapter(
const respondToRequest: OpenCodeAdapterShape["respondToRequest"] = Effect.fn(
"respondToRequest",
)(function* (threadId, requestId, decision) {
const context = ensureSessionContext(sessions, threadId);
const context = yield* ensureSessionContext(sessions, threadId);
if (!context.pendingPermissions.has(requestId)) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
@@ -1333,7 +1330,7 @@ export function makeOpenCodeAdapter(
const respondToUserInput: OpenCodeAdapterShape["respondToUserInput"] = Effect.fn(
"respondToUserInput",
)(function* (threadId, requestId, answers) {
const context = ensureSessionContext(sessions, threadId);
const context = yield* ensureSessionContext(sessions, threadId);
const request = context.pendingQuestions.get(requestId);
if (!request) {
return yield* new ProviderAdapterRequestError({
@@ -1355,7 +1352,7 @@ export function makeOpenCodeAdapter(
function* (threadId) {
const context = sessions.get(threadId);
if (!context) {
throw new ProviderAdapterSessionNotFoundError({
return yield* new ProviderAdapterSessionNotFoundError({
provider: PROVIDER,
threadId,
});
@@ -1385,7 +1382,7 @@ export function makeOpenCodeAdapter(
const readThread: OpenCodeAdapterShape["readThread"] = Effect.fn("readThread")(
function* (threadId) {
const context = ensureSessionContext(sessions, threadId);
const context = yield* ensureSessionContext(sessions, threadId);
const messages = yield* runOpenCodeSdk("session.messages", () =>
context.client.session.messages({
sessionID: context.openCodeSessionId,
@@ -1411,7 +1408,7 @@ export function makeOpenCodeAdapter(
const rollbackThread: OpenCodeAdapterShape["rollbackThread"] = Effect.fn("rollbackThread")(
function* (threadId, numTurns) {
const context = ensureSessionContext(sessions, threadId);
const context = yield* ensureSessionContext(sessions, threadId);
const messages = yield* runOpenCodeSdk("session.messages", () =>
context.client.session.messages({
sessionID: context.openCodeSessionId,
@@ -76,7 +76,7 @@ const makeClaudeConfig = (overrides: Partial<ClaudeSettings>): ClaudeSettings =>
const makeCursorConfig = (overrides: Partial<CursorSettings>): CursorSettings => ({
enabled: false,
binaryPath: "agent",
binaryPath: "cursor-agent",
apiEndpoint: "",
customModels: [],
...overrides,
@@ -1396,7 +1396,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te
Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
if (command === "agent") {
if (command === "cursor-agent") {
cursorSpawned = true;
}
const joined = args.join(" ");
@@ -116,6 +116,43 @@ describe("AcpSessionRuntime", () => {
),
);
it.effect("keeps assistant item IDs unique when a provider session restarts", () => {
const collectFirstAssistantItemId = Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
expect(started.sessionId).toBe("mock-session-1");
yield* runtime.prompt({
prompt: [{ type: "text", text: "hi" }],
});
const events = Array.from(yield* Stream.runCollect(Stream.take(runtime.getEvents(), 4)));
const assistantStart = events.find((event) => event._tag === "AssistantItemStarted");
expect(assistantStart?._tag).toBe("AssistantItemStarted");
return assistantStart?._tag === "AssistantItemStarted" ? assistantStart.itemId : "";
}).pipe(
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: mockAgentCommand,
args: mockAgentArgs,
},
cwd: process.cwd(),
clientInfo: { name: "t3-test", version: "0.0.0" },
authMethodId: "test",
}),
),
Effect.scoped,
);
return Effect.gen(function* () {
const beforeRestart = yield* collectFirstAssistantItemId;
const afterRestart = yield* collectFirstAssistantItemId;
expect(afterRestart).not.toBe(beforeRestart);
}).pipe(Effect.provide(NodeServices.layer));
});
it.effect("drops session updates emitted for a child ACP session", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
@@ -1,6 +1,7 @@
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
@@ -270,14 +271,24 @@ export const make = (
): Effect.Effect<
AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runtimeScope = yield* Scope.Scope;
const eventQueue = yield* Queue.unbounded<AcpSessionRuntimeEvent>();
const modeStateRef = yield* Ref.make<AcpSessionModeState | undefined>(undefined);
const toolCallsRef = yield* Ref.make(new Map<string, AcpToolCallState>());
const assistantItemRuntimeId = yield* crypto.randomUUIDv4.pipe(
Effect.mapError(
(cause) =>
new EffectAcpErrors.AcpTransportError({
detail: "Failed to generate an ACP assistant item runtime identifier.",
cause,
}),
),
);
const assistantSegmentRef = yield* Ref.make<AcpAssistantSegmentState>({ nextSegmentIndex: 0 });
const configOptionsRef = yield* Ref.make(sessionConfigOptionsFromSetup(undefined));
const startStateRef = yield* Ref.make<AcpStartState>({ _tag: "NotStarted" });
@@ -387,6 +398,7 @@ export const make = (
modeStateRef,
toolCallsRef,
assistantSegmentRef,
assistantItemRuntimeId,
params: notification,
});
}),
@@ -802,7 +814,7 @@ export const layer = (
): Layer.Layer<
AcpSessionRuntime,
EffectAcpErrors.AcpError,
ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner | Crypto.Crypto
> => Layer.effect(AcpSessionRuntime, make(options));
function sessionConfigOptionsFromSetup(
@@ -834,12 +846,14 @@ const handleSessionUpdate = ({
modeStateRef,
toolCallsRef,
assistantSegmentRef,
assistantItemRuntimeId,
params,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly modeStateRef: Ref.Ref<AcpSessionModeState | undefined>;
readonly toolCallsRef: Ref.Ref<Map<string, AcpToolCallState>>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly assistantItemRuntimeId: string;
readonly params: EffectAcpSchema.SessionNotification;
}): Effect.Effect<void> =>
Effect.gen(function* () {
@@ -887,6 +901,7 @@ const handleSessionUpdate = ({
queue,
assistantSegmentRef,
sessionId: params.sessionId,
assistantItemRuntimeId,
});
yield* Queue.offer(queue, {
...event,
@@ -924,17 +939,19 @@ function shouldEmitToolCallUpdate(
return previous === undefined || previous.title !== next.title || previous.detail !== next.detail;
}
const assistantItemId = (sessionId: string, segmentIndex: number) =>
`assistant:${sessionId}:segment:${segmentIndex}`;
const assistantItemId = (sessionId: string, runtimeId: string, segmentIndex: number) =>
`assistant:${sessionId}:runtime:${runtimeId}:segment:${segmentIndex}`;
const ensureActiveAssistantSegment = ({
queue,
assistantSegmentRef,
sessionId,
assistantItemRuntimeId,
}: {
readonly queue: Queue.Queue<AcpSessionRuntimeEvent>;
readonly assistantSegmentRef: Ref.Ref<AcpAssistantSegmentState>;
readonly sessionId: string;
readonly assistantItemRuntimeId: string;
}) =>
Ref.modify<AcpAssistantSegmentState, EnsureActiveAssistantSegmentResult>(
assistantSegmentRef,
@@ -942,7 +959,7 @@ const ensureActiveAssistantSegment = ({
if (current.activeItemId) {
return [{ itemId: current.activeItemId }, current] as const;
}
const itemId = assistantItemId(sessionId, current.nextSegmentIndex);
const itemId = assistantItemId(sessionId, assistantItemRuntimeId, current.nextSegmentIndex);
return [
{
itemId,
@@ -1,5 +1,5 @@
/**
* Optional integration check against a real `agent acp` install.
* Optional integration check against a real `cursor-agent acp` install.
* Enable with: T3_CURSOR_ACP_PROBE=1 bun run test --filter CursorAcpCliProbe
*/
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -12,7 +12,7 @@ import type * as EffectAcpSchema from "effect-acp/schema";
import * as AcpSessionRuntime from "./AcpSessionRuntime.ts";
describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe", () => {
it.effect("initialize and authenticate against real agent acp", () =>
it.effect("initialize and authenticate against real cursor-agent acp", () =>
Effect.gen(function* () {
const runtime = yield* AcpSessionRuntime.AcpSessionRuntime;
const started = yield* runtime.start();
@@ -21,7 +21,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
Effect.provide(
AcpSessionRuntime.layer({
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -77,7 +77,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -133,7 +133,7 @@ describe.runIf(process.env.T3_CURSOR_ACP_PROBE === "1")("Cursor ACP CLI probe",
AcpSessionRuntime.layer({
authMethodId: "cursor_login",
spawn: {
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: process.cwd(),
},
@@ -53,7 +53,7 @@ const parameterizedGpt54ConfigOptions: ReadonlyArray<EffectAcpSchema.SessionConf
describe("buildCursorAcpSpawnInput", () => {
it("builds the default Cursor ACP command", () => {
expect(buildCursorAcpSpawnInput(undefined, "/tmp/project")).toEqual({
command: "agent",
command: "cursor-agent",
args: ["acp"],
cwd: "/tmp/project",
});
@@ -1,4 +1,5 @@
import { type CursorSettings, type ProviderOptionSelection } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
@@ -35,7 +36,7 @@ export function buildCursorAcpSpawnInput(
environment?: NodeJS.ProcessEnv,
): AcpSessionRuntime.AcpSpawnInput {
return {
command: cursorSettings?.binaryPath || "agent",
command: cursorSettings?.binaryPath || "cursor-agent",
args: [
...(cursorSettings?.apiEndpoint ? (["-e", cursorSettings.apiEndpoint] as const) : []),
"acp",
@@ -50,7 +51,7 @@ export const makeCursorAcpRuntime = (
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
@@ -1,4 +1,5 @@
import { type GrokSettings, ProviderDriverKind } from "@t3tools/contracts";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Scope from "effect/Scope";
@@ -55,7 +56,7 @@ export const makeGrokAcpRuntime = (
): Effect.Effect<
AcpSessionRuntime.AcpSessionRuntime["Service"],
EffectAcpErrors.AcpError,
Scope.Scope
Crypto.Crypto | Scope.Scope
> =>
Effect.gen(function* () {
const acpContext = yield* Layer.build(
@@ -48,7 +48,7 @@ function lifecycleFor(provider: ProviderDriverKind): ProviderMaintenanceCapabili
return makeProviderMaintenanceCapabilities({
provider,
packageName: null,
updateExecutable: "agent",
updateExecutable: "cursor-agent",
updateArgs: ["update"],
updateLockKey: "cursor-agent",
});
@@ -226,7 +226,7 @@ describe("providerMaintenanceRunner", () => {
const result = yield* updater.updateProvider(CURSOR_DRIVER);
assert.deepStrictEqual(calls, [
{
command: "agent",
command: "cursor-agent",
args: ["update"],
},
]);
+57
View File
@@ -1334,6 +1334,63 @@ it.layer(
}),
);
it.effect("strips AppImage runtime env from terminal sessions", () =>
Effect.gen(function* () {
const appDir = "/tmp/.mount_T3Codeabc123";
const { manager, ptyAdapter } = yield* createManager(5, {
env: {
APPIMAGE: "/home/user/T3-Code.AppImage",
APPDIR: appDir,
ARGV0: "/home/user/T3-Code.AppImage",
OWD: "/home/user/project",
PATH: `${appDir}/usr/bin:${appDir}:/usr/local/bin:/usr/bin:/bin`,
LD_LIBRARY_PATH: `${appDir}/usr/lib:/home/user/.local/lib`,
TEST_TERMINAL_KEEP: "keep-me",
},
});
yield* manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
// AppImage runtime markers must never reach the PTY — tools inside the
// terminal otherwise resolve against the AppImage mount (e.g. PHP_BINARY
// reporting the AppImage path instead of the real binary).
expect(spawnInput.env.APPIMAGE).toBeUndefined();
expect(spawnInput.env.APPDIR).toBeUndefined();
expect(spawnInput.env.ARGV0).toBeUndefined();
expect(spawnInput.env.OWD).toBeUndefined();
// PATH/LD_LIBRARY_PATH keep the user's real entries but drop the AppImage
// mount segments that the runtime prepended.
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
// Unrelated host vars still pass through untouched.
expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me");
}),
);
it.effect("leaves the environment untouched when not launched from an AppImage", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager(5, {
env: {
PATH: "/usr/local/bin:/usr/bin:/bin",
LD_LIBRARY_PATH: "/home/user/.local/lib",
// Without APPIMAGE/APPDIR set, OWD is an ordinary variable and must
// not be stripped — only an AppImage launch gives it special meaning.
OWD: "/home/user/keep-this",
},
});
yield* manager.open(openInput());
const spawnInput = ptyAdapter.spawnInputs[0];
expect(spawnInput).toBeDefined();
if (!spawnInput) return;
expect(spawnInput.env.PATH).toBe("/usr/local/bin:/usr/bin:/bin");
expect(spawnInput.env.LD_LIBRARY_PATH).toBe("/home/user/.local/lib");
expect(spawnInput.env.OWD).toBe("/home/user/keep-this");
}),
);
it.effect("injects runtime env overrides into spawned terminals", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
+48 -1
View File
@@ -1065,6 +1065,53 @@ function shouldExcludeTerminalEnvKey(key: string): boolean {
return TERMINAL_ENV_BLOCKLIST.has(normalizedKey);
}
// Marker variables the AppImage runtime injects into the process it launches.
// They describe the AppImage itself, not the user's session, so terminals must
// not inherit them.
const APPIMAGE_RUNTIME_ENV_KEYS = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"] as const;
// PATH-style variables the AppImage runtime prepends with its temporary mount
// (e.g. /tmp/.mount_T3-XXXX/usr/bin). Only the mount segments are dropped; the
// user's real entries are preserved.
const APPIMAGE_PATH_LIKE_ENV_KEYS = ["PATH", "LD_LIBRARY_PATH"] as const;
function isPathSegmentUnderAppDir(segment: string, appDir: string): boolean {
return segment === appDir || segment.startsWith(`${appDir}/`);
}
// On Linux AppImage builds the runtime mounts the app under a temporary dir and
// injects APPIMAGE/APPDIR/ARGV0/OWD plus mount entries on PATH/LD_LIBRARY_PATH.
// The integrated terminal inherits the server process environment, so without
// this scrub those leak into the PTY and tools resolve against the AppImage
// mount instead of the user's real environment (e.g. `php` reporting
// PHP_BINARY as the AppImage path). See issue #1699. The scrub is gated on an
// actual AppImage launch so non-AppImage environments are left untouched.
function stripAppImageRuntimeEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
if (env.APPIMAGE === undefined && env.APPDIR === undefined) return env;
const scrubbed: NodeJS.ProcessEnv = { ...env };
for (const key of APPIMAGE_RUNTIME_ENV_KEYS) {
delete scrubbed[key];
}
const appDir = env.APPDIR?.replace(/\/+$/, "");
if (appDir) {
for (const key of APPIMAGE_PATH_LIKE_ENV_KEYS) {
const value = scrubbed[key];
if (value === undefined) continue;
const kept = value
.split(":")
.filter((segment) => segment.length > 0 && !isPathSegmentUnderAppDir(segment, appDir));
if (kept.length > 0) {
scrubbed[key] = kept.join(":");
} else {
delete scrubbed[key];
}
}
}
return scrubbed;
}
function createTerminalSpawnEnv(
baseEnv: NodeJS.ProcessEnv,
runtimeEnv?: Record<string, string> | null,
@@ -1080,7 +1127,7 @@ function createTerminalSpawnEnv(
spawnEnv[key] = value;
}
}
return spawnEnv;
return stripAppImageRuntimeEnv(spawnEnv);
}
function normalizedRuntimeEnv(
@@ -1,3 +1,4 @@
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -38,6 +39,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
cursorSettings: CursorSettings,
environment?: NodeJS.ProcessEnv,
) {
const crypto = yield* Crypto.Crypto;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const resolvedEnvironment = environment ?? process.env;
@@ -66,7 +68,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")(fu
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
@@ -1,3 +1,4 @@
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -37,6 +38,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
grokSettings: GrokSettings,
environment: NodeJS.ProcessEnv = process.env,
) {
const crypto = yield* Crypto.Crypto;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const runGrokJson = <S extends Schema.Top>({
@@ -65,7 +67,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
childProcessSpawner: commandSpawner,
cwd,
clientInfo: { name: "t3-code-git-text", version: "0.0.0" },
});
}).pipe(Effect.provideService(Crypto.Crypto, crypto));
yield* runtime.handleSessionUpdate((notification) => {
const update = notification.update;
@@ -1,5 +1,5 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
@@ -73,6 +73,24 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
}),
);
it.effect("bounds previews while reporting the complete file size", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
const cwd = yield* makeTempDir;
const contents = "a".repeat(1024 * 1024 + 5);
yield* writeTextFile(cwd, "large.txt", contents);
const result = yield* workspaceFileSystem.readFile({
cwd,
relativePath: "large.txt",
});
assert.strictEqual(result.contents.length, 1024 * 1024);
assert.strictEqual(result.byteLength, contents.length);
assert.isTrue(result.truncated);
}),
);
it.effect("rejects reads outside the workspace root", () =>
Effect.gen(function* () {
const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;
@@ -185,8 +203,13 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
expect(error.cause).toMatchObject({
_tag: "PlatformError",
reason: {
_tag: "NotFound",
pathOrDescriptor: resolvedPath,
},
});
}),
);
});
@@ -1,4 +1,3 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -7,8 +6,6 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -19,6 +16,7 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -140,30 +138,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -178,85 +178,72 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
return yield* Effect.gen(function* () {
const handle = yield* fileSystem.open(realTargetPath, { flag: "r" }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
operation: "open",
cause,
}),
}),
);
),
);
const stat = yield* handle.stat.pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const byteLength = Number(stat.size);
const bytesToRead = Math.min(byteLength, PROJECT_READ_FILE_MAX_BYTES);
const fileBytes = yield* handle.readAlloc(FileSystem.Size(bytesToRead)).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
),
Effect.map(Option.getOrElse(() => new Uint8Array())),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength,
truncated: byteLength > PROJECT_READ_FILE_MAX_BYTES,
};
}).pipe(Effect.scoped);
});
const writeFile: WorkspaceFileSystem["Service"]["writeFile"] = Effect.fn(
Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

After

Width:  |  Height:  |  Size: 111 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1003 B

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.0 KiB

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 204 KiB

After

Width:  |  Height:  |  Size: 277 KiB

+28 -6
View File
@@ -1,13 +1,21 @@
import { useAtomValue } from "@effect/atom-react";
import { useEffect, useState, type CSSProperties, type ReactNode } from "react";
import { useNavigate } from "@tanstack/react-router";
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { isMacPlatform } from "../lib/utils";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
import ThreadSidebar from "./Sidebar";
import { Sidebar, SidebarProvider, SidebarRail, SidebarTrigger, useSidebar } from "./ui/sidebar";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
Sidebar,
SidebarProvider,
SidebarRail,
SidebarTrigger,
useSidebar,
useSidebarVisibility,
} from "./ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width";
@@ -18,6 +26,8 @@ const MACOS_TRAFFIC_LIGHTS_LEFT_INSET = "90px";
function SidebarControl() {
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
const { toggleSidebar } = useSidebar();
const isSidebarVisible = useSidebarVisibility();
const stageBackdropVariant = useSidebarStageBackdropVariant();
const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");
useEffect(() => {
@@ -42,7 +52,15 @@ function SidebarControl() {
<Tooltip>
<TooltipTrigger
render={
<SidebarTrigger className="pointer-events-auto" aria-label="Toggle main sidebar" />
<SidebarTrigger
className={cn(
"pointer-events-auto",
isSidebarVisible &&
stageBackdropVariant &&
"hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
)}
aria-label="Toggle main sidebar"
/>
}
/>
<TooltipPopup side="bottom">
@@ -55,6 +73,7 @@ function SidebarControl() {
export function AppSidebarLayout({ children }: { children: ReactNode }) {
const navigate = useNavigate();
const pathname = useLocation({ select: (location) => location.pathname });
const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
@@ -92,14 +111,17 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
const unsubscribe = onMenuAction((action) => {
if (action === "open-settings") {
void navigate({ to: "/settings" });
const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);
if (!isSettingsRoute) {
void navigate({ to: "/settings" });
}
}
});
return () => {
unsubscribe?.();
};
}, [navigate]);
}, [navigate, pathname]);
return (
<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={macosWindowControlsStyle}>
+56 -1
View File
@@ -1,4 +1,11 @@
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId, TurnId } from "@t3tools/contracts";
import {
EnvironmentId,
MessageId,
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { Thread } from "../types";
@@ -359,6 +366,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
localDispatch,
phase: "ready",
latestTurn: completedTurn,
latestUserMessageId: localDispatch.latestUserMessageId,
session: readySession,
hasPendingApproval: false,
hasPendingUserInput: false,
@@ -384,6 +392,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
localDispatch,
phase: "ready",
latestTurn: newerTurn,
latestUserMessageId: localDispatch.latestUserMessageId,
session: { ...readySession, updatedAt: newerTurn.completedAt },
hasPendingApproval: false,
hasPendingUserInput: false,
@@ -410,6 +419,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
localDispatch,
phase: "running",
latestTurn: runningTurn,
latestUserMessageId: localDispatch.latestUserMessageId,
session: {
...readySession,
status: "running",
@@ -425,6 +435,7 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
localDispatch,
phase: "running",
latestTurn: runningTurn,
latestUserMessageId: localDispatch.latestUserMessageId,
session: {
...readySession,
status: "running",
@@ -437,12 +448,56 @@ describe("hasServerAcknowledgedLocalDispatch", () => {
).toBe(true);
});
it("acknowledges a steering message projected onto the current running turn", () => {
const runningTurn = {
...completedTurn,
state: "running" as const,
completedAt: null,
};
const runningSession = {
...readySession,
status: "running" as const,
activeTurnId: runningTurn.turnId,
};
const localDispatch = createLocalDispatchSnapshot(
makeThread({
latestTurn: runningTurn,
session: runningSession,
messages: [
{
id: MessageId.make("message-before-steer"),
role: "user",
text: "Initial prompt",
turnId: runningTurn.turnId,
createdAt: runningTurn.requestedAt,
updatedAt: runningTurn.requestedAt,
streaming: false,
},
],
}),
);
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "running",
latestTurn: runningTurn,
latestUserMessageId: MessageId.make("message-steer"),
session: runningSession,
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
it("acknowledges pending user interaction and errors immediately", () => {
const localDispatch = createLocalDispatchSnapshot(makeThread());
const common = {
localDispatch,
phase: "ready" as const,
latestTurn: null,
latestUserMessageId: localDispatch.latestUserMessageId,
session: null,
hasPendingApproval: false,
hasPendingUserInput: false,
+13
View File
@@ -387,6 +387,7 @@ export async function waitForStartedServerThread(
export interface LocalDispatchSnapshot {
startedAt: string;
preparingWorktree: boolean;
latestUserMessageId: ChatMessage["id"] | null;
latestTurnTurnId: TurnId | null;
latestTurnRequestedAt: string | null;
latestTurnStartedAt: string | null;
@@ -401,9 +402,11 @@ export function createLocalDispatchSnapshot(
): LocalDispatchSnapshot {
const latestTurn = activeThread?.latestTurn ?? null;
const session = activeThread?.session ?? null;
const latestUserMessage = activeThread?.messages.findLast((message) => message.role === "user");
return {
startedAt: new Date().toISOString(),
preparingWorktree: Boolean(options?.preparingWorktree),
latestUserMessageId: latestUserMessage?.id ?? null,
latestTurnTurnId: latestTurn?.turnId ?? null,
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
latestTurnStartedAt: latestTurn?.startedAt ?? null,
@@ -417,6 +420,7 @@ export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
latestTurn: Thread["latestTurn"] | null;
latestUserMessageId: ChatMessage["id"] | null;
session: Thread["session"] | null;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
@@ -431,6 +435,8 @@ export function hasServerAcknowledgedLocalDispatch(input: {
const latestTurn = input.latestTurn ?? null;
const session = input.session ?? null;
const latestUserMessageChanged =
input.localDispatch.latestUserMessageId !== input.latestUserMessageId;
const latestTurnChanged =
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
@@ -438,6 +444,13 @@ export function hasServerAcknowledgedLocalDispatch(input: {
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null);
if (input.phase === "running") {
// Steering adds a user message to the current running turn without
// necessarily changing any of the turn timestamps. Treat that projected
// message as the server acknowledgment so the composer does not remain
// stuck in its local "Sending" state until the turn settles.
if (latestUserMessageChanged) {
return true;
}
if (!latestTurnChanged) {
return false;
}
+385 -140
View File
@@ -53,6 +53,7 @@ import {
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import { useNavigate } from "@tanstack/react-router";
import { useShallow } from "zustand/react/shallow";
import {
@@ -201,6 +202,7 @@ import {
} from "../state/entities";
import { environmentShell } from "../state/shell";
import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";
import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";
import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
import { MessagesTimeline } from "./chat/MessagesTimeline";
@@ -212,6 +214,14 @@ import { resolveEffectiveEnvMode } from "./BranchToolbar.logic";
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import {
DRAFT_HERO_TRANSITION_ANIMATION_ID,
DRAFT_HERO_TRANSITION_DURATION_MS,
DRAFT_HERO_TRANSITION_EASING,
MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
runMobileComposerTransition,
} from "./chat/draftHeroTransition";
import {
MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,
buildExpiredTerminalContextToastCopy,
@@ -256,6 +266,78 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {
const transitionGroupRef = useRef<HTMLDivElement | null>(null);
const composerAnchorRef = useRef<HTMLDivElement | null>(null);
const previousStateRef = useRef(isDraftHeroState);
const previousComposerRectRef = useRef<DOMRect | null>(null);
const animationRef = useRef<Animation | null>(null);
const attachTransitionGroupRef = (element: HTMLDivElement | null) => {
transitionGroupRef.current = element;
};
const attachComposerAnchorRef = (element: HTMLDivElement | null) => {
composerAnchorRef.current = element;
};
const captureComposerRect = () => {
previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;
};
useLayoutEffect(() => {
const transitionGroup = transitionGroupRef.current;
const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;
const stateChanged = previousStateRef.current !== isDraftHeroState;
const prefersReducedMotion =
typeof window !== "undefined" &&
window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
const mobileComposerTransitionActive =
typeof document !== "undefined" &&
document.documentElement.dataset.mobileComposerRouteTransition === "true";
animationRef.current?.cancel();
animationRef.current = null;
const previousComposerRect = previousComposerRectRef.current;
if (
stateChanged &&
!prefersReducedMotion &&
!mobileComposerTransitionActive &&
transitionGroup &&
previousComposerRect &&
nextComposerRect &&
typeof transitionGroup.animate === "function"
) {
const translateX = previousComposerRect.left - nextComposerRect.left;
const translateY = previousComposerRect.top - nextComposerRect.top;
if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {
const animation = transitionGroup.animate(
[
{ transform: `translate3d(${translateX}px, ${translateY}px, 0)` },
{ transform: "translate3d(0, 0, 0)" },
],
{
duration: DRAFT_HERO_TRANSITION_DURATION_MS,
easing: DRAFT_HERO_TRANSITION_EASING,
},
);
animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;
animationRef.current = animation;
void animation.finished
.catch(() => undefined)
.then(() => {
if (animationRef.current !== animation) {
return;
}
animationRef.current = null;
});
}
}
previousStateRef.current = isDraftHeroState;
previousComposerRectRef.current = nextComposerRect;
}, [isDraftHeroState]);
return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const;
}
const PreviewPanel = lazy(() =>
import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),
);
@@ -339,6 +421,7 @@ type ChatViewProps =
threadId: ThreadId;
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
routeKind: "server";
draftId?: never;
}
@@ -347,6 +430,7 @@ type ChatViewProps =
threadId: ThreadId;
onDiffPanelOpen?: () => void;
reserveTitleBarControlInset?: boolean;
forceExpandedMobileComposer?: boolean;
routeKind: "draft";
draftId: DraftId;
};
@@ -368,6 +452,8 @@ function useLocalDispatchState(input: {
threadError: string | null | undefined;
}) {
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
const latestUserMessageId =
input.activeThread?.messages.findLast((message) => message.role === "user")?.id ?? null;
const resetLocalDispatch = useCallback(() => {
setLocalDispatch(null);
@@ -379,6 +465,7 @@ function useLocalDispatchState(input: {
localDispatch,
phase: input.phase,
latestTurn: input.activeLatestTurn,
latestUserMessageId,
session: input.activeThread?.session ?? null,
hasPendingApproval: input.activePendingApproval !== null,
hasPendingUserInput: input.activePendingUserInput !== null,
@@ -391,6 +478,7 @@ function useLocalDispatchState(input: {
input.activeThread?.session,
input.phase,
input.threadError,
latestUserMessageId,
localDispatch,
],
);
@@ -979,6 +1067,14 @@ const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPane
);
});
// Errors surface through two maps (draft-keyed and thread-keyed) whose entries
// can race around promotion, so each write carries its time to let the latest
// one win when they collide.
type LocalThreadErrorEntry = {
readonly message: string | null;
readonly at: number;
};
function ChatViewContent(props: ChatViewProps) {
const {
environmentId,
@@ -986,6 +1082,7 @@ function ChatViewContent(props: ChatViewProps) {
routeKind,
onDiffPanelOpen,
reserveTitleBarControlInset = true,
forceExpandedMobileComposer = false,
} = props;
const draftId = routeKind === "draft" ? props.draftId : null;
const routeThreadRef = useMemo(
@@ -1035,10 +1132,10 @@ function ChatViewContent(props: ChatViewProps) {
);
const composerDraftTarget: ScopedThreadRef | DraftId =
routeKind === "server" ? routeThreadRef : props.draftId;
const serverThread = useThread(routeKind === "server" ? routeThreadRef : null);
const serverThread = useThread(routeThreadRef);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore((store) =>
routeKind === "server" ? store.threadLastVisitedAtById[routeThreadKey] : undefined,
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[routeThreadKey],
);
const settings = useEnvironmentSettings(environmentId);
const setStickyComposerModelSelection = useComposerDraftStore(
@@ -1103,10 +1200,10 @@ function ChatViewContent(props: ChatViewProps) {
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
optimisticUserMessagesRef.current = optimisticUserMessages;
const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<
Record<string, string | null>
Record<string, LocalThreadErrorEntry>
>({});
const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState<
Record<string, string | null>
Record<string, LocalThreadErrorEntry>
>({});
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
@@ -1218,11 +1315,45 @@ function ChatViewContent(props: ChatViewProps) {
? scopeProjectRef(draftThread.environmentId, draftThread.projectId)
: null;
const fallbackDraftProject = useProject(fallbackDraftProjectRef);
const localDraftError =
routeKind === "server" && serverThread
? null
: ((draftId ? localDraftErrorsByDraftId[draftId] : null) ?? null);
const localServerError = localServerErrorsByThreadKey[routeThreadKey] ?? null;
const localDraftError = serverThread
? null
: ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);
const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;
// Draft errors are keyed by draftId while server errors are keyed by thread
// key, so a pending draft entry must migrate when the server thread loads or
// a failed send would silently disappear on promotion. When both keys hold
// an entry, the most recent write wins.
useEffect(() => {
if (!serverThread || !draftId) {
return;
}
const pendingDraftEntry = localDraftErrorsByDraftId[draftId];
if (pendingDraftEntry === undefined) {
return;
}
setLocalDraftErrorsByDraftId((existing) => {
if (existing[draftId] === undefined) {
return existing;
}
const next = { ...existing };
delete next[draftId];
return next;
});
setLocalServerErrorsByThreadKey((existing) => {
const currentEntry = existing[routeThreadKey];
if (
currentEntry !== undefined &&
(currentEntry.at > pendingDraftEntry.at ||
currentEntry.message === pendingDraftEntry.message)
) {
return existing;
}
return {
...existing,
[routeThreadKey]: pendingDraftEntry,
};
});
}, [draftId, localDraftErrorsByDraftId, routeThreadKey, serverThread]);
const localDraftThread = useMemo(
() =>
draftThread
@@ -1237,7 +1368,10 @@ function ChatViewContent(props: ChatViewProps) {
: undefined,
[draftThread, fallbackDraftProject?.defaultModelSelection, threadId],
);
const isServerThread = routeKind === "server" && serverThread !== null;
// Promotion is data-driven: the draft route keeps rendering while the
// server thread (same pre-allocated ref) starts, so live state must not
// depend on which route is mounted.
const isServerThread = serverThread !== null;
const activeThread = isServerThread ? serverThread : localDraftThread;
const threadError = isServerThread
? (localServerError ?? serverThread?.session?.lastError ?? null)
@@ -2063,6 +2197,16 @@ function ChatViewContent(props: ChatViewProps) {
deriveTimelineEntries(timelineMessages, activeThread?.proposedPlans ?? [], workLogEntries),
[activeThread?.proposedPlans, timelineMessages, workLogEntries],
);
const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);
const draftHeroDockRequested =
activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;
const isDraftHeroState =
isLocalDraftThread && timelineEntries.length === 0 && !isWorking && !draftHeroDockRequested;
const [
attachDraftHeroTransitionGroupRef,
attachDraftHeroComposerAnchorRef,
captureDraftHeroComposerRect,
] = useDraftHeroLayoutTransition(isDraftHeroState);
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
const turnDiffSummaryByAssistantMessageId = useMemo(() => {
@@ -2112,12 +2256,13 @@ function ChatViewContent(props: ChatViewProps) {
worktreePath: activeThread?.worktreePath ?? null,
})
: null;
const gitStatusCwd = activeThread?.worktreePath ?? gitCwd;
const gitStatusQuery = useEnvironmentQuery(
gitCwd === null
gitStatusCwd === null
? null
: vcsEnvironment.status({
environmentId,
input: { cwd: gitCwd },
input: { cwd: gitStatusCwd },
}),
);
const keybindings = useAtomValue(primaryServerKeybindingsAtom);
@@ -2151,6 +2296,9 @@ function ChatViewContent(props: ChatViewProps) {
terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;
// Default true while loading to avoid toolbar flicker.
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const initialDiffPanelGitScope =
gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";
const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";
const terminalShortcutLabelOptions = useMemo(
() => ({
context: {
@@ -2226,6 +2374,7 @@ function ChatViewContent(props: ChatViewProps) {
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
const nextError = sanitizeThreadErrorMessage(error);
const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };
if (
serverThread &&
targetThreadId === routeThreadRef.threadId &&
@@ -2233,24 +2382,24 @@ function ChatViewContent(props: ChatViewProps) {
serverThread.id === targetThreadId
) {
setLocalServerErrorsByThreadKey((existing) => {
if ((existing[routeThreadKey] ?? null) === nextError) {
if ((existing[routeThreadKey]?.message ?? null) === nextError) {
return existing;
}
return {
...existing,
[routeThreadKey]: nextError,
[routeThreadKey]: nextEntry,
};
});
return;
}
const localDraftErrorKey = draftId ?? targetThreadId;
setLocalDraftErrorsByDraftId((existing) => {
if ((existing[localDraftErrorKey] ?? null) === nextError) {
if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {
return existing;
}
return {
...existing,
[localDraftErrorKey]: nextError,
[localDraftErrorKey]: nextEntry,
};
});
},
@@ -2771,9 +2920,19 @@ function ChatViewContent(props: ChatViewProps) {
}, [activeThreadRef, openPreview]);
const addDiffSurface = useCallback(() => {
if (!activeThreadRef || !isServerThread || !isGitRepo) return;
if (planSidebarOpen) {
dismissPlanSidebarForCurrentTurn();
}
useRightPanelStore.getState().open(activeThreadRef, "diff");
onDiffPanelOpen?.();
}, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]);
}, [
activeThreadRef,
dismissPlanSidebarForCurrentTurn,
isGitRepo,
isServerThread,
onDiffPanelOpen,
planSidebarOpen,
]);
const addFilesSurface = useCallback(() => {
if (!activeThreadRef || !activeProject) return;
useRightPanelStore.getState().open(activeThreadRef, "files");
@@ -3963,7 +4122,16 @@ function ChatViewContent(props: ChatViewProps) {
}
return;
}
if (!activeProject) return;
if (!activeProject) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Choose a project first",
description: "This draft no longer points to an available project.",
}),
);
return;
}
const threadIdForSend = activeThread.id;
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
const baseBranchForWorktree =
@@ -3981,6 +4149,21 @@ function ChatViewContent(props: ChatViewProps) {
}
sendInFlightRef.current = true;
if (isDraftHeroState && activeThreadKey) {
let resolveDockStarted: (() => void) | undefined;
const dockStarted = new Promise<void>((resolve) => {
resolveDockStarted = resolve;
});
const dockTransition = runMobileComposerTransition(() => {
flushSync(() => {
captureDraftHeroComposerRect();
setDockedDraftHeroThreadKey(activeThreadKey);
});
resolveDockStarted?.();
});
void dockTransition.catch(() => resolveDockStarted?.());
await dockStarted;
}
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
const composerImagesSnapshot = [...composerImages];
@@ -4234,6 +4417,9 @@ function ChatViewContent(props: ChatViewProps) {
}
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
setDockedDraftHeroThreadKey((currentThreadKey) =>
currentThreadKey === activeThreadKey ? null : currentThreadKey,
);
resetLocalDispatch();
}
};
@@ -4968,7 +5154,12 @@ function ChatViewContent(props: ChatViewProps) {
/>
) : activeRightPanelSurface?.kind === "diff" ? (
<Suspense fallback={null}>
<DiffPanel mode="embedded" composerDraftTarget={composerDraftTarget} />
<DiffPanel
key={`${activeThreadKey}:${diffPanelGitStatusResolutionKey}`}
mode="embedded"
composerDraftTarget={composerDraftTarget}
initialGitScope={initialDiffPanelGitScope}
/>
</Suspense>
) : activeRightPanelSurface?.kind === "plan" ? (
<PlanSidebar
@@ -5101,6 +5292,7 @@ function ChatViewContent(props: ChatViewProps) {
contentInsetEndAdjustment={composerOverlayHeight}
onIsAtEndChange={onIsAtEndChange}
onManualNavigation={cancelTimelineLiveFollowForUserNavigation}
hideEmptyPlaceholder={isDraftHeroState}
/>
{/* scroll to end pill — shown when user has scrolled away from the live edge */}
@@ -5123,135 +5315,188 @@ function ChatViewContent(props: ChatViewProps) {
)}
</div>
{/* Input bar */}
{/* Input bar — centered hero while a draft has no messages, docked at the bottom otherwise */}
<div
ref={setComposerOverlayElement}
data-chat-composer-overlay="true"
className="pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
className={
isDraftHeroState
? "pointer-events-none absolute inset-0 z-20 flex items-center"
: "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"
}
>
<div
aria-hidden="true"
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
>
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
<div className="chat-composer-shared-blur absolute -inset-8" />
{!isDraftHeroState ? (
<div
key="docked-composer-blur"
aria-hidden="true"
className="chat-composer-horizontal-inset pointer-events-none absolute inset-x-0 top-1.5 bottom-0 z-0 sm:top-2"
>
<div className="relative mx-auto h-full w-full max-w-3xl overflow-clip rounded-t-[20px]">
<div className="chat-composer-shared-blur absolute -inset-8" />
</div>
</div>
</div>
<div className="chat-composer-horizontal-inset">
) : null}
<div
ref={attachDraftHeroTransitionGroupRef}
className="chat-composer-horizontal-inset w-full"
>
<div className="pointer-events-auto relative z-10 isolate">
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
<div className="relative z-10">
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
{isDraftHeroState ? (
<div className="absolute inset-x-0 bottom-full z-0">
<div
className="pb-8"
style={
forceExpandedMobileComposer
? {
viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
}
: undefined
}
>
<DraftHeroHeadline
activeProjectRef={activeProjectRef}
activeProjectTitle={activeProject?.title ?? null}
/>
</div>
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
</div>
) : (
<ComposerBannerStack className="relative z-0" items={composerBannerItems} />
)}
<div
className="relative"
style={
forceExpandedMobileComposer
? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }
: undefined
}
>
<div
ref={attachDraftHeroComposerAnchorRef}
className="relative z-10 mx-auto w-full max-w-3xl"
>
<ChatComposer
composerRef={composerRef}
composerDraftTarget={composerDraftTarget}
environmentId={environmentId}
routeKind={routeKind}
routeThreadRef={routeThreadRef}
draftId={draftId}
activeThreadId={activeThreadId}
activeThreadEnvironmentId={activeThread?.environmentId}
activeThread={activeThread}
isServerThread={isServerThread}
isLocalDraftThread={isLocalDraftThread}
forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}
projectSelectionRequired={isLocalDraftThread && activeProject === null}
phase={phase}
isConnecting={isConnecting}
isSendBusy={isSendBusy}
isPreparingWorktree={isPreparingWorktree}
environmentUnavailable={activeEnvironmentUnavailableState}
activePendingApproval={activePendingApproval}
pendingApprovals={pendingApprovals}
pendingUserInputs={pendingUserInputs}
activePendingProgress={activePendingProgress}
activePendingResolvedAnswers={activePendingResolvedAnswers}
activePendingIsResponding={activePendingIsResponding}
activePendingDraftAnswers={activePendingDraftAnswers}
activePendingQuestionIndex={activePendingQuestionIndex}
respondingRequestIds={respondingRequestIds}
showPlanFollowUpPrompt={showPlanFollowUpPrompt}
activeProposedPlan={activeProposedPlan}
activePlan={activePlan as { turnId?: TurnId } | null}
sidebarProposedPlan={sidebarProposedPlan as { turnId?: TurnId } | null}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
interactionMode={interactionMode}
lockedProvider={lockedProvider}
providerStatuses={providerStatuses as ServerProvider[]}
activeProjectDefaultModelSelection={activeProject?.defaultModelSelection}
activeThreadModelSelection={activeThread?.modelSelection}
activeThreadActivities={activeThread?.activities}
resolvedTheme={resolvedTheme}
settings={settings}
keybindings={keybindings}
terminalOpen={Boolean(terminalUiState.terminalOpen)}
gitCwd={gitCwd}
promptRef={promptRef}
composerImagesRef={composerImagesRef}
composerTerminalContextsRef={composerTerminalContextsRef}
composerElementContextsRef={composerElementContextsRef}
onSend={onSend}
onInterrupt={onInterrupt}
onImplementPlanInNewThread={onImplementPlanInNewThread}
onRespondToApproval={onRespondToApproval}
onSelectActivePendingUserInputOption={onSelectActivePendingUserInputOption}
onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}
onPreviousActivePendingUserInputQuestion={
onPreviousActivePendingUserInputQuestion
}
onChangeActivePendingUserInputCustomAnswer={
onChangeActivePendingUserInputCustomAnswer
}
onProviderModelSelect={onProviderModelSelect}
getModelDisabledReason={getModelDisabledReason}
toggleInteractionMode={toggleInteractionMode}
handleRuntimeModeChange={handleRuntimeModeChange}
handleInteractionModeChange={handleInteractionModeChange}
togglePlanSidebar={togglePlanSidebar}
focusComposer={focusComposer}
scheduleComposerFocus={scheduleComposerFocus}
setThreadError={setThreadError}
onExpandImage={onExpandTimelineImage}
/>
</div>
<div
className={cn(
"min-h-0",
isDraftHeroState ? "absolute inset-x-0 top-full" : null,
)}
>
<div
className={cn(
"chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange:
setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
</div>
</div>
</div>
</div>
</div>
<div
className={cn(
"chat-composer-horizontal-inset chat-composer-lower-chrome relative z-10",
isGitRepo
? "pb-[calc(env(safe-area-inset-bottom)+0.25rem)]"
: "pb-[calc(env(safe-area-inset-bottom)+0.75rem)] sm:pb-[calc(env(safe-area-inset-bottom)+1rem)]",
)}
>
{isGitRepo && (
<div className="pointer-events-auto">
<BranchToolbar
environmentId={activeThread.environmentId}
threadId={activeThread.id}
{...(routeKind === "draft" && draftId ? { draftId } : {})}
onEnvModeChange={onEnvModeChange}
startFromOrigin={startFromOrigin}
onStartFromOriginChange={onStartFromOriginChange}
{...(canOverrideServerThreadEnvMode
? { effectiveEnvModeOverride: envMode }
: {})}
{...(canOverrideServerThreadEnvMode
? {
activeThreadBranchOverride: activeThreadBranch,
onActiveThreadBranchOverrideChange: setPendingServerThreadBranch,
}
: {})}
envLocked={envLocked}
onComposerFocusRequest={scheduleComposerFocus}
{...(canCheckoutPullRequestIntoThread
? { onCheckoutPullRequestRequest: openPullRequestDialog }
: {})}
{...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}
availableEnvironments={logicalProjectEnvironments}
/>
</div>
)}
</div>
</div>
{pullRequestDialogState ? (
@@ -0,0 +1,73 @@
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
$createParagraphNode,
$createTextNode,
$getRoot,
$getSelection,
$isRangeSelection,
COMMAND_PRIORITY_EDITOR,
createEditor,
PASTE_COMMAND,
} from "lexical";
import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
class TestClipboardEvent extends Event {
readonly clipboardData: DataTransfer;
constructor(text: string) {
super("paste", { cancelable: true });
this.clipboardData = {
files: [],
getData: (type: string) => (type === "text/plain" ? text : ""),
} as unknown as DataTransfer;
}
}
describe("registerComposerInlineTokenPaste", () => {
afterEach(() => {
vi.unstubAllGlobals();
});
it("handles a copied mention without also running the plain-text paste fallback", () => {
vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
const editor = createEditor();
const mention = "[improve-deploy-error-logging.md](.changeset/improve-deploy-error-logging.md)";
const plainTextFallback = vi.fn(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection)) return false;
selection.insertText(mention);
return true;
});
editor.update(
() => {
const paragraph = $createParagraphNode();
$getRoot().append(paragraph);
paragraph.selectEnd();
},
{ discrete: true },
);
registerComposerInlineTokenPaste(editor, {
createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
getExpandedAbsoluteOffsetForPoint: () => 0,
});
editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
const event = new TestClipboardEvent(mention);
let handled = false;
editor.update(
() => {
handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
},
{ discrete: true },
);
expect(handled).toBe(true);
expect(plainTextFallback).not.toHaveBeenCalled();
expect(event.defaultPrevented).toBe(true);
expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
"<mention:.changeset/improve-deploy-error-logging.md> ",
);
});
});
@@ -9,6 +9,7 @@ import { type ServerProviderSkill } from "@t3tools/contracts";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import {
$applyNodeReplacement,
$createRangeSelectionFromDom,
$createRangeSelection,
$getSelection,
$setSelection,
@@ -23,6 +24,7 @@ import {
KEY_ARROW_LEFT_COMMAND,
KEY_ARROW_RIGHT_COMMAND,
KEY_ARROW_UP_COMMAND,
KEY_DOWN_COMMAND,
KEY_ENTER_COMMAND,
KEY_TAB_COMMAND,
COMMAND_PRIORITY_HIGH,
@@ -63,7 +65,7 @@ import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { cn, isMacPlatform } from "~/lib/utils";
import { basenameOfPath } from "~/pierre-icons";
import {
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
@@ -75,6 +77,7 @@ import { FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
import { formatProviderSkillDisplayName } from "~/providerSkillPresentation";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
const SURROUND_SYMBOLS: [string, string][] = [
@@ -1022,6 +1025,53 @@ function ComposerInlineTokenArrowPlugin() {
return null;
}
function ComposerHomeEndKeyPlugin() {
const [editor] = useLexicalComposerContext();
useEffect(() => {
return editor.registerCommand(
KEY_DOWN_COMMAND,
(event) => {
if (!isMacPlatform(navigator.platform)) {
return false;
}
if (event.key !== "Home" && event.key !== "End") {
return false;
}
if (event.altKey || event.metaKey || event.ctrlKey || event.isComposing) {
return false;
}
const rootElement = editor.getRootElement();
const selection = window.getSelection();
const anchorNode = selection?.anchorNode;
if (!rootElement || !selection || !anchorNode || !rootElement.contains(anchorNode)) {
return false;
}
if (selection.rangeCount === 0 || typeof selection.modify !== "function") {
return false;
}
event.preventDefault();
event.stopPropagation();
selection.modify(
event.shiftKey ? "extend" : "move",
event.key === "Home" ? "backward" : "forward",
"lineboundary",
);
editor.update(() => {
$setSelection($createRangeSelectionFromDom(selection, editor));
});
return true;
},
COMMAND_PRIORITY_HIGH,
);
}, [editor]);
return null;
}
function ComposerInlineTokenSelectionNormalizePlugin() {
const [editor] = useLexicalComposerContext();
@@ -1117,6 +1167,21 @@ function ComposerInlineTokenBackspacePlugin() {
return null;
}
function ComposerInlineTokenPastePlugin() {
const [editor] = useLexicalComposerContext();
useEffect(
() =>
registerComposerInlineTokenPaste(editor, {
createMentionNode: $createComposerMentionNode,
getExpandedAbsoluteOffsetForPoint,
}),
[editor],
);
return null;
}
function ComposerSurroundSelectionPlugin(props: {
terminalContexts: ReadonlyArray<TerminalContextDraft>;
skills: ReadonlyArray<ServerProviderSkill>;
@@ -1631,9 +1696,11 @@ function ComposerPromptEditorInner({
<OnChangePlugin onChange={handleEditorChange} />
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} skills={skills} />
<ComposerHomeEndKeyPlugin />
<ComposerInlineTokenArrowPlugin />
<ComposerInlineTokenSelectionNormalizePlugin />
<ComposerInlineTokenBackspacePlugin />
<ComposerInlineTokenPastePlugin />
<HistoryPlugin />
</div>
</ComposerTerminalContextActionsContext>
+14 -4
View File
@@ -178,13 +178,19 @@ const DIFF_PANEL_UNSAFE_CSS = `
interface DiffPanelProps {
mode?: DiffPanelMode;
composerDraftTarget: ScopedThreadRef | DraftId;
initialGitScope: "branch" | "unstaged";
}
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline", composerDraftTarget }: DiffPanelProps) {
export default function DiffPanel({
mode = "inline",
composerDraftTarget,
initialGitScope: initialGitScopeProp,
}: DiffPanelProps) {
const { resolvedTheme } = useTheme();
const settings = useClientSettings();
const [initialGitScope] = useState(initialGitScopeProp);
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const [wordWrap, setWordWrap] = useState(settings.wordWrap);
const [diffIgnoreWhitespace, setDiffIgnoreWhitespace] = useState(settings.diffIgnoreWhitespace);
@@ -199,9 +205,6 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
strict: false,
select: (params) => resolveThreadRouteRef(params),
});
const diffSelection = useDiffPanelStore((state) =>
selectThreadDiffPanelSelection(state.byThreadKey, routeThreadRef),
);
const activeThreadId = routeThreadRef?.threadId ?? null;
const activeThread = useThread(routeThreadRef);
const activeProjectId = activeThread?.projectId ?? null;
@@ -229,6 +232,13 @@ export default function DiffPanel({ mode = "inline", composerDraftTarget }: Diff
})
: null,
);
const diffSelection = useDiffPanelStore((state) =>
selectThreadDiffPanelSelection(
state.byThreadKey,
routeThreadRef,
initialGitScope === "unstaged",
),
);
const isGitRepo = gitStatusQuery.data?.isRepo ?? true;
const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =
useTurnDiffSummaries(activeThread);
@@ -19,6 +19,7 @@ import {
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortScopedProjectsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import {
@@ -1066,3 +1067,73 @@ describe("sortProjectsForSidebar", () => {
expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
});
});
describe("sortScopedProjectsForSidebar", () => {
it("keeps identical project ids in different environments separate", () => {
const remoteEnvironmentId = EnvironmentId.make("environment-remote");
const sharedProjectId = ProjectId.make("shared-project");
const projects = [
makeProject({
environmentId: localEnvironmentId,
id: sharedProjectId,
title: "Local project",
}),
makeProject({
environmentId: remoteEnvironmentId,
id: sharedProjectId,
title: "Remote project",
}),
];
const threads = [
makeThread({
environmentId: localEnvironmentId,
projectId: sharedProjectId,
updatedAt: "2026-03-09T10:02:00.000Z",
}),
makeThread({
environmentId: remoteEnvironmentId,
projectId: sharedProjectId,
updatedAt: "2026-03-09T10:10:00.000Z",
}),
];
const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
expect(sorted.map((project) => project.title)).toEqual(["Remote project", "Local project"]);
});
it("does not use archived threads as project activity", () => {
const projects = [
makeProject({
id: ProjectId.make("project-visible"),
title: "Visible project",
updatedAt: "2026-03-09T10:01:00.000Z",
}),
makeProject({
id: ProjectId.make("project-archived"),
title: "Archived-only project",
updatedAt: "2026-03-09T10:00:00.000Z",
}),
];
const threads = [
makeThread({
id: ThreadId.make("thread-visible"),
projectId: ProjectId.make("project-visible"),
updatedAt: "2026-03-09T10:02:00.000Z",
}),
makeThread({
id: ThreadId.make("thread-archived"),
projectId: ProjectId.make("project-archived"),
updatedAt: "2026-03-09T10:10:00.000Z",
archivedAt: "2026-03-09T10:11:00.000Z",
}),
];
const sorted = sortScopedProjectsForSidebar(projects, threads, "updated_at");
expect(sorted.map((project) => project.title)).toEqual([
"Visible project",
"Archived-only project",
]);
});
});
+72 -20
View File
@@ -24,6 +24,16 @@ type SidebarProject = {
updatedAt?: string | undefined;
};
type ScopedSidebarProject = SidebarProject & {
environmentId: string;
};
type ScopedSidebarThread = ThreadSortInput & {
environmentId: string;
projectId: string;
archivedAt: string | null;
};
export type ThreadTraversalDirection = "previous" | "next";
export interface ThreadStatusPill {
@@ -534,6 +544,25 @@ export function getProjectSortTimestamp(
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
function sortProjectsByActivity<TProject extends SidebarProject>(
projects: readonly TProject[],
sortOrder: SidebarProjectSortOrder,
getProjectThreads: (project: TProject) => readonly ThreadSortInput[],
compareTies: (left: TProject, right: TProject) => number,
): TProject[] {
if (sortOrder === "manual") {
return [...projects];
}
return [...projects].toSorted((left, right) => {
const rightTimestamp = getProjectSortTimestamp(right, getProjectThreads(right), sortOrder);
const leftTimestamp = getProjectSortTimestamp(left, getProjectThreads(left), sortOrder);
const byTimestamp =
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
return byTimestamp || compareTies(left, right);
});
}
export function sortProjectsForSidebar<
TProject extends SidebarProject,
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & ThreadSortInput,
@@ -542,10 +571,6 @@ export function sortProjectsForSidebar<
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
): TProject[] {
if (sortOrder === "manual") {
return [...projects];
}
const threadsByProjectId = new Map<string, TThread[]>();
for (const thread of threads) {
const existing = threadsByProjectId.get(thread.projectId) ?? [];
@@ -553,20 +578,47 @@ export function sortProjectsForSidebar<
threadsByProjectId.set(thread.projectId, existing);
}
return [...projects].toSorted((left, right) => {
const rightTimestamp = getProjectSortTimestamp(
right,
threadsByProjectId.get(right.id) ?? [],
sortOrder,
);
const leftTimestamp = getProjectSortTimestamp(
left,
threadsByProjectId.get(left.id) ?? [],
sortOrder,
);
const byTimestamp =
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
if (byTimestamp !== 0) return byTimestamp;
return left.title.localeCompare(right.title) || left.id.localeCompare(right.id);
});
return sortProjectsByActivity(
projects,
sortOrder,
(project) => threadsByProjectId.get(project.id) ?? [],
(left, right) => left.title.localeCompare(right.title) || left.id.localeCompare(right.id),
);
}
/**
* Sorts the cross-environment project collection used by landing surfaces.
* Project ids are only unique within an environment, and archived threads
* must not make a project appear recently active.
*/
export function sortScopedProjectsForSidebar<
TProject extends ScopedSidebarProject,
TThread extends ScopedSidebarThread,
>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
): TProject[] {
const scopedKey = (environmentId: string, projectId: string) =>
`${environmentId}\u0000${projectId}`;
const threadsByProject = new Map<string, TThread[]>();
for (const thread of threads) {
if (thread.archivedAt !== null) {
continue;
}
const key = scopedKey(thread.environmentId, thread.projectId);
const existing = threadsByProject.get(key) ?? [];
existing.push(thread);
threadsByProject.set(key, existing);
}
return sortProjectsByActivity(
projects,
sortOrder,
(project) => threadsByProject.get(scopedKey(project.environmentId, project.id)) ?? [],
(left, right) =>
left.title.localeCompare(right.title) ||
left.environmentId.localeCompare(right.environmentId) ||
left.id.localeCompare(right.id),
);
}
+40 -17
View File
@@ -77,7 +77,7 @@ import { isElectron } from "../env";
import { APP_STAGE_LABEL } from "../branding";
import { useOpenPrLink } from "../lib/openPullRequestLink";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isMacPlatform } from "../lib/utils";
import { cn, isMacPlatform } from "../lib/utils";
import {
readThreadShell,
useProject,
@@ -126,6 +126,7 @@ import {
import { stackedThreadToast, toastManager } from "./ui/toast";
import { formatRelativeTimeLabel } from "../timestampFormat";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarStageBackdrop, resolveSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import { Kbd } from "./ui/kbd";
import {
getArm64IntelBuildWarningDescription,
@@ -2744,33 +2745,55 @@ const SidebarChromeHeader = memo(function SidebarChromeHeader({
}: {
isElectron: boolean;
}) {
return isElectron ? (
<SidebarHeader className="@container/sidebar-header drag-region h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
<SidebarTrigger className="md:hidden" />
<SidebarBrand />
</SidebarHeader>
) : (
<SidebarHeader className="@container/sidebar-header h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0">
<SidebarTrigger className="md:hidden" />
<SidebarBrand />
const stageLabel = useSidebarStageLabel();
const backdropVariant = resolveSidebarStageBackdropVariant(stageLabel);
return (
<SidebarHeader
className={cn(
"@container/sidebar-header relative h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center px-3 py-0 md:px-0",
isElectron && "drag-region",
)}
>
{backdropVariant ? <SidebarStageBackdrop variant={backdropVariant} /> : null}
<SidebarTrigger
className={cn(
"relative z-10 md:hidden",
backdropVariant && "hover:bg-white/15 [&_svg]:text-white/85! [&_svg]:hover:text-white!",
)}
/>
<SidebarBrand onBackdrop={backdropVariant !== null} stageLabel={stageLabel} />
</SidebarHeader>
);
});
function SidebarBrand() {
const stageLabel = useSidebarStageLabel();
function SidebarBrand({ stageLabel, onBackdrop }: { stageLabel: string; onBackdrop: boolean }) {
return (
<Link
aria-label="Go to threads"
className="sidebar-brand ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md text-foreground outline-hidden ring-ring focus-visible:ring-2"
className={cn(
"sidebar-brand relative z-10 ml-[var(--workspace-titlebar-content-left)] h-7 w-fit min-w-0 shrink-0 items-center gap-1 overflow-hidden rounded-md outline-hidden ring-ring focus-visible:ring-2",
onBackdrop ? "text-white" : "text-foreground",
)}
to="/"
>
<T3Wordmark />
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
<span
className={cn(
"truncate text-sm font-medium tracking-tight",
onBackdrop ? "text-white/70" : "text-muted-foreground",
)}
>
Code
</span>
<span className="sidebar-brand-stage shrink-0 items-center whitespace-nowrap rounded-full bg-muted/50 px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em] text-muted-foreground/60">
<span
className={cn(
"sidebar-brand-stage shrink-0 items-center whitespace-nowrap rounded-full px-1.5 py-0.5 text-[8px] font-medium uppercase tracking-[0.18em]",
onBackdrop
? "bg-white/15 text-white/80 backdrop-blur-sm"
: "bg-muted/50 text-muted-foreground/60",
)}
>
{stageLabel}
</span>
</Link>
@@ -2791,7 +2814,7 @@ function T3Wordmark() {
return (
<svg
aria-label="T3"
className="h-2.5 w-auto shrink-0 text-foreground"
className="h-2.5 w-auto shrink-0"
viewBox="15.5309 37 94.3941 56.96"
xmlns="http://www.w3.org/2000/svg"
>
@@ -0,0 +1,316 @@
import { useAtomValue } from "@effect/atom-react";
import { APP_STAGE_LABEL } from "../branding";
import { resolveServerBackedAppStageLabel } from "../branding.logic";
import { primaryServerConfigAtom } from "../state/server";
export type SidebarStageBackdropVariant = "nightly" | "dev";
// A wide viewBox keeps the 96-unit art height at a fixed scale while sidebar resizing reveals
// more horizontal canvas instead of zooming the scene.
const STAGE_BACKDROP_VIEW_BOX = "0 0 8192 96";
export function resolveSidebarStageBackdropVariant(
stageLabel: string,
): SidebarStageBackdropVariant | null {
const normalized = stageLabel.trim().toLowerCase();
if (normalized === "nightly") return "nightly";
if (normalized === "dev") return "dev";
return null;
}
export function useSidebarStageBackdropVariant(): SidebarStageBackdropVariant | null {
const primaryServerVersion =
useAtomValue(primaryServerConfigAtom)?.environment.serverVersion ?? null;
return resolveSidebarStageBackdropVariant(
resolveServerBackedAppStageLabel({
primaryServerVersion,
fallbackStageLabel: APP_STAGE_LABEL,
}),
);
}
/** Stage-channel header art; palettes mirror the per-channel app icons in `assets/`. */
export function SidebarStageBackdrop({ variant }: { variant: SidebarStageBackdropVariant }) {
return (
<div
aria-hidden
className="sidebar-stage-backdrop pointer-events-none absolute inset-x-0 top-0 z-0 h-20 select-none overflow-hidden"
>
{variant === "nightly" ? <NightlySkyArt /> : <DevBlueprintArt />}
</div>
);
}
const NIGHTLY_STARS: ReadonlyArray<{
cx: number;
cy: number;
r: number;
opacity: number;
}> = [
{ cx: 14, cy: 10, r: 0.6, opacity: 0.85 },
{ cx: 38, cy: 22, r: 0.4, opacity: 0.55 },
{ cx: 58, cy: 8, r: 0.5, opacity: 0.7 },
{ cx: 84, cy: 16, r: 0.4, opacity: 0.5 },
{ cx: 104, cy: 7, r: 0.6, opacity: 0.8 },
{ cx: 126, cy: 20, r: 0.4, opacity: 0.55 },
{ cx: 148, cy: 11, r: 0.5, opacity: 0.7 },
{ cx: 170, cy: 24, r: 0.4, opacity: 0.5 },
{ cx: 192, cy: 9, r: 0.6, opacity: 0.8 },
{ cx: 214, cy: 18, r: 0.4, opacity: 0.55 },
{ cx: 236, cy: 8, r: 0.5, opacity: 0.7 },
{ cx: 258, cy: 20, r: 0.45, opacity: 0.6 },
{ cx: 278, cy: 11, r: 0.55, opacity: 0.75 },
{ cx: 26, cy: 34, r: 0.4, opacity: 0.45 },
{ cx: 118, cy: 34, r: 0.4, opacity: 0.45 },
{ cx: 202, cy: 32, r: 0.4, opacity: 0.5 },
{ cx: 268, cy: 34, r: 0.4, opacity: 0.45 },
];
const NIGHTLY_SPARKLES: ReadonlyArray<{ x: number; y: number }> = [
{ x: 70, y: 28 },
{ x: 160, y: 36 },
{ x: 246, y: 26 },
];
function NightlySkyArt() {
return (
<svg
className="h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<linearGradient
id="stage-night-sky"
x1="24"
y1="0"
x2="264"
y2="96"
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<stop stopColor="#07152F" />
<stop offset="0.5" stopColor="#151443" />
<stop offset="1" stopColor="#32155B" />
</linearGradient>
<radialGradient
id="stage-night-glow"
cx="0"
cy="0"
r="1"
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#5165D8" stopOpacity="0.4" />
<stop offset="0.5" stopColor="#283075" stopOpacity="0.16" />
<stop offset="1" stopColor="#111635" stopOpacity="0" />
</radialGradient>
<linearGradient
id="stage-night-cloud"
x1="0"
y1="60"
x2="288"
y2="96"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#4EA4FF" stopOpacity="0.5" />
<stop offset="0.52" stopColor="#696FEA" stopOpacity="0.62" />
<stop offset="1" stopColor="#A85BEA" stopOpacity="0.5" />
</linearGradient>
<filter
id="stage-night-soft"
x="-24"
y="-24"
width="336"
height="144"
filterUnits="userSpaceOnUse"
>
<feGaussianBlur stdDeviation="4" />
</filter>
<pattern id="stage-night-stars" width="288" height="96" patternUnits="userSpaceOnUse">
<g fill="#E4EAFF">
{NIGHTLY_STARS.map((star) => (
<circle
key={`${star.cx}-${star.cy}`}
cx={star.cx}
cy={star.cy}
r={star.r}
fillOpacity={star.opacity}
/>
))}
</g>
<g stroke="#C8D7FF" strokeLinecap="round" strokeOpacity="0.7" strokeWidth="0.6">
{NIGHTLY_SPARKLES.map((sparkle) => (
<g key={`${sparkle.x}-${sparkle.y}`}>
<path d={`M${sparkle.x - 1.5} ${sparkle.y}H${sparkle.x + 1.5}`} />
<path d={`M${sparkle.x} ${sparkle.y - 1.5}V${sparkle.y + 1.5}`} />
</g>
))}
</g>
</pattern>
<pattern id="stage-night-glows" width="640" height="96" patternUnits="userSpaceOnUse">
<rect width="640" height="96" fill="url(#stage-night-glow)" />
</pattern>
</defs>
<rect width="100%" height="96" fill="url(#stage-night-sky)" />
<rect width="100%" height="96" fill="url(#stage-night-glows)" />
<rect width="100%" height="96" fill="url(#stage-night-stars)" />
<g filter="url(#stage-night-soft)">
<path
d="M-12 88C-12 74 0 63 14 63C18 50 30 41 44 41C58 41 70 49 74 62C79 57 86 54 94 54C110 54 123 66 124 82C132 83 138 88 141 96H-12V88Z"
fill="url(#stage-night-cloud)"
/>
</g>
<g filter="url(#stage-night-soft)">
<path
d="M150 96C151 84 161 75 173 75C176 64 186 57 198 57C210 57 220 64 223 75C231 75 238 80 241 87C250 87 257 91 260 96H150Z"
fill="url(#stage-night-cloud)"
fillOpacity="0.8"
/>
</g>
</svg>
);
}
function DevBlueprintArt() {
return (
<svg
className="stage-blueprint h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
<linearGradient
id="stage-bp-paper"
x1="60"
y1="0"
x2="220"
y2="96"
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<stop style={{ stopColor: "var(--stage-bp-top)" }} />
<stop offset="0.5" style={{ stopColor: "var(--stage-bp-mid)" }} />
<stop offset="1" style={{ stopColor: "var(--stage-bp-bottom)" }} />
</linearGradient>
<radialGradient
id="stage-bp-glow"
cx="0"
cy="0"
r="1"
gradientTransform="translate(216 14) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D4F6FF" stopOpacity="0.4" />
<stop offset="0.52" stopColor="#65C8FF" stopOpacity="0.16" />
<stop offset="1" stopColor="#276AF1" stopOpacity="0" />
</radialGradient>
<radialGradient
id="stage-bp-glow-celeste"
cx="0"
cy="0"
r="1"
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D2FFFF" stopOpacity="0.34" />
<stop offset="0.5" stopColor="#48DCF5" stopOpacity="0.18" />
<stop offset="1" stopColor="#277EF1" stopOpacity="0" />
</radialGradient>
<radialGradient
id="stage-bp-glow-violet"
cx="0"
cy="0"
r="1"
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D9D8FF" stopOpacity="0.3" />
<stop offset="0.52" stopColor="#7C8BFF" stopOpacity="0.14" />
<stop offset="1" stopColor="#3155DF" stopOpacity="0" />
</radialGradient>
<pattern id="stage-bp-grid-minor" width="8" height="8" patternUnits="userSpaceOnUse">
<path d="M8 0H0V8" stroke="#EAF6FF" strokeOpacity="0.14" strokeWidth="0.5" />
</pattern>
<pattern id="stage-bp-grid-major" width="32" height="32" patternUnits="userSpaceOnUse">
<path d="M32 0H0V32" stroke="#EAF6FF" strokeOpacity="0.26" strokeWidth="0.6" />
</pattern>
<pattern id="stage-bp-ruler" width="32" height="6" patternUnits="userSpaceOnUse">
<path
d="M4 0V2.5M12 0V2.5M20 0V4M28 0V2.5"
stroke="#DDF7FF"
strokeOpacity="0.5"
strokeWidth="0.5"
/>
</pattern>
<pattern id="stage-bp-glows" width="768" height="96" patternUnits="userSpaceOnUse">
<rect width="768" height="96" fill="url(#stage-bp-glow)" />
<rect width="768" height="96" fill="url(#stage-bp-glow-celeste)" />
<rect width="768" height="96" fill="url(#stage-bp-glow-violet)" />
</pattern>
<pattern id="stage-bp-annotations" width="768" height="96" patternUnits="userSpaceOnUse">
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.6" strokeWidth="0.7">
<path d="M180 64H264" strokeDasharray="5 4" />
<path d="M180 61V67M264 61V67" />
<path d="M276 10V44" strokeDasharray="4 4" strokeOpacity="0.5" />
<path d="M273 10H279M273 44H279" strokeOpacity="0.5" />
<path d="M348 30H428" strokeDasharray="3.5 5" strokeOpacity="0.5" />
<path d="M348 27V33M428 27V33" strokeOpacity="0.5" />
<path d="M512 48V80" strokeDasharray="5 3" strokeOpacity="0.45" />
<path d="M509 48H515M509 80H515" strokeOpacity="0.45" />
<path d="M590 70H724" strokeDasharray="7 4" strokeOpacity="0.55" />
<path d="M590 67V73M724 67V73" strokeOpacity="0.55" />
</g>
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.55" strokeWidth="0.6">
<g>
<path d="M34 60L38 64M38 60L34 64" />
</g>
<g>
<path d="M228 26H234M231 23V29" />
</g>
<g>
<path d="M143 51H149M146 48V54" />
</g>
<g>
<path d="M316 16L322 22M322 16L316 22" />
</g>
<g>
<path d="M468 70H476M472 66V74" />
</g>
<g>
<path d="M558 28L564 34M564 28L558 34" />
</g>
<g>
<path d="M742 44H750M746 40V48" />
</g>
</g>
<g stroke="#DDF7FF" strokeOpacity="0.35" strokeWidth="0.6">
<circle cx="196" cy="38" r="13" strokeDasharray="3.5 4" />
<path d="M196 33V43M191 38H201" strokeOpacity="0.6" strokeWidth="0.4" />
<circle cx="414" cy="64" r="10" strokeDasharray="2.5 3.5" />
<path d="M414 60V68M410 64H418" strokeOpacity="0.6" strokeWidth="0.4" />
<circle cx="648" cy="32" r="15" strokeDasharray="4 5" />
<path d="M648 26V38M642 32H654" strokeOpacity="0.6" strokeWidth="0.4" />
</g>
</pattern>
</defs>
<rect width="100%" height="96" fill="url(#stage-bp-paper)" />
<rect width="100%" height="96" fill="url(#stage-bp-glows)" />
<rect width="100%" height="96" fill="url(#stage-bp-grid-minor)" />
<rect width="100%" height="96" fill="url(#stage-bp-grid-major)" />
<rect width="100%" height="6" fill="url(#stage-bp-ruler)" />
<rect width="100%" height="96" fill="url(#stage-bp-annotations)" />
</svg>
);
}
@@ -31,6 +31,7 @@ import {
useState,
} from "react";
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
import { cn } from "~/lib/utils";
import { type TerminalContextSelection } from "~/lib/terminalContext";
import { useOpenInPreferredEditor } from "../editorPreferences";
@@ -330,7 +331,7 @@ export function TerminalViewport({
const selectionPointerRef = useRef<{ x: number; y: number } | null>(null);
const selectionGestureActiveRef = useRef(false);
const selectionActionRequestIdRef = useRef(0);
const selectionActionOpenRef = useRef(false);
const selectionActionMenuOpenRef = useRef(false);
const selectionActionTimerRef = useRef<number | null>(null);
const keybindingsRef = useRef(keybindings);
const runtimeEnvKey = useMemo(() => runtimeEnvSignature(runtimeEnv), [runtimeEnv]);
@@ -417,6 +418,7 @@ export function TerminalViewport({
const readSelectionAction = (): {
position: { x: number; y: number };
clipboardText: string;
selection: TerminalContextSelection;
} | null => {
const activeTerminal = terminalRef.current;
@@ -445,6 +447,7 @@ export function TerminalViewport({
});
return {
position,
clipboardText: selectionText,
selection: {
terminalId,
terminalLabel: readTerminalLabel(),
@@ -460,7 +463,7 @@ export function TerminalViewport({
clearSelectionAction();
return;
}
if (selectionActionOpenRef.current) {
if (selectionActionMenuOpenRef.current) {
return;
}
const nextAction = readSelectionAction();
@@ -469,20 +472,46 @@ export function TerminalViewport({
return;
}
const requestId = ++selectionActionRequestIdRef.current;
selectionActionOpenRef.current = true;
try {
const clicked = await localApi.contextMenu.show(
[{ id: "add-to-chat", label: "Add to chat" }],
selectionActionMenuOpenRef.current = true;
const clicked = await localApi.contextMenu
.show(
[
{ id: "add-to-chat", label: "Add to chat" },
{ id: "copy", label: "Copy" },
],
nextAction.position,
);
if (requestId !== selectionActionRequestIdRef.current || clicked !== "add-to-chat") {
)
.finally(() => {
selectionActionMenuOpenRef.current = false;
});
if (requestId !== selectionActionRequestIdRef.current || clicked === null) {
return;
}
switch (clicked) {
case "add-to-chat":
handleAddTerminalContext(nextAction.selection);
terminalRef.current?.clearSelection();
terminalRef.current?.focus();
return;
case "copy":
try {
await writeTextToClipboard(nextAction.clipboardText, "terminal selection");
} catch (error) {
if (requestId !== selectionActionRequestIdRef.current) {
return;
}
const activeTerminal = terminalRef.current;
if (activeTerminal) {
writeSystemMessage(
activeTerminal,
error instanceof Error ? error.message : "Unable to copy terminal selection",
);
}
}
if (requestId === selectionActionRequestIdRef.current) {
terminalRef.current?.focus();
}
return;
}
handleAddTerminalContext(nextAction.selection);
terminalRef.current?.clearSelection();
terminalRef.current?.focus();
} finally {
selectionActionOpenRef.current = false;
}
};
+68 -28
View File
@@ -41,6 +41,7 @@ import {
detectComposerTrigger,
expandCollapsedComposerCursor,
replaceTextRange,
shouldSubmitComposerOnEnter,
} from "../../composer-logic";
import { deriveComposerSendState, readFileAsDataUrl } from "../ChatView.logic";
import {
@@ -94,6 +95,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import {
BotIcon,
CheckIcon,
CircleAlertIcon,
ListTodoIcon,
PencilRulerIcon,
@@ -272,16 +274,25 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
{runtimeModeOptions.map((mode) => {
const option = runtimeModeConfig[mode];
const OptionIcon = option.icon;
const isSelected = props.runtimeMode === mode;
return (
<SelectItem key={mode} value={mode} className="min-w-64 py-2">
<div className="grid min-w-0 gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
</span>
<span className="text-muted-foreground text-xs leading-4">
{option.description}
</span>
<SelectItem key={mode} value={mode} hideIndicator className="min-w-64 py-2">
<div className="flex min-w-0 items-center gap-3">
<div className="grid min-w-0 flex-1 gap-0.5">
<span className="inline-flex items-center gap-1.5 font-medium text-foreground">
<OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />
{option.label}
</span>
<span className="text-muted-foreground text-xs leading-4">
{option.description}
</span>
</div>
<CheckIcon
className={cn(
"size-4 text-blue-400",
isSelected ? "opacity-100" : "opacity-0",
)}
/>
</div>
</SelectItem>
);
@@ -389,7 +400,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
export interface ChatComposerHandle {
focusAtEnd: () => void;
focusAt: (cursor: number) => void;
insertTextAtEnd: (text: string) => boolean;
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => boolean;
openModelPicker: () => void;
toggleModelPicker: () => void;
isModelPickerOpen: () => boolean;
@@ -441,6 +452,8 @@ export interface ChatComposerProps {
activeThread: Thread | undefined;
isServerThread: boolean;
isLocalDraftThread: boolean;
forceExpandedOnMobile: boolean;
projectSelectionRequired: boolean;
// Session phase
phase: SessionPhase;
@@ -552,6 +565,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
activeThread,
isServerThread: _isServerThread,
isLocalDraftThread: _isLocalDraftThread,
forceExpandedOnMobile,
projectSelectionRequired,
phase,
isConnecting,
isSendBusy,
@@ -882,7 +897,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const isComposerCollapsedMobile = isMobileViewport && !isComposerFocused;
const isComposerCollapsedMobile =
isMobileViewport && !forceExpandedOnMobile && !isComposerFocused;
// ------------------------------------------------------------------
// Refs
@@ -1135,7 +1151,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
[activePendingIsResponding, activePendingProgress, activePendingResolvedAnswers],
);
const collapsedComposerPrimaryActionDisabled =
phase === "running" || isSendBusy || isConnecting || !composerSendState.hasSendableContent;
phase === "running" ||
isSendBusy ||
isConnecting ||
projectSelectionRequired ||
!composerSendState.hasSendableContent;
const collapsedComposerPrimaryActionLabel = "Send message";
const showMobilePendingAnswerActions =
isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;
@@ -1750,7 +1770,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
return true;
}
}
if (key === "Enter" && !event.shiftKey) {
if (
key === "Enter" &&
shouldSubmitComposerOnEnter({ isMobileViewport, shiftKey: event.shiftKey })
) {
submitComposer();
return true;
}
@@ -1918,18 +1941,25 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
focusAt: (cursor: number) => {
composerEditorRef.current?.focusAt(cursor);
},
insertTextAtEnd: (text: string) => {
insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => {
if (
text.length === 0 ||
isConnecting ||
isComposerApprovalState ||
pendingUserInputs.length > 0 ||
projectSelectionRequired ||
(environmentUnavailable !== null && activePendingProgress === null)
) {
return false;
}
const rangeEnd = promptRef.current.length;
return applyPromptReplacement(rangeEnd, rangeEnd, text);
const prompt = promptRef.current;
const needsLeadingSpace =
(options?.ensureLeadingBoundary ?? false) && prompt.length > 0 && !/\s$/.test(prompt);
return applyPromptReplacement(
prompt.length,
prompt.length,
needsLeadingSpace ? ` ${text}` : text,
);
},
openModelPicker: () => {
setIsComposerModelPickerOpen(true);
@@ -2024,6 +2054,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isConnecting,
isComposerApprovalState,
pendingUserInputs.length,
projectSelectionRequired,
environmentUnavailable,
activePendingProgress,
applyPromptReplacement,
@@ -2061,9 +2092,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
ref={composerSurfaceRef}
data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"}
className={cn(
"chat-composer-glass rounded-[20px] border transition-colors duration-200 has-focus-visible:border-ring/45",
"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 ? "opacity-75" : null,
environmentUnavailable || projectSelectionRequired ? "opacity-75" : null,
composerProviderState.composerSurfaceClassName,
)}
onFocusCapture={(event) => {
@@ -2175,7 +2206,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
@@ -2409,17 +2442,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? "Type your own answer, or leave this blank to use the selected option"
: showPlanFollowUpPrompt && activeProposedPlan
? "Add feedback to refine the plan, or leave this blank to implement it"
: environmentUnavailable
? `${environmentUnavailable.label}: ${connectionStatusText(
environmentUnavailable.connection,
)}`
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
: projectSelectionRequired
? "Choose a project above to start a thread"
: environmentUnavailable
? `${environmentUnavailable.label}: ${connectionStatusText(
environmentUnavailable.connection,
)}`
: phase === "disconnected"
? "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)
}
/>
@@ -2436,7 +2472,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={false}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={false}
hasSendableContent={false}
preserveComposerFocusOnPointerDown
@@ -2547,7 +2585,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
promptHasText={prompt.trim().length > 0}
isSendBusy={isSendBusy}
isConnecting={isConnecting}
isEnvironmentUnavailable={environmentUnavailable !== null}
isEnvironmentUnavailable={
environmentUnavailable !== null || projectSelectionRequired
}
isPreparingWorktree={isPreparingWorktree}
hasSendableContent={composerSendState.hasSendableContent}
preserveComposerFocusOnPointerDown={isMobileViewport}
@@ -190,7 +190,7 @@ const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard(
<div className="min-w-0 flex-1 flex flex-col gap-0.5">
<span className="text-sm font-medium">{option.label}</span>
{option.description && option.description !== option.label ? (
<span className="text-xs text-muted-foreground/50">{option.description}</span>
<span className="text-xs text-muted-foreground">{option.description}</span>
) : null}
</div>
{isSelected ? (
@@ -0,0 +1,114 @@
import type { ScopedProjectRef } from "@t3tools/contracts";
import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";
import { FolderPlusIcon } from "lucide-react";
import { useMemo } from "react";
import { useOpenAddProjectCommandPalette } from "~/commandPaletteContext";
import { useNewThreadHandler } from "~/hooks/useHandleNewThread";
import { useProjects, useThreadShells } from "~/state/entities";
import { sortScopedProjectsForSidebar } from "../Sidebar.logic";
import {
Menu,
MenuItem,
MenuPopup,
MenuRadioGroup,
MenuRadioItem,
MenuSeparator,
MenuTrigger,
} from "../ui/menu";
interface DraftHeroHeadlineProps {
readonly activeProjectRef: ScopedProjectRef | null;
readonly activeProjectTitle: string | null;
}
export function DraftHeroHeadline({
activeProjectRef,
activeProjectTitle,
}: DraftHeroHeadlineProps) {
const projects = useProjects();
const threads = useThreadShells();
const handleNewThread = useNewThreadHandler();
const openAddProject = useOpenAddProjectCommandPalette();
const orderedProjects = useMemo(
() => sortScopedProjectsForSidebar(projects, threads, "updated_at"),
[projects, threads],
);
const projectByKey = useMemo(
() =>
new Map(
orderedProjects.map(
(project) =>
[
scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
project,
] as const,
),
),
[orderedProjects],
);
const activeProjectKey = activeProjectRef === null ? "" : scopedProjectKey(activeProjectRef);
const hasResolvedProject = activeProjectTitle !== null;
const canChooseProject = orderedProjects.length > 0;
const shouldShowProjectMenu = canChooseProject;
const projectSelector = shouldShowProjectMenu ? (
<Menu>
<MenuTrigger
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectTitle ?? "Choose a project"}
</MenuTrigger>
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
<MenuRadioGroup
value={activeProjectKey}
onValueChange={(value) => {
const project = projectByKey.get(value as string);
if (!project || value === activeProjectKey) {
return;
}
void handleNewThread(scopeProjectRef(project.environmentId, project.id), {
replace: true,
});
}}
>
{orderedProjects.map((project) => {
const key = scopedProjectKey(scopeProjectRef(project.environmentId, project.id));
return (
<MenuRadioItem key={key} value={key} closeOnClick>
<span className="min-w-0 truncate">{project.title}</span>
</MenuRadioItem>
);
})}
</MenuRadioGroup>
<MenuSeparator />
<MenuItem onClick={openAddProject}>
<FolderPlusIcon />
New project
</MenuItem>
</MenuPopup>
</Menu>
) : (
<button
type="button"
onClick={openAddProject}
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-muted-foreground/60 underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
>
{activeProjectTitle ?? "Add a project"}
</button>
);
return (
<h1 className="mx-auto w-full max-w-5xl text-center font-normal text-3xl text-foreground tracking-tight sm:text-5xl">
{hasResolvedProject ? (
<>What should we build in {projectSelector}?</>
) : canChooseProject ? (
<>{projectSelector} to start</>
) : (
<>Add a project to start</>
)}
</h1>
);
}
@@ -179,6 +179,7 @@ interface MessagesTimelineProps {
contentInsetEndAdjustment: number;
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
}
// ---------------------------------------------------------------------------
@@ -212,6 +213,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
contentInsetEndAdjustment,
onIsAtEndChange,
onManualNavigation,
hideEmptyPlaceholder = false,
}: MessagesTimelineProps) {
const [expandedTurnIds, setExpandedTurnIds] = useState<ReadonlySet<TurnId>>(new Set());
const [expandedWorkGroupIds, setExpandedWorkGroupIds] = useState<ReadonlySet<string>>(new Set());
@@ -458,6 +460,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
);
if (rows.length === 0 && !isWorking) {
if (hideEmptyPlaceholder) {
return null;
}
return (
<div className="flex h-full items-center justify-center">
<p className="text-sm text-muted-foreground/30">
+42 -5
View File
@@ -31,111 +31,138 @@ import {
RustRoverIcon,
WebStormIcon,
} from "../JetBrainsIcons";
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { cn, isMacPlatform, isWindowsPlatform } from "~/lib/utils";
import { shellEnvironment } from "~/state/shell";
import { useAtomCommand } from "~/state/use-atom-command";
type OpenInOption = {
label: string;
Icon: Icon;
value: EditorId;
kind: "brand" | "generic";
};
const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
const baseOptions: ReadonlyArray<OpenInOption> = [
{
label: "Cursor",
Icon: CursorIcon,
value: "cursor",
kind: "brand",
},
{
label: "Trae",
Icon: TraeIcon,
value: "trae",
kind: "brand",
},
{
label: "Kiro",
Icon: KiroIcon,
value: "kiro",
kind: "brand",
},
{
label: "VS Code",
Icon: VisualStudioCode,
value: "vscode",
kind: "brand",
},
{
label: "VS Code Insiders",
Icon: VisualStudioCodeInsiders,
value: "vscode-insiders",
kind: "brand",
},
{
label: "VSCodium",
Icon: VSCodium,
value: "vscodium",
kind: "brand",
},
{
label: "Zed",
Icon: Zed,
value: "zed",
kind: "brand",
},
{
label: "Antigravity",
Icon: AntigravityIcon,
value: "antigravity",
kind: "brand",
},
{
label: "IntelliJ IDEA",
Icon: IntelliJIdeaIcon,
value: "idea",
kind: "brand",
},
{
label: "Aqua",
Icon: AquaIcon,
value: "aqua",
kind: "brand",
},
{
label: "CLion",
Icon: CLionIcon,
value: "clion",
kind: "brand",
},
{
label: "DataGrip",
Icon: DataGripIcon,
value: "datagrip",
kind: "brand",
},
{
label: "DataSpell",
Icon: DataSpellIcon,
value: "dataspell",
kind: "brand",
},
{
label: "GoLand",
Icon: GoLandIcon,
value: "goland",
kind: "brand",
},
{
label: "PhpStorm",
Icon: PhpStormIcon,
value: "phpstorm",
kind: "brand",
},
{
label: "PyCharm",
Icon: PyCharmIcon,
value: "pycharm",
kind: "brand",
},
{
label: "Rider",
Icon: RiderIcon,
value: "rider",
kind: "brand",
},
{
label: "RubyMine",
Icon: RubyMineIcon,
value: "rubymine",
kind: "brand",
},
{
label: "RustRover",
Icon: RustRoverIcon,
value: "rustrover",
kind: "brand",
},
{
label: "WebStorm",
Icon: WebStormIcon,
value: "webstorm",
kind: "brand",
},
{
label: isMacPlatform(platform)
@@ -145,12 +172,17 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
: "Files",
Icon: FolderClosedIcon,
value: "file-manager",
kind: "generic",
},
];
const availableEditorSet = new Set(availableEditors);
return baseOptions.filter((option) => availableEditorSet.has(option.value));
};
function getOpenInIconClass(kind: OpenInOption["kind"]) {
return cn(kind === "brand" ? "text-foreground opacity-100" : "text-muted-foreground");
}
export const OpenInPicker = memo(function OpenInPicker({
environmentId,
keybindings,
@@ -233,7 +265,12 @@ export const OpenInPicker = memo(function OpenInPicker({
disabled={!preferredEditor || !openInCwd}
onClick={() => openInEditor(preferredEditor)}
>
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
{primaryOption?.Icon && (
<primaryOption.Icon
aria-hidden="true"
className={cn("size-3.5", getOpenInIconClass(primaryOption.kind))}
/>
)}
<span
className={
compact
@@ -259,9 +296,9 @@ export const OpenInPicker = memo(function OpenInPicker({
</MenuTrigger>
<MenuPopup align="end">
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
{options.map(({ label, Icon, value }) => (
{options.map(({ label, Icon, value, kind }) => (
<MenuItem key={value} onClick={() => openInEditor(value)}>
<Icon aria-hidden="true" className="text-muted-foreground" />
<Icon aria-hidden="true" className={getOpenInIconClass(kind)} />
{label}
{value === preferredEditor && openFavoriteEditorShortcutLabel && (
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
+96 -56
View File
@@ -16,7 +16,7 @@ import {
} from "@t3tools/shared/model";
import { memo, useCallback, useState } from "react";
import type { VariantProps } from "class-variance-authority";
import { ChevronDownIcon } from "lucide-react";
import { CheckIcon, ChevronDownIcon } from "lucide-react";
import { Button, buttonVariants } from "../ui/button";
import {
Menu,
@@ -30,6 +30,7 @@ import {
import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { cn } from "~/lib/utils";
import { Badge } from "../ui/badge";
type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
@@ -46,6 +47,17 @@ type TraitsPersistence =
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
function DefaultBadge() {
return (
<Badge
variant="outline"
className="inline-flex h-4 w-fit min-w-0 items-center justify-center gap-0 border-border/70 bg-muted/60 px-1.5 py-0 font-semibold text-[10px] text-muted-foreground leading-none sm:h-4"
>
Default
</Badge>
);
}
function replaceDescriptorCurrentValue(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
descriptorId: string,
@@ -285,62 +297,90 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
return (
<>
{selectDescriptors.map((descriptor, index) => (
<div key={descriptor.id}>
{index > 0 ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
{descriptor.label}
</div>
{ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
Your prompt contains &quot;ultrathink&quot; in the text. Remove it to change this
option.
{selectDescriptors.map((descriptor, index) => {
const selectedValue =
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "ultrathink"
: (getDescriptorStringValue(descriptor) ?? "");
return (
<div key={descriptor.id}>
{index > 0 ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">
{descriptor.label}
</div>
) : null}
<MenuRadioGroup
value={
ultrathinkPromptControlled && descriptor.id === primarySelectDescriptor?.id
? "ultrathink"
: (getDescriptorStringValue(descriptor) ?? "")
}
onValueChange={(value) => handleSelectChange(descriptor, value)}
>
{descriptor.options.map((option) => (
<MenuRadioItem
key={option.id}
value={option.id}
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
>
{option.label}
{option.isDefault ? " (default)" : ""}
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</div>
))}
{booleanDescriptors.map((descriptor, index) => (
<div key={descriptor.id}>
{index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
{descriptor.label}
</div>
<MenuRadioGroup
value={descriptor.currentValue === true ? "on" : "off"}
onValueChange={(value) => {
updateDescriptors(
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
);
}}
>
<MenuRadioItem value="on">On</MenuRadioItem>
<MenuRadioItem value="off">Off</MenuRadioItem>
</MenuRadioGroup>
</MenuGroup>
</div>
))}
{ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id ? (
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
Your prompt contains &quot;ultrathink&quot; in the text. Remove it to change this
option.
</div>
) : null}
<MenuRadioGroup
value={selectedValue}
onValueChange={(value) => handleSelectChange(descriptor, value)}
>
{descriptor.options.map((option) => (
<MenuRadioItem
key={option.id}
value={option.id}
hideIndicator
disabled={ultrathinkInBodyText && descriptor.id === primarySelectDescriptor?.id}
>
<span className="flex w-full min-w-0 items-center justify-between gap-3">
<span className="min-w-0 truncate">
{option.label}
{option.isDefault ? (
<>
{" "}
<DefaultBadge />
</>
) : null}
</span>
{option.id === selectedValue ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</div>
);
})}
{booleanDescriptors.map((descriptor, index) => {
const selectedValue = descriptor.currentValue === true ? "on" : "off";
return (
<div key={descriptor.id}>
{index > 0 || selectDescriptors.length > 0 ? <MenuDivider /> : null}
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
{descriptor.label}
</div>
<MenuRadioGroup
value={selectedValue}
onValueChange={(value) => {
updateDescriptors(
replaceDescriptorCurrentValue(descriptors, descriptor.id, value === "on"),
);
}}
>
{(["on", "off"] as const).map((value) => (
<MenuRadioItem key={value} value={value} hideIndicator>
<span className="flex w-full min-w-0 items-center justify-between gap-3">
<span>{value === "on" ? "On" : "Off"}</span>
{value === selectedValue ? (
<CheckIcon className="size-3.5 shrink-0 text-blue-400" />
) : null}
</span>
</MenuRadioItem>
))}
</MenuRadioGroup>
</MenuGroup>
</div>
);
})}
</>
);
});
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more