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
26 changed files with 1385 additions and 340 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
@@ -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;
+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(
@@ -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(
+21 -3
View File
@@ -4,10 +4,18 @@ 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">
@@ -15,7 +15,6 @@ import {
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveSidebarThreadRowTransientProps,
resolveThreadRowClassName,
resolveThreadStatusPill,
shouldClearThreadSelectionOnMouseDown,
@@ -39,51 +38,6 @@ import {
const localEnvironmentId = EnvironmentId.make("environment-local");
describe("resolveSidebarThreadRowTransientProps", () => {
it("only publishes rename state to the row being edited", () => {
expect(
resolveSidebarThreadRowTransientProps({
threadKey: "thread-1",
renamingThreadKey: "thread-1",
renamingTitle: "Edited title",
confirmingArchiveThreadKey: null,
}),
).toEqual({
isRenaming: true,
renamingTitle: "Edited title",
isConfirmingArchive: false,
});
expect(
resolveSidebarThreadRowTransientProps({
threadKey: "thread-2",
renamingThreadKey: "thread-1",
renamingTitle: "Edited title",
confirmingArchiveThreadKey: null,
}),
).toEqual({
isRenaming: false,
renamingTitle: "",
isConfirmingArchive: false,
});
});
it("only publishes archive confirmation state to its target row", () => {
expect(
resolveSidebarThreadRowTransientProps({
threadKey: "thread-2",
renamingThreadKey: null,
renamingTitle: "",
confirmingArchiveThreadKey: "thread-2",
}),
).toEqual({
isRenaming: false,
renamingTitle: "",
isConfirmingArchive: true,
});
});
});
describe("resolveSidebarStageBadgeLabel", () => {
it("returns Nightly for nightly primary server versions", () => {
expect(
-19
View File
@@ -17,25 +17,6 @@ export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
// nearby thread usually reuses an already-hot subscription.
export const SIDEBAR_THREAD_PREWARM_LIMIT = 10;
export type SidebarNewThreadEnvMode = "local" | "worktree";
export function resolveSidebarThreadRowTransientProps(input: {
threadKey: string;
renamingThreadKey: string | null;
renamingTitle: string;
confirmingArchiveThreadKey: string | null;
}): {
isRenaming: boolean;
renamingTitle: string;
isConfirmingArchive: boolean;
} {
const isRenaming = input.renamingThreadKey === input.threadKey;
return {
isRenaming,
renamingTitle: isRenaming ? input.renamingTitle : "",
isConfirmingArchive: input.confirmingArchiveThreadKey === input.threadKey,
};
}
type SidebarProject = {
id: string;
title: string;
+53 -37
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,
@@ -192,7 +193,6 @@ import {
resolveSidebarNewThreadSeedContext,
resolveSidebarNewThreadEnvMode,
resolveSidebarStageBadgeLabel,
resolveSidebarThreadRowTransientProps,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -325,13 +325,13 @@ interface SidebarThreadRowProps {
isActive: boolean;
jumpLabel: string | null;
appSettingsConfirmThreadArchive: boolean;
isRenaming: boolean;
renamingThreadKey: string | null;
renamingTitle: string;
setRenamingTitle: (title: string) => void;
startThreadRename: (threadKey: string, title: string) => void;
renamingInputRef: React.RefObject<HTMLInputElement | null>;
renamingCommittedRef: React.RefObject<boolean>;
isConfirmingArchive: boolean;
confirmingArchiveThreadKey: string | null;
setConfirmingArchiveThreadKey: React.Dispatch<React.SetStateAction<string | null>>;
confirmArchiveButtonRefs: React.RefObject<Map<string, HTMLButtonElement>>;
handleThreadClick: (
@@ -362,13 +362,13 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
isActive,
jumpLabel,
appSettingsConfirmThreadArchive,
isRenaming,
renamingThreadKey,
renamingTitle,
setRenamingTitle,
startThreadRename,
renamingInputRef,
renamingCommittedRef,
isConfirmingArchive,
confirmingArchiveThreadKey,
setConfirmingArchiveThreadKey,
confirmArchiveButtonRefs,
handleThreadClick,
@@ -469,8 +469,8 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
const pr = resolveThreadPr(thread.branch, gitStatus.data);
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const showArchiveConfirmation = isConfirmingArchive && !isThreadRunning;
const threadMetaClassName = showArchiveConfirmation
const isConfirmingArchive = confirmingArchiveThreadKey === threadKey && !isThreadRunning;
const threadMetaClassName = isConfirmingArchive
? "pointer-events-none opacity-0"
: !isThreadRunning
? "pointer-events-none transition-opacity duration-150 max-sm:pr-6 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
@@ -503,7 +503,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
(event: React.MouseEvent) => {
// Already renaming this row: a double-click on the row chrome (outside the
// input) must not restart and discard the in-progress edit.
if (isRenaming) return;
if (renamingThreadKey === threadKey) return;
// On mobile the first tap navigates and closes the sidebar sheet, so the
// inline rename can't be shown. Renaming there stays on the context menu.
if (isMobile) return;
@@ -515,7 +515,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
event.preventDefault();
startThreadRename(threadKey, thread.title);
},
[isMobile, isRenaming, startThreadRename, threadKey, thread.title],
[isMobile, renamingThreadKey, startThreadRename, threadKey, thread.title],
);
const handleRowKeyDown = useCallback(
(event: React.KeyboardEvent) => {
@@ -710,7 +710,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{isRenaming ? (
{renamingThreadKey === threadKey ? (
<input
ref={handleRenameInputRef}
className="min-w-0 flex-1 truncate text-base sm:text-xs bg-transparent outline-none border border-ring rounded px-0.5"
@@ -784,7 +784,7 @@ export const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThr
isRemoteThread ? "max-sm:min-w-24" : "max-sm:min-w-20"
}`}
>
{showArchiveConfirmation ? (
{isConfirmingArchive ? (
<button
ref={handleConfirmArchiveRef}
type="button"
@@ -996,12 +996,6 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
{shouldShowThreadPanel &&
renderedThreads.map((thread) => {
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
const transientProps = resolveSidebarThreadRowTransientProps({
threadKey,
renamingThreadKey,
renamingTitle,
confirmingArchiveThreadKey,
});
return (
<SidebarThreadRow
key={threadKey}
@@ -1011,13 +1005,13 @@ const SidebarProjectThreadList = memo(function SidebarProjectThreadList(
isActive={activeRouteThreadKey === threadKey}
jumpLabel={threadJumpLabelByKey.get(threadKey) ?? null}
appSettingsConfirmThreadArchive={appSettingsConfirmThreadArchive}
isRenaming={transientProps.isRenaming}
renamingTitle={transientProps.renamingTitle}
renamingThreadKey={renamingThreadKey}
renamingTitle={renamingTitle}
setRenamingTitle={setRenamingTitle}
startThreadRename={startThreadRename}
renamingInputRef={renamingInputRef}
renamingCommittedRef={renamingCommittedRef}
isConfirmingArchive={transientProps.isConfirmingArchive}
confirmingArchiveThreadKey={confirmingArchiveThreadKey}
setConfirmingArchiveThreadKey={setConfirmingArchiveThreadKey}
confirmArchiveButtonRefs={confirmArchiveButtonRefs}
handleThreadClick={handleThreadClick}
@@ -2751,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>
@@ -2798,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;
}
};
+36
View File
@@ -231,6 +231,42 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
}
/* Stage-channel sidebar art; ::after ramps to the sidebar bg color and the
mask lets the surface grain show through at the boundary. */
.sidebar-stage-backdrop {
mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
-webkit-mask-image: linear-gradient(to bottom, black 0%, black 55%, transparent 92%);
}
.sidebar-stage-backdrop::after {
content: "";
position: absolute;
inset: 0;
background: linear-gradient(
to bottom,
transparent 0%,
transparent 28%,
color-mix(in srgb, var(--app-chrome-background) 10%, transparent) 40%,
color-mix(in srgb, var(--app-chrome-background) 30%, transparent) 52%,
color-mix(in srgb, var(--app-chrome-background) 58%, transparent) 64%,
color-mix(in srgb, var(--app-chrome-background) 82%, transparent) 75%,
color-mix(in srgb, var(--app-chrome-background) 96%, transparent) 85%,
var(--app-chrome-background) 93%
);
}
.stage-blueprint {
--stage-bp-top: #67c2ff;
--stage-bp-mid: #347ff8;
--stage-bp-bottom: #1538d0;
}
.dark .stage-blueprint {
--stage-bp-top: #3a7ad1;
--stage-bp-mid: #2050ae;
--stage-bp-bottom: #101f6e;
}
.workspace-topbar {
display: flex;
height: var(--workspace-topbar-height);
+17 -9
View File
@@ -165,16 +165,24 @@ The backend reads observability config at process start. If you change OTLP env
The trace file is the fastest way to inspect raw span data.
Resolve the production or explicitly configured trace file once. Runtime state lives under the
base directory's `userdata` folder:
```bash
TRACE_FILE="${T3CODE_HOME:-$HOME/.t3}/userdata/logs/server.trace.ndjson"
```
Tail it:
```bash
tail -f "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
tail -f "$TRACE_FILE"
```
In monorepo dev, use:
For an implicit monorepo dev server, use:
```bash
tail -f ./dev/logs/server.trace.ndjson
TRACE_FILE="$HOME/.t3/dev/logs/server.trace.ndjson"
tail -f "$TRACE_FILE"
```
Show failed spans:
@@ -185,7 +193,7 @@ jq -c 'select(.exit._tag != "Success") | {
durationMs,
exit,
attributes
}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
}' "$TRACE_FILE"
```
Show slow spans:
@@ -196,7 +204,7 @@ jq -c 'select(.durationMs > 1000) | {
durationMs,
traceId,
spanId
}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
}' "$TRACE_FILE"
```
Inspect embedded log events:
@@ -213,7 +221,7 @@ jq -c 'select(any(.events[]?; .attributes["effect.logLevel"] != null)) | {
level: .attributes["effect.logLevel"]
}
]
}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
}' "$TRACE_FILE"
```
Follow one trace:
@@ -224,7 +232,7 @@ jq -r 'select(.traceId == "TRACE_ID_HERE") | [
.spanId,
(.parentSpanId // "-"),
.durationMs
] | @tsv' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
] | @tsv' "$TRACE_FILE"
```
Filter orchestration commands:
@@ -235,7 +243,7 @@ jq -c 'select(.attributes["orchestration.command_type"] != null) | {
durationMs,
commandType: .attributes["orchestration.command_type"],
aggregateKind: .attributes["orchestration.aggregate_kind"]
}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
}' "$TRACE_FILE"
```
Filter git activity:
@@ -250,7 +258,7 @@ jq -c 'select(.attributes["git.operation"] != null) | {
.events[]
| select(.name == "git.hook.started" or .name == "git.hook.finished")
]
}' "$T3CODE_HOME/userdata/logs/server.trace.ndjson"
}' "$TRACE_FILE"
```
### Use Tempo When You Need A Real Trace Viewer
+5 -3
View File
@@ -3,13 +3,15 @@
- `vp run dev` — Starts contracts, server, and web in watch mode.
- `vp run dev:server` — Starts just the WebSocket server. The server process runs on Bun (`@effect/platform-bun` + `BunPtyAdapter`), but task running uses `vp run`.
- `vp run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_HOME` to `~/.t3` — the same shared home the desktop/production app uses. Override with `--home-dir` (see below) to keep dev state separate.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`vp run dev -- --home-dir ~/.t3-2`
- Dev commands implicitly use `~/.t3/dev`, keeping development state separate from `~/.t3/userdata`. An explicit `--home-dir <path>` stores state under `<path>/userdata`; the base directory remains available for caches, worktrees, and other shared data.
- Web dev commands do not auto-open a browser. Open the one-time pairing URL printed by the server so the first browser navigation is authenticated. Set `T3CODE_NO_BROWSER=0` only when interactive auto-open is intentional.
- Pass dev-runner flags directly after the root task name, for example:
`vp run dev --home-dir /tmp/t3code-dev`
- `vp run start` — Runs the production server (serves built web app as static files).
- `vp run build` — Builds contracts, web app, and server.
- `vp run typecheck` — Strict TypeScript checks for all packages.
- `vp run test` — Runs workspace tests.
- `node apps/server/scripts/t3-sqlite-state.ts <query|exec> --base-dir <path> ...` — Inspects or seeds an isolated T3 SQLite database; writes create a private backup first.
- `vp run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
- `vp run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
- `vp run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
+51 -12
View File
@@ -1,5 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeOS from "node:os";
import * as NetService from "@t3tools/shared/Net";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { assert, describe, it } from "@effect/vitest";
@@ -52,7 +51,7 @@ function mockProcess(exit: number | PlatformError.PlatformError) {
const devServerInput = {
mode: "dev:server",
t3Home: "/tmp/t3code-dev-runner",
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
@@ -127,16 +126,15 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
});
describe("createDevRunnerEnv", () => {
it.effect("defaults T3CODE_HOME to ~/.t3 when not provided", () =>
it.effect("leaves the shared home implicit and disables browser auto-open", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
@@ -144,7 +142,48 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
devUrl: undefined,
});
assert.equal(env.T3CODE_HOME, path.resolve(NodeOS.homedir(), ".t3"));
assert.equal(env.T3CODE_HOME, undefined);
assert.equal(env.T3CODE_NO_BROWSER, "1");
}),
);
it.effect("allows browser auto-open to be explicitly enabled", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: {},
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: true,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_NO_BROWSER, "0");
}),
);
it.effect("requires the browser flag even when the environment enables auto-open", () =>
Effect.gen(function* () {
const env = yield* createDevRunnerEnv({
mode: "dev",
baseEnv: { T3CODE_NO_BROWSER: "0" },
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
browser: false,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
port: undefined,
devUrl: undefined,
});
assert.equal(env.T3CODE_NO_BROWSER, "1");
}),
);
@@ -157,7 +196,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/custom-t3",
noBrowser: true,
browser: false,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
host: "0.0.0.0",
@@ -187,7 +226,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
@@ -210,7 +249,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: false,
host: undefined,
@@ -231,7 +270,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/my-t3",
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
@@ -259,7 +298,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: "/tmp/my-t3",
noBrowser: true,
browser: true,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: "127.0.0.1",
@@ -288,7 +327,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
serverOffset: 0,
webOffset: 0,
t3Home: undefined,
noBrowser: undefined,
browser: undefined,
autoBootstrapProjectFromCwd: undefined,
logWebSocketEvents: undefined,
host: undefined,
+21 -15
View File
@@ -221,7 +221,7 @@ interface CreateDevRunnerEnvInput {
readonly serverOffset: number;
readonly webOffset: number;
readonly t3Home: string | undefined;
readonly noBrowser: boolean | undefined;
readonly browser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
@@ -235,7 +235,7 @@ export function createDevRunnerEnv({
serverOffset,
webOffset,
t3Home,
noBrowser,
browser,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
host,
@@ -245,7 +245,8 @@ export function createDevRunnerEnv({
return Effect.gen(function* () {
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
const webPort = BASE_WEB_PORT + webOffset;
const resolvedBaseDir = yield* resolveBaseDir(t3Home);
const configuredBaseDir = t3Home?.trim() || baseEnv.T3CODE_HOME?.trim() || undefined;
const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
const isDesktopMode = mode === "dev:desktop";
const output: NodeJS.ProcessEnv = {
@@ -254,9 +255,14 @@ export function createDevRunnerEnv({
VITE_DEV_SERVER_URL:
devUrl?.toString() ??
`http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
T3CODE_HOME: resolvedBaseDir,
};
if (configuredBaseDir !== undefined) {
output.T3CODE_HOME = resolvedBaseDir;
} else {
delete output.T3CODE_HOME;
}
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
@@ -274,10 +280,8 @@ export function createDevRunnerEnv({
output.T3CODE_HOST = host;
}
if (!isDesktopMode && noBrowser !== undefined) {
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
} else if (!isDesktopMode) {
delete output.T3CODE_NO_BROWSER;
if (!isDesktopMode) {
output.T3CODE_NO_BROWSER = browser === true ? "0" : "1";
}
if (autoBootstrapProjectFromCwd !== undefined) {
@@ -469,7 +473,7 @@ export function resolveModePortOffsets<R = NetService.NetService>({
interface DevRunnerCliInput {
readonly mode: DevMode;
readonly t3Home: string | undefined;
readonly noBrowser: boolean | undefined;
readonly browser: boolean | undefined;
readonly autoBootstrapProjectFromCwd: boolean | undefined;
readonly logWebSocketEvents: boolean | undefined;
readonly host: string | undefined;
@@ -507,7 +511,7 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
serverOffset,
webOffset,
t3Home: input.t3Home,
noBrowser: input.noBrowser,
browser: input.browser,
autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
logWebSocketEvents: input.logWebSocketEvents,
host: input.host,
@@ -519,9 +523,10 @@ export function runDevRunnerWithInput(input: DevRunnerCliInput) {
serverOffset !== offset || webOffset !== offset
? ` selectedOffset(server=${serverOffset},web=${webOffset})`
: "";
const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME);
yield* Effect.logInfo(
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${String(env.T3CODE_HOME)}`,
`[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
);
if (input.dryRun) {
@@ -586,12 +591,13 @@ const devRunnerCli = Command.make("dev-runner", {
Argument.withDescription("Development mode to run."),
),
t3Home: Flag.string("home-dir").pipe(
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
Flag.withDescription(
"Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
),
Flag.withFallbackConfig(optionalStringConfig("T3CODE_HOME")),
),
noBrowser: Flag.boolean("no-browser").pipe(
Flag.withDescription("Browser auto-open toggle (equivalent to T3CODE_NO_BROWSER)."),
Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_NO_BROWSER")),
browser: Flag.boolean("browser").pipe(
Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
),
autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(