Compare commits

...
Author SHA1 Message Date
Cursor Agent 7885e2ba38 Fix: resolve shell option on Windows to support .cmd/.bat shims
On Windows, Node.js spawn with shell:false cannot execute .cmd/.bat
shims — only native .exe binaries. The previous commit forced
shell:false for gh CLI invocations to prevent command injection, but
this regressed Windows setups where gh is installed as a .cmd shim
(e.g., via Scoop or corporate package managers).

Add resolveShellOption() in processRunner.ts that, on Windows, probes
PATH for the first matching file: if it's a .cmd/.bat shim, shell:true
is used (required for cmd.exe to interpret the shim); if it's an .exe,
shell:false is preserved (preventing injection). On non-Windows
platforms, the caller's explicit value is used (defaulting to false).
2026-04-10 08:11:19 +00:00
Julius Marminge 1fd62443af Merge branch 'main' into codex/fix-github-cli-command-injection-vulnerability 2026-04-10 00:59:11 -07:00
Julius Marminge cc5871a8ba Mitigate Windows GH CLI command injection 2026-04-10 00:58:49 -07:00
Julius Marminge 1a05d8ca1a Document remote server network access setup (#1872) 2026-04-10 07:43:38 +00:00
Julius Marminge cf9f236c80 Add headless t3 serve pairing output (#1871) 2026-04-10 00:12:52 -07:00
Julius Marminge e82b987386 Select desktop backend port by sequential scan (#1870) 2026-04-09 21:51:04 -07:00
Julius Marminge ea9e61b266 Align chat composer and toolbar widths (#1869) 2026-04-10 04:42:52 +00:00
Julius Marminge e32077cee7 Persist client settings and saved environment secrets (#1868) 2026-04-09 20:18:41 -07:00
Noah GregoryandJulius Marminge 5d9eb18312 fix: don't let un-updateable builds check for an update (#1808)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 18:27:24 -07:00
Noah Gregory abb84c09e3 fix: use different bundle ID for dev runner (#1806) 2026-04-09 17:57:50 -07:00
Magnus BuvarpandJulius Marminge 65d797c13e feat(web): add surround selection in composer (#1502)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-10 00:53:06 +00:00
Jacob 7c0849fe2e fix(web): harmonize typography in chat messages and code blocks (#1861) 2026-04-09 17:52:41 -07:00
Yash SinghandJulius Marminge 592c234fd5 fix: make file uri links clickable (#1867)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 17:49:35 -07:00
66d76b5d02 Fix composer footer focus ring overflow (#1865)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-04-10 00:40:27 +00:00
Julius Marmingeandcodex 528bb2a1fa [codex] Harden WebSocket reconnect recovery (#1864)
Co-authored-by: codex <[email protected]>
2026-04-09 17:23:37 -07:00
869789b4ed Extract ChatComposer to fix composer keystroke re-renders (#1857)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-04-09 16:37:47 -07:00
Julius Marminge 9bedd7140c Debounce reconnect disconnect logging (#1862) 2026-04-09 15:39:28 -07:00
Julius MarmingeandJulius Marminge 70f5dfcef7 Stabilize keybindings toast stream setup (#1860)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-09 14:26:28 -07:00
Julius Marminge 9847e9b621 fix build (#1859) 2026-04-09 21:20:05 +00:00
Julius Marminge b547fee77e Scope git toast state by thread ref (#1855) 2026-04-09 19:59:30 +00:00
Julius Marminge 7b3cdc6a8c Clarify environment and workspace picker labels (#1854) 2026-04-09 12:51:17 -07:00
94 changed files with 8637 additions and 3489 deletions

No files matched your search

+63 -44
View File
@@ -1,68 +1,87 @@
# Remote Access Setup
# Remote Access
Use this when you want to open T3 Code from another device (phone, tablet, another laptop).
Use this when you want to connect to a T3 Code server from another device such as a phone, tablet, or separate desktop app.
## CLI ↔ Env option map
## Recommended Setup
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
Use a trusted private network that meshes your devices together, such as a tailnet.
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
That gives you:
> TIP: Use the `--help` flag to see all available options and their descriptions.
- a stable address to connect to
- transport security at the network layer
- less exposure than opening the server to the public internet
## Security First
## Enabling Network Access
- Always set `--auth-token` before exposing the server outside localhost.
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
- Treat the token like a password.
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
There are two ways to expose your server for remote connections: from the desktop app or from the CLI.
## 1) Build + run server for remote access
### Option 1: Desktop App
Remote access should use the built web app (not local Vite redirect mode).
If you are already running the desktop app and want to make it reachable from other devices:
1. Open **Settings** → **Connections**.
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
4. Use **Create Link** to generate a pairing link you can share with another device.
### Option 2: Headless Server (CLI)
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
Run the server with `t3 serve`.
```bash
bun run build
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host 0.0.0.0 --port 3773 --auth-token "$TOKEN" --no-browser
npx t3 serve --host "$(tailscale ip -4)"
```
Then open on your phone:
`t3 serve` starts the server without opening a browser and prints:
`http://<your-machine-ip>:3773`
- a connection string
- a pairing token
- a pairing URL
- a QR code for the pairing URL
Example:
From there, connect from another device in either of these ways:
`http://192.168.1.42:3773`
- scan the QR code on your phone
- in the desktop app, enter the full pairing URL
- in the desktop app, enter the host and token separately
Notes:
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
- `--host 0.0.0.0` listens on all IPv4 interfaces.
- `--no-browser` prevents local auto-open, which is usually better for headless/remote sessions.
- Ensure your OS firewall allows inbound TCP on the selected port.
> Note
> The GUIs do not currently support adding projects on remote environments.
> For now, use `t3 project ...` on the server machine instead.
> Full GUI support for remote project management is coming soon.
## 2) Tailnet / Tailscale access
## How Pairing Works
If you use Tailscale, you can bind directly to your Tailnet address.
The remote device does not need a long-lived secret up front.
```bash
TAILNET_IP="$(tailscale ip -4)"
TOKEN="$(openssl rand -hex 24)"
bun run --cwd apps/server start -- --host "$(tailscale ip -4)" --port 3773 --auth-token "$TOKEN" --no-browser
```
Instead:
Open from any device in your tailnet:
1. `t3 serve` issues a one-time owner pairing token.
2. The remote device exchanges that token with the server.
3. The server creates an authenticated session for that device.
`http://<tailnet-ip>:3773`
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
You can also bind `--host 0.0.0.0` and connect through the Tailnet IP, but binding directly to the Tailnet IP limits exposure.
## Managing Access Later
Use `t3 auth` to manage access after the initial pairing flow.
Typical uses:
- issue additional pairing credentials
- inspect active sessions
- revoke old pairing links or sessions
Use `t3 auth --help` and the nested subcommand help pages for the full reference.
## Security Notes
- Treat pairing URLs and pairing tokens like passwords.
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
+1 -1
View File
@@ -18,7 +18,7 @@ import { fileURLToPath } from "node:url";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_BUNDLE_ID = "com.t3tools.t3code";
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
const LAUNCHER_VERSION = 1;
const __dirname = dirname(fileURLToPath(import.meta.url));
+56
View File
@@ -0,0 +1,56 @@
import { describe, expect, it, vi } from "vitest";
import { resolveDesktopBackendPort } from "./backendPort";
describe("resolveDesktopBackendPort", () => {
it("returns the starting port when it is available", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3773);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3773);
expect(canListenOnHost).toHaveBeenCalledTimes(1);
expect(canListenOnHost).toHaveBeenCalledWith(3773, "127.0.0.1");
});
it("increments sequentially until it finds an available port", async () => {
const canListenOnHost = vi.fn(async (port: number) => port === 3775);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 3773,
canListenOnHost,
}),
).resolves.toBe(3775);
expect(canListenOnHost.mock.calls).toEqual([
[3773, "127.0.0.1"],
[3774, "127.0.0.1"],
[3775, "127.0.0.1"],
]);
});
it("fails when the scan range is exhausted", async () => {
const canListenOnHost = vi.fn(async () => false);
await expect(
resolveDesktopBackendPort({
host: "127.0.0.1",
startPort: 65534,
maxPort: 65535,
canListenOnHost,
}),
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
expect(canListenOnHost.mock.calls).toEqual([
[65534, "127.0.0.1"],
[65535, "127.0.0.1"],
]);
});
});
+53
View File
@@ -0,0 +1,53 @@
import * as Effect from "effect/Effect";
import { NetService } from "@t3tools/shared/Net";
export const DEFAULT_DESKTOP_BACKEND_PORT = 3773;
const MAX_TCP_PORT = 65_535;
export interface ResolveDesktopBackendPortOptions {
readonly host: string;
readonly startPort?: number;
readonly maxPort?: number;
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
}
const defaultCanListenOnHost = async (port: number, host: string): Promise<boolean> =>
Effect.service(NetService).pipe(
Effect.flatMap((net) => net.canListenOnHost(port, host)),
Effect.provide(NetService.layer),
Effect.runPromise,
);
const isValidPort = (port: number): boolean =>
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
export async function resolveDesktopBackendPort({
host,
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
maxPort = MAX_TCP_PORT,
canListenOnHost = defaultCanListenOnHost,
}: ResolveDesktopBackendPortOptions): Promise<number> {
if (!isValidPort(startPort)) {
throw new Error(`Invalid desktop backend start port: ${startPort}`);
}
if (!isValidPort(maxPort)) {
throw new Error(`Invalid desktop backend max port: ${maxPort}`);
}
if (maxPort < startPort) {
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
}
// Keep desktop startup predictable across app restarts by probing upward from
// the same preferred port instead of picking a fresh ephemeral port.
for (let port = startPort; port <= maxPort; port += 1) {
if (await canListenOnHost(port, host)) {
return port;
}
}
throw new Error(
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
);
}
+234
View File
@@ -0,0 +1,234 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
EnvironmentId,
type ClientSettings,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
type DesktopSecretStorage,
} from "./clientPersistence";
const tempDirectories: string[] = [];
afterEach(() => {
for (const directory of tempDirectories.splice(0)) {
fs.rmSync(directory, { recursive: true, force: true });
}
});
function makeTempPath(fileName: string): string {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), "t3-client-persistence-test-"));
tempDirectories.push(directory);
return path.join(directory, fileName);
}
function makeSecretStorage(available: boolean): DesktopSecretStorage {
return {
isEncryptionAvailable: () => available,
encryptString: (value) => Buffer.from(`enc:${value}`, "utf8"),
decryptString: (value) => {
const decoded = value.toString("utf8");
if (!decoded.startsWith("enc:")) {
throw new Error("invalid secret");
}
return decoded.slice("enc:".length);
},
};
}
const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
};
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: "2026-04-09T01:00:00.000Z",
};
describe("clientPersistence", () => {
it("persists and reloads client settings", () => {
const settingsPath = makeTempPath("client-settings.json");
writeClientSettings(settingsPath, clientSettings);
expect(readClientSettings(settingsPath)).toEqual(clientSettings);
});
it("persists and reloads saved environment metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
});
it("persists encrypted saved environment secrets when encryption is available", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
}),
).toBe(true);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
expect(JSON.parse(fs.readFileSync(registryPath, "utf8"))).toEqual({
records: [
{
...savedRegistryRecord,
encryptedBearerToken: Buffer.from("enc:bearer-token", "utf8").toString("base64"),
},
],
});
});
it("preserves existing secrets when encryption is unavailable", () => {
const registryPath = makeTempPath("saved-environments.json");
const availableSecretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: availableSecretStorage,
});
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "next-token",
secretStorage: makeSecretStorage(false),
}),
).toBe(false);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: availableSecretStorage,
}),
).toBe("bearer-token");
});
it("removes saved environment secrets", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
});
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBeNull();
});
it("treats malformed secrets documents as empty", () => {
const registryPath = makeTempPath("saved-environments.json");
fs.writeFileSync(registryPath, "{}\n", "utf8");
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage: makeSecretStorage(true),
}),
).toBeNull();
expect(() =>
removeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
}),
).not.toThrow();
});
it("returns false when writing a secret without metadata", () => {
const registryPath = makeTempPath("saved-environments.json");
expect(
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage: makeSecretStorage(true),
}),
).toBe(false);
});
it("preserves encrypted secrets when metadata is rewritten", () => {
const registryPath = makeTempPath("saved-environments.json");
const secretStorage = makeSecretStorage(true);
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
writeSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secret: "bearer-token",
secretStorage,
});
writeSavedEnvironmentRegistry(registryPath, [savedRegistryRecord]);
expect(readSavedEnvironmentRegistry(registryPath)).toEqual([savedRegistryRecord]);
expect(
readSavedEnvironmentSecret({
registryPath,
environmentId: savedRegistryRecord.environmentId,
secretStorage,
}),
).toBe("bearer-token");
});
});
+216
View File
@@ -0,0 +1,216 @@
import * as FS from "node:fs";
import * as Path from "node:path";
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { Predicate } from "effect";
interface ClientSettingsDocument {
readonly settings: ClientSettings;
}
interface PersistedSavedEnvironmentStorageRecord extends PersistedSavedEnvironmentRecord {
readonly encryptedBearerToken?: string;
}
interface SavedEnvironmentRegistryDocument {
readonly records: readonly PersistedSavedEnvironmentStorageRecord[];
}
export interface DesktopSecretStorage {
readonly isEncryptionAvailable: () => boolean;
readonly encryptString: (value: string) => Buffer;
readonly decryptString: (value: Buffer) => string;
}
function readJsonFile<T>(filePath: string): T | null {
try {
if (!FS.existsSync(filePath)) {
return null;
}
return JSON.parse(FS.readFileSync(filePath, "utf8")) as T;
} catch {
return null;
}
}
function writeJsonFile(filePath: string, value: unknown): void {
const directory = Path.dirname(filePath);
const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
FS.mkdirSync(directory, { recursive: true });
FS.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, "utf8");
FS.renameSync(tempPath, filePath);
}
function isPersistedSavedEnvironmentStorageRecord(
value: unknown,
): value is PersistedSavedEnvironmentStorageRecord {
return (
Predicate.isObject(value) &&
typeof value.environmentId === "string" &&
typeof value.label === "string" &&
typeof value.httpBaseUrl === "string" &&
typeof value.wsBaseUrl === "string" &&
typeof value.createdAt === "string" &&
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
);
}
function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmentRegistryDocument {
const parsed = readJsonFile<SavedEnvironmentRegistryDocument>(filePath);
if (!Predicate.isObject(parsed)) {
return { records: [] };
}
return {
records: Array.isArray(parsed.records)
? parsed.records.filter(isPersistedSavedEnvironmentStorageRecord)
: [],
};
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentStorageRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readClientSettings(settingsPath: string): ClientSettings | null {
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
}
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
writeJsonFile(settingsPath, { settings } satisfies ClientSettingsDocument);
}
export function readSavedEnvironmentRegistry(
registryPath: string,
): readonly PersistedSavedEnvironmentRecord[] {
return readSavedEnvironmentRegistryDocument(registryPath).records.map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeSavedEnvironmentRegistry(
registryPath: string,
records: readonly PersistedSavedEnvironmentRecord[],
): void {
const currentDocument = readSavedEnvironmentRegistryDocument(registryPath);
const encryptedBearerTokenById = new Map(
currentDocument.records.flatMap((record) =>
record.encryptedBearerToken
? [[record.environmentId, record.encryptedBearerToken] as const]
: [],
),
);
writeJsonFile(registryPath, {
records: records.map((record) => {
const encryptedBearerToken = encryptedBearerTokenById.get(record.environmentId);
return encryptedBearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
}
: record;
}),
} satisfies SavedEnvironmentRegistryDocument);
}
export function readSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secretStorage: DesktopSecretStorage;
}): string | null {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
const encoded = document.records.find(
(record) => record.environmentId === input.environmentId,
)?.encryptedBearerToken;
if (!encoded) {
return null;
}
if (!input.secretStorage.isEncryptionAvailable()) {
return null;
}
try {
return input.secretStorage.decryptString(Buffer.from(encoded, "base64"));
} catch {
return null;
}
}
export function writeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
readonly secret: string;
readonly secretStorage: DesktopSecretStorage;
}): boolean {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (!input.secretStorage.isEncryptionAvailable()) {
return false;
}
let found = false;
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
found = true;
const encryptedBearerToken = input.secretStorage
.encryptString(input.secret)
.toString("base64");
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
encryptedBearerToken,
} satisfies PersistedSavedEnvironmentStorageRecord;
}),
} satisfies SavedEnvironmentRegistryDocument);
return found;
}
export function removeSavedEnvironmentSecret(input: {
readonly registryPath: string;
readonly environmentId: string;
}): void {
const document = readSavedEnvironmentRegistryDocument(input.registryPath);
if (
!document.records.some(
(record) =>
record.environmentId === input.environmentId && record.encryptedBearerToken !== undefined,
)
) {
return;
}
writeJsonFile(input.registryPath, {
records: document.records.map((record) => {
if (record.environmentId !== input.environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
} satisfies SavedEnvironmentRegistryDocument);
}
+132 -19
View File
@@ -14,14 +14,16 @@ import {
nativeImage,
nativeTheme,
protocol,
safeStorage,
shell,
} from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
ClientSettings,
DesktopTheme,
DesktopServerExposureMode,
DesktopServerExposureState,
PersistedSavedEnvironmentRecord,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
@@ -29,15 +31,24 @@ import type {
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
import {
DEFAULT_DESKTOP_SETTINGS,
readDesktopSettings,
setDesktopServerExposurePreference,
writeDesktopSettings,
} from "./desktopSettings";
import {
readClientSettings,
readSavedEnvironmentRegistry,
readSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
writeClientSettings,
writeSavedEnvironmentRegistry,
writeSavedEnvironmentSecret,
} from "./clientPersistence";
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { resolveDesktopServerExposure } from "./serverExposure";
@@ -71,11 +82,20 @@ const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const DESKTOP_SETTINGS_PATH = Path.join(STATE_DIR, "desktop-settings.json");
const CLIENT_SETTINGS_PATH = Path.join(STATE_DIR, "client-settings.json");
const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments.json");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -204,6 +224,14 @@ function getDesktopServerExposureState(): DesktopServerExposureState {
};
}
function getDesktopSecretStorage() {
return {
isEncryptionAvailable: () => safeStorage.isEncryptionAvailable(),
encryptString: (value: string) => safeStorage.encryptString(value),
decryptString: (value: Buffer) => safeStorage.decryptString(value),
} as const;
}
function resolveAdvertisedHostOverride(): string | undefined {
const override = process.env.T3CODE_DESKTOP_LAN_HOST?.trim();
return override && override.length > 0 ? override : undefined;
@@ -700,12 +728,15 @@ function dispatchMenuAction(action: string): void {
}
function handleCheckForUpdatesMenuClick(): void {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
const disabledReason = getAutoUpdateDisabledReason({
isDevelopment,
isPackaged: app.isPackaged,
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
hasUpdateFeedConfig,
});
if (disabledReason) {
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
@@ -942,6 +973,8 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
}
function shouldEnableAutoUpdates(): boolean {
const hasUpdateFeedConfig =
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
return (
getAutoUpdateDisabledReason({
isDevelopment,
@@ -949,6 +982,7 @@ function shouldEnableAutoUpdates(): boolean {
platform: process.platform,
appImage: process.env.APPIMAGE,
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
hasUpdateFeedConfig,
}) === null
);
}
@@ -1032,17 +1066,6 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
}
function configureAutoUpdater(): void {
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
if (githubToken) {
@@ -1067,6 +1090,17 @@ function configureAutoUpdater(): void {
});
}
const enabled = shouldEnableAutoUpdates();
setUpdateState({
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
enabled,
status: enabled ? "idle" : "disabled",
});
if (!enabled) {
return;
}
updaterConfigured = true;
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
@@ -1343,6 +1377,86 @@ function registerIpcHandlers(): void {
} as const;
});
ipcMain.removeHandler(GET_CLIENT_SETTINGS_CHANNEL);
ipcMain.handle(GET_CLIENT_SETTINGS_CHANNEL, async () => readClientSettings(CLIENT_SETTINGS_PATH));
ipcMain.removeHandler(SET_CLIENT_SETTINGS_CHANNEL);
ipcMain.handle(SET_CLIENT_SETTINGS_CHANNEL, async (_event, rawSettings: unknown) => {
if (typeof rawSettings !== "object" || rawSettings === null) {
throw new Error("Invalid client settings payload.");
}
writeClientSettings(CLIENT_SETTINGS_PATH, rawSettings as ClientSettings);
});
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
ipcMain.handle(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async () =>
readSavedEnvironmentRegistry(SAVED_ENVIRONMENT_REGISTRY_PATH),
);
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL);
ipcMain.handle(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, async (_event, rawRecords: unknown) => {
if (!Array.isArray(rawRecords)) {
throw new Error("Invalid saved environment registry payload.");
}
writeSavedEnvironmentRegistry(
SAVED_ENVIRONMENT_REGISTRY_PATH,
rawRecords as readonly PersistedSavedEnvironmentRecord[],
);
});
ipcMain.removeHandler(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
GET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
return null;
}
return readSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
secretStorage: getDesktopSecretStorage(),
});
},
);
ipcMain.removeHandler(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
SET_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown, rawSecret: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
throw new Error("Invalid saved environment id.");
}
if (typeof rawSecret !== "string" || rawSecret.trim().length === 0) {
throw new Error("Invalid saved environment secret.");
}
return writeSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
secret: rawSecret,
secretStorage: getDesktopSecretStorage(),
});
},
);
ipcMain.removeHandler(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL);
ipcMain.handle(
REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL,
async (_event, rawEnvironmentId: unknown) => {
if (typeof rawEnvironmentId !== "string" || rawEnvironmentId.trim().length === 0) {
return;
}
removeSavedEnvironmentSecret({
registryPath: SAVED_ENVIRONMENT_REGISTRY_PATH,
environmentId: rawEnvironmentId,
});
},
);
ipcMain.removeHandler(GET_SERVER_EXPOSURE_STATE_CHANNEL);
ipcMain.handle(GET_SERVER_EXPOSURE_STATE_CHANNEL, async () => getDesktopServerExposureState());
@@ -1656,14 +1770,13 @@ async function bootstrap(): Promise<void> {
backendPort =
configuredBackendPort ??
(await Effect.service(NetService).pipe(
Effect.flatMap((net) => net.reserveLoopbackPort(DESKTOP_LOOPBACK_HOST)),
Effect.provide(NetService.layer),
Effect.runPromise,
));
(await resolveDesktopBackendPort({
host: DESKTOP_LOOPBACK_HOST,
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
}));
writeDesktopLogHeader(
configuredBackendPort === undefined
? `reserved backend port via NetService port=${backendPort}`
? `selected backend port via sequential scan startPort=${DEFAULT_DESKTOP_BACKEND_PORT} port=${backendPort}`
: `using configured backend port port=${backendPort}`,
);
backendBootstrapToken = Crypto.randomBytes(24).toString("hex");
+18
View File
@@ -13,6 +13,13 @@ const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
const GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:get-saved-environment-registry";
const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-registry";
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
@@ -24,6 +31,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getLocalEnvironmentBootstrap"]>;
},
getClientSettings: () => ipcRenderer.invoke(GET_CLIENT_SETTINGS_CHANNEL),
setClientSettings: (settings) => ipcRenderer.invoke(SET_CLIENT_SETTINGS_CHANNEL, settings),
getSavedEnvironmentRegistry: () => ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL),
setSavedEnvironmentRegistry: (records) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL, records),
getSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(GET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
setSavedEnvironmentSecret: (environmentId, secret) =>
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
removeSavedEnvironmentSecret: (environmentId) =>
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
+29
View File
@@ -71,10 +71,37 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("packaged production builds");
});
it("reports packaged local builds without an update feed as disabled", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: false,
}),
).toContain("no update feed");
});
it("allows packaged builds with an update feed", () => {
expect(
getAutoUpdateDisabledReason({
isDevelopment: false,
isPackaged: true,
platform: "darwin",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toBeNull();
});
it("reports env-disabled auto updates", () => {
expect(
getAutoUpdateDisabledReason({
@@ -83,6 +110,7 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "darwin",
appImage: undefined,
disabledByEnv: true,
hasUpdateFeedConfig: true,
}),
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
});
@@ -95,6 +123,7 @@ describe("getAutoUpdateDisabledReason", () => {
platform: "linux",
appImage: undefined,
disabledByEnv: false,
hasUpdateFeedConfig: true,
}),
).toContain("AppImage");
});
+4
View File
@@ -34,7 +34,11 @@ export function getAutoUpdateDisabledReason(args: {
platform: NodeJS.Platform;
appImage?: string | undefined;
disabledByEnv: boolean;
hasUpdateFeedConfig: boolean;
}): string | null {
if (!args.hasUpdateFeedConfig) {
return "Automatic updates are not available because no update feed is configured.";
}
if (args.isDevelopment || !args.isPackaged) {
return "Automatic updates are only available in packaged production builds.";
}
@@ -4,23 +4,7 @@ import { Effect, Layer } from "effect";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
import { SESSION_COOKIE_NAME } from "../utils.ts";
const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
const isLoopbackHost = (host: string | undefined): boolean => {
if (!host || host.length === 0) {
return true;
}
return (
host === "localhost" ||
host === "127.0.0.1" ||
host === "::1" ||
host === "[::1]" ||
host.startsWith("127.")
);
};
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
export const makeServerAuthPolicy = Effect.gen(function* () {
const config = yield* ServerConfig;
@@ -46,6 +46,9 @@ const WebSocketClaims = Schema.Struct({
});
type WebSocketClaims = typeof WebSocketClaims.Type;
const decodeSessionClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(SessionClaims));
const decodeWebSocketClaims = Schema.decodeUnknownEffect(Schema.fromJsonString(WebSocketClaims));
function createDefaultClientMetadata(): AuthClientMetadata {
return {
deviceType: "unknown",
@@ -259,15 +262,15 @@ export const makeSessionCredentialService = Effect.gen(function* () {
});
}
const claims = yield* Effect.try({
try: () =>
Schema.decodeUnknownSync(SessionClaims)(JSON.parse(base64UrlDecodeUtf8(encodedPayload))),
catch: (cause) =>
new SessionCredentialError({
message: "Invalid session token payload.",
cause,
}),
});
const claims = yield* decodeSessionClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialError({
message: "Invalid session token payload.",
cause,
}),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
@@ -348,17 +351,15 @@ export const makeSessionCredentialService = Effect.gen(function* () {
});
}
const claims = yield* Effect.try({
try: () =>
Schema.decodeUnknownSync(WebSocketClaims)(
JSON.parse(base64UrlDecodeUtf8(encodedPayload)),
),
catch: (cause) =>
new SessionCredentialError({
message: "Invalid websocket token payload.",
cause,
}),
});
const claims = yield* decodeWebSocketClaims(base64UrlDecodeUtf8(encodedPayload)).pipe(
Effect.mapError(
(cause) =>
new SessionCredentialError({
message: "Invalid websocket token payload.",
cause,
}),
),
);
const now = yield* Clock.currentTimeMillis;
if (claims.exp <= now) {
+64
View File
@@ -83,6 +83,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
@@ -144,6 +145,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
@@ -212,6 +214,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
@@ -329,6 +332,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
@@ -392,6 +396,66 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(3773),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
{
startupPresentation: "headless",
},
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_NO_BROWSER: "false",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
mode: "web",
port: 3773,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: undefined,
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
startupPresentation: "headless",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
+219
View File
@@ -1,17 +1,38 @@
import * as NodeHttp from "node:http";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as HttpRouter from "effect/unstable/http/HttpRouter";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as CliError from "effect/unstable/cli/CliError";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/unstable/cli";
import { cli } from "./cli.ts";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
orchestrationDispatchRouteLayer,
orchestrationSnapshotRouteLayer,
} from "./orchestration/http.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import {
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState.ts";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -28,6 +49,104 @@ const captureStdout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
return { result, output };
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer)));
const makeCliTestServerConfig = (baseDir: string) =>
Effect.gen(function* () {
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
return {
logLevel: "Info",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
mode: "web",
port: 0,
host: "127.0.0.1",
cwd: process.cwd(),
baseDir,
...derivedPaths,
staticDir: undefined,
devUrl: undefined,
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
} satisfies ServerConfigShape;
});
const makeProjectPersistenceLayer = (config: ServerConfigShape) =>
Layer.mergeAll(
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
WorkspacePathsLive,
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provide(Layer.succeed(ServerConfig, config)),
);
const readPersistedSnapshot = (baseDir: string) =>
Effect.gen(function* () {
const config = yield* makeCliTestServerConfig(baseDir);
return yield* Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
}).pipe(Effect.provide(makeProjectPersistenceLayer(config)));
});
const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Effect<A, E, R>) =>
Effect.gen(function* () {
const config = yield* makeCliTestServerConfig(baseDir);
const routesLayer = Layer.mergeAll(
orchestrationSnapshotRouteLayer,
orchestrationDispatchRouteLayer,
);
const appLayer = HttpRouter.serve(routesLayer, {
disableListenLog: true,
disableLogger: true,
}).pipe(
Layer.provideMerge(
ServerAuthLive.pipe(
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provide(ServerSecretStoreLive),
),
),
Layer.provideMerge(makeProjectPersistenceLayer(config)),
Layer.provideMerge(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 0,
}),
),
Layer.provideMerge(NodeServices.layer),
Layer.provide(Layer.succeed(ServerConfig, config)),
);
return yield* Effect.scoped(
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
assert.fail(`Expected TCP address, got ${address}`);
}
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state: makePersistedServerRuntimeState({
config,
port: address.port,
}),
});
return yield* run();
}).pipe(Effect.provide(Layer.mergeAll(appLayer, NodeServices.layer))),
);
});
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
runCliWithRuntime(["--log-level", "debug", "--version"]),
@@ -130,4 +249,104 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
assert.isTrue(ttlError.message.includes("5m, 1h, 30d, or 15 minutes"));
}),
);
it.effect("adds, renames, and removes projects offline through the orchestration engine", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-offline-test-"));
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-workspace-"));
yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--title",
"Alpha",
"--base-dir",
baseDir,
]);
const afterAdd = yield* readPersistedSnapshot(baseDir);
const addedProject = afterAdd.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.equal(addedProject?.title, "Alpha");
yield* runCliWithRuntime(["project", "rename", workspaceRoot, "Beta", "--base-dir", baseDir]);
const afterRename = yield* readPersistedSnapshot(baseDir);
const renamedProject = afterRename.projects.find(
(project) => project.id === addedProject?.id,
);
assert.equal(renamedProject?.title, "Beta");
assert.equal(renamedProject?.deletedAt, null);
yield* runCliWithRuntime([
"project",
"remove",
addedProject?.id ?? "",
"--base-dir",
baseDir,
]);
const afterRemove = yield* readPersistedSnapshot(baseDir);
const removedProject = afterRemove.projects.find(
(project) => project.id === addedProject?.id,
);
assert.isTrue((removedProject?.deletedAt ?? null) !== null);
}),
);
it.effect("routes project commands through a running server when runtime state is present", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-test-"));
const workspaceRoot = mkdtempSync(join(tmpdir(), "t3-cli-projects-live-workspace-"));
yield* withLiveProjectCliServer(baseDir, () =>
Effect.gen(function* () {
yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--title",
"Live Project",
"--base-dir",
baseDir,
]);
const orchestrationEngine = yield* OrchestrationEngineService;
const readModel = yield* orchestrationEngine.getReadModel();
const addedProject = readModel.projects.find(
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
);
assert.isTrue(addedProject !== undefined);
assert.equal(addedProject?.title, "Live Project");
}),
);
}),
);
it.effect("rejects dev-url on project commands", () =>
Effect.gen(function* () {
const workspaceRoot = mkdtempSync(
join(tmpdir(), "t3-cli-projects-unknown-option-workspace-"),
);
const error = yield* runCliWithRuntime([
"project",
"add",
workspaceRoot,
"--dev-url",
"http://127.0.0.1:5173",
]).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "project", "add"]);
const optionError = error.errors[0] as CliError.CliError | undefined;
if (!optionError || optionError._tag !== "UnrecognizedOption") {
assert.fail(`Expected UnrecognizedOption, got ${String(optionError?._tag)}`);
}
assert.equal(optionError.option, "--dev-url");
}),
);
});
+523 -58
View File
@@ -1,12 +1,20 @@
import { NetService } from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { AuthSessionId } from "@t3tools/contracts";
import {
AuthSessionId,
CommandId,
OrchestrationReadModel,
ProjectId,
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import {
Config,
Console,
Duration,
Effect,
Exit,
FileSystem,
Layer,
LogLevel,
Option,
Path,
@@ -16,6 +24,12 @@ import {
SchemaTransformation,
} from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
FetchHttpClient,
HttpClient,
HttpClientRequest,
HttpClientResponse,
} from "effect/unstable/http";
import {
DEFAULT_PORT,
@@ -25,6 +39,7 @@ import {
ServerConfig,
RuntimeMode,
type ServerConfigShape,
type StartupPresentation,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, resolveBaseDir } from "./os-jank";
@@ -37,6 +52,18 @@ import {
formatSessionList,
} from "./cliAuthFormat";
import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
import {
clearPersistedServerRuntimeState,
readPersistedServerRuntimeState,
} from "./serverRuntimeState";
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
@@ -163,7 +190,7 @@ interface CliServerFlags {
interface CliAuthLocationFlags {
readonly baseDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly devUrl?: Option.Option<URL>;
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
@@ -187,13 +214,29 @@ const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: st
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
options?: {
readonly startupPresentation?: StartupPresentation;
readonly forceAutoBootstrapProjectFromCwd?: boolean;
},
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const env = yield* EnvServerConfig;
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
const normalizedFlags = {
mode: flags.mode ?? Option.none(),
port: flags.port ?? Option.none(),
host: flags.host ?? Option.none(),
baseDir: flags.baseDir ?? Option.none(),
cwd: flags.cwd ?? Option.none(),
devUrl: flags.devUrl ?? Option.none(),
noBrowser: flags.noBrowser ?? Option.none(),
bootstrapFd: flags.bootstrapFd ?? Option.none(),
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
@@ -201,7 +244,7 @@ export const resolveServerConfig = (
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
flags.mode,
normalizedFlags.mode,
Option.fromUndefinedOr(env.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
),
@@ -210,7 +253,7 @@ export const resolveServerConfig = (
const port = yield* Option.match(
resolveOptionPrecedence(
flags.port,
normalizedFlags.port,
Option.fromUndefinedOr(env.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
),
@@ -226,7 +269,7 @@ export const resolveServerConfig = (
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(
flags.devUrl,
normalizedFlags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
),
@@ -235,7 +278,7 @@ export const resolveServerConfig = (
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
flags.baseDir,
normalizedFlags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
@@ -243,7 +286,7 @@ export const resolveServerConfig = (
),
),
);
const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
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* deriveServerPaths(baseDir, devUrl);
@@ -253,37 +296,45 @@ export const resolveServerConfig = (
);
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const noBrowser = resolveBooleanFlag(
flags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const startupPresentation = options?.startupPresentation ?? "browser";
const noBrowser =
startupPresentation === "headless"
? true
: resolveBooleanFlag(
normalizedFlags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const desktopBootstrapToken = Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
),
);
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
flags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
);
const autoBootstrapProjectFromCwd =
options?.forceAutoBootstrapProjectFromCwd ??
(startupPresentation === "headless"
? false
: resolveBooleanFlag(
normalizedFlags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
));
const logWebSocketEvents = resolveBooleanFlag(
flags.logWebSocketEvents,
normalizedFlags.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
@@ -297,7 +348,7 @@ export const resolveServerConfig = (
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
flags.host,
normalizedFlags.host,
Option.fromUndefinedOr(env.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
),
@@ -340,6 +391,7 @@ export const resolveServerConfig = (
staticDir,
devUrl,
noBrowser,
startupPresentation,
desktopBootstrapToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
@@ -359,7 +411,7 @@ const resolveCliAuthConfig = (
host: Option.none(),
baseDir: flags.baseDir,
cwd: Option.none(),
devUrl: flags.devUrl,
devUrl: flags.devUrl ?? Option.none(),
noBrowser: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
@@ -446,13 +498,289 @@ const runWithAuthControlPlane = <A, E>(
const authControlPlane = yield* AuthControlPlane;
return yield* run(authControlPlane);
}).pipe(
Effect.provide(AuthControlPlaneRuntimeLive),
Effect.provideService(ServerConfig, config),
Effect.provideService(References.MinimumLogLevel, minimumLogLevel),
Effect.provide(
Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
);
});
const commandFlags = {
type ProjectMutationTarget = {
readonly id: ProjectId;
readonly title: string;
readonly workspaceRoot: string;
};
type ProjectCommandExecutionMode = "live" | "offline";
type ProjectCliDispatchCommand = Extract<
ClientOrchestrationCommand,
{ type: "project.create" | "project.meta.update" | "project.delete" }
>;
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(SqlitePersistenceLayerLive),
),
);
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
const OrchestrationHttpErrorResponse = Schema.Struct({
error: Schema.String,
});
const withProjectCliSessionToken = <A, E, R>(
authControlPlane: AuthControlPlaneShape,
run: (token: string) => Effect.Effect<A, E, R>,
) =>
Effect.acquireUseRelease(
authControlPlane.issueSession({
role: "owner",
label: "t3 project cli",
}),
(issued) => run(issued.token),
(issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
);
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
const runLiveServerRequest = <A, E extends Error, R>(
request: HttpClientRequest.HttpClientRequest,
handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
) =>
Effect.gen(function* () {
const httpClient = yield* HttpClient.HttpClient;
const response = yield* httpClient.execute(request);
return yield* handle(response);
}).pipe(withProjectCliLiveServerTimeout);
const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
Effect.map((body) => body.error),
Effect.catch(() => Effect.succeed(null)),
Effect.map((body) => {
if (typeof body === "string" && body.trim().length > 0) {
return body;
}
return `Server request failed with status ${response.status}.`;
}),
);
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
"normalizeWorkspaceRootForProjectCommand",
)(function* (workspaceRoot: string) {
const workspacePaths = yield* WorkspacePaths;
return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
});
const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
workspaceRoot: string,
explicitTitle?: string,
) {
if (explicitTitle !== undefined) {
const trimmed = explicitTitle.trim();
if (trimmed.length > 0) {
return trimmed;
}
return yield* Effect.fail(new Error("Project title cannot be empty."));
}
const path = yield* Path.Path;
const basename = path.basename(workspaceRoot).trim();
return basename.length > 0 ? basename : "project";
});
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
readonly snapshot: OrchestrationReadModel;
readonly identifier: string;
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
}
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
if (exactIdMatch) {
return {
id: exactIdMatch.id,
title: exactIdMatch.title,
workspaceRoot: exactIdMatch.workspaceRoot,
} satisfies ProjectMutationTarget;
}
const normalizedWorkspaceRootResult = yield* Effect.exit(
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
);
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
? normalizedWorkspaceRootResult.value
: null;
const exactWorkspaceMatch =
normalizedWorkspaceRoot === null
? undefined
: activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
}
return {
id: resolved.id,
title: resolved.title,
workspaceRoot: resolved.workspaceRoot,
} satisfies ProjectMutationTarget;
});
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
runLiveServerRequest(
HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bearerToken(bearerToken),
),
HttpClientResponse.matchStatus({
"2xx": decodeOrchestrationReadModelResponse,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
),
}),
);
const dispatchLiveOrchestrationCommand = (
origin: string,
bearerToken: string,
command: ProjectCliDispatchCommand,
) =>
HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
HttpClientRequest.acceptJson,
HttpClientRequest.bearerToken(bearerToken),
HttpClientRequest.bodyJson(command),
Effect.flatMap((request) =>
runLiveServerRequest(
request,
HttpClientResponse.matchStatus({
"2xx": () => Effect.void,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
),
}),
),
),
);
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
return yield* projectionSnapshotQuery.getSnapshot();
});
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
if (Option.isNone(runtimeState)) {
return Option.none<{ readonly origin: string }>();
}
const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
Effect.as({
origin: runtimeState.value.origin,
}),
),
);
const attempted = yield* Effect.exit(attempt);
if (Exit.isSuccess(attempted)) {
return Option.some(attempted.value);
}
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
return Option.none<{ readonly origin: string }>();
},
);
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
flags: CliAuthLocationFlags,
run: (input: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
readonly mode: ProjectCommandExecutionMode;
}) => Effect.Effect<
string,
Error,
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
>,
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
const minimumLogLevel = config.logLevel;
return yield* Effect.gen(function* () {
const authControlPlane = yield* AuthControlPlane;
const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
if (Option.isSome(liveMode)) {
return yield* withProjectCliSessionToken(authControlPlane, (token) =>
Effect.gen(function* () {
const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
const output = yield* run({
snapshot,
dispatch: (command) =>
dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
mode: "live",
});
yield* Console.log(output);
}),
);
}
const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
);
return yield* Effect.gen(function* () {
const snapshot = yield* getOfflineSnapshot();
const orchestrationEngine = yield* OrchestrationEngineService;
const output = yield* run({
snapshot,
dispatch: (command) => orchestrationEngine.dispatch(command),
mode: "offline",
});
yield* Console.log(output);
}).pipe(Effect.provide(offlineRuntimeLayer));
}).pipe(
Effect.provide(
Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(Layer.succeed(ServerConfig, config)),
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
),
),
);
});
const sharedServerLocationFlags = {
baseDir: baseDirFlag,
devUrl: devUrlFlag,
} as const;
const projectLocationFlags = {
baseDir: baseDirFlag,
} as const;
const sharedServerCommandFlags = {
mode: modeFlag,
port: portFlag,
host: hostFlag,
@@ -470,10 +798,7 @@ const commandFlags = {
logWebSocketEvents: logWebSocketEventsFlag,
} as const;
const authLocationFlags = {
baseDir: baseDirFlag,
devUrl: devUrlFlag,
} as const;
const authLocationFlags = sharedServerLocationFlags;
const ttlFlag = Flag.string("ttl").pipe(
Flag.withSchema(DurationFromString),
@@ -674,25 +999,165 @@ const authCommand = Command.make("auth").pipe(
Command.withSubcommands([pairingCommand, sessionCommand]),
);
const startCommand = Command.make("start", commandFlags).pipe(
Command.withDescription("Run the T3 Code server."),
const projectAddCommand = Command.make("add", {
...projectLocationFlags,
workspaceRoot: Argument.string("path").pipe(
Argument.withDescription("Workspace root to add as a project."),
),
title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
}).pipe(
Command.withDescription("Add a project."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
runProjectMutation(
flags,
Effect.fn("projectAddMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
const existingProject = snapshot.projects.find(
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* Effect.fail(
new Error(`An active project already exists for '${workspaceRoot}'.`),
);
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
yield* dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId,
title,
workspaceRoot,
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
createdAt: new Date().toISOString(),
});
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
}),
),
),
);
const projectRemoveCommand = Command.make("remove", {
...projectLocationFlags,
project: Argument.string("project").pipe(
Argument.withDescription("Project id or workspace root to remove."),
),
}).pipe(
Command.withDescription("Remove a project."),
Command.withHandler((flags) =>
runProjectMutation(
flags,
Effect.fn("projectRemoveMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const project = yield* findActiveProjectTarget({
snapshot,
identifier: flags.project,
});
yield* dispatch({
type: "project.delete",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: project.id,
});
return `Removed project ${project.id} (${project.title}).`;
}),
),
),
);
const projectRenameCommand = Command.make("rename", {
...projectLocationFlags,
project: Argument.string("project").pipe(
Argument.withDescription("Project id or workspace root to rename."),
),
title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
}).pipe(
Command.withDescription("Rename a project."),
Command.withHandler((flags) =>
runProjectMutation(
flags,
Effect.fn("projectRenameMutation")(function* ({
snapshot,
dispatch,
}: {
readonly snapshot: OrchestrationReadModel;
readonly dispatch: (
command: ProjectCliDispatchCommand,
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
}) {
const project = yield* findActiveProjectTarget({
snapshot,
identifier: flags.project,
});
const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
if (nextTitle === project.title) {
return `Project ${project.id} is already named ${nextTitle}.`;
}
yield* dispatch({
type: "project.meta.update",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: project.id,
title: nextTitle,
});
return `Renamed project ${project.id} to ${nextTitle}.`;
}),
),
),
);
const projectCommand = Command.make("project").pipe(
Command.withDescription("Manage projects."),
Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
);
const runServerCommand = (
flags: CliServerFlags,
options?: {
readonly startupPresentation?: StartupPresentation;
readonly forceAutoBootstrapProjectFromCwd?: boolean;
},
) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel, options);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
});
const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) => runServerCommand(flags)),
);
const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
Command.withDescription(
"Run the T3 Code server without opening a browser and print headless pairing details.",
),
Command.withHandler((flags) =>
runServerCommand(flags, {
startupPresentation: "headless",
forceAutoBootstrapProjectFromCwd: false,
}),
),
);
export const cli = Command.make("t3", commandFlags).pipe(
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
}),
),
Command.withSubcommands([startCommand, authCommand]),
Command.withHandler((flags) => runServerCommand(flags)),
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
);
+8
View File
@@ -13,6 +13,9 @@ export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export const StartupPresentation = Schema.Literals(["browser", "headless"]);
export type StartupPresentation = typeof StartupPresentation.Type;
/**
* ServerDerivedPaths - Derived paths from the base directory.
*/
@@ -31,6 +34,7 @@ export interface ServerDerivedPaths {
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
readonly environmentIdPath: string;
readonly serverRuntimeStatePath: string;
readonly secretsDir: string;
}
@@ -56,6 +60,7 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
readonly startupPresentation: StartupPresentation;
readonly desktopBootstrapToken: string | undefined;
readonly autoBootstrapProjectFromCwd: boolean;
readonly logWebSocketEvents: boolean;
@@ -86,6 +91,7 @@ export const deriveServerPaths = Effect.fn(function* (
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
environmentIdPath: join(stateDir, "environment-id"),
serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
secretsDir: join(stateDir, "secrets"),
};
});
@@ -105,6 +111,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
],
{ concurrency: "unbounded" },
);
@@ -153,6 +160,7 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
staticDir: undefined,
devUrl,
noBrowser: false,
startupPresentation: "browser",
} satisfies ServerConfigShape;
}),
);
@@ -36,6 +36,7 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
staticDir: undefined,
devUrl: undefined,
noBrowser: false,
startupPresentation: "browser",
} satisfies ServerConfigShape;
});
+1
View File
@@ -168,6 +168,7 @@ const makeGitHubCli = Effect.sync(() => {
runProcess("gh", input.args, {
cwd: input.cwd,
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
shell: false,
}),
catch: (error) => normalizeGitHubCliError("execute", error),
});
+93
View File
@@ -0,0 +1,93 @@
import {
ClientOrchestrationCommand,
OrchestrationDispatchCommandError,
OrchestrationGetSnapshotError,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { ServerAuth } from "../auth/Services/ServerAuth.ts";
import { normalizeDispatchCommand } from "./Normalizer.ts";
import { OrchestrationEngineService } from "./Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./Services/ProjectionSnapshotQuery.ts";
const respondToOrchestrationHttpError = (
error: OrchestrationDispatchCommandError | OrchestrationGetSnapshotError,
) =>
Effect.gen(function* () {
if (error._tag === "OrchestrationGetSnapshotError") {
yield* Effect.logError("orchestration http route failed", {
message: error.message,
cause: error.cause,
});
return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 500 });
}
return HttpServerResponse.jsonUnsafe({ error: error.message }, { status: 400 });
});
const authenticateOwnerSession = Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
const session = yield* serverAuth.authenticateHttpRequest(request);
if (session.role !== "owner") {
return yield* new OrchestrationDispatchCommandError({
message: "Only owner sessions can manage projects.",
});
}
return session;
});
export const orchestrationSnapshotRouteLayer = HttpRouter.add(
"GET",
"/api/orchestration/snapshot",
Effect.gen(function* () {
yield* authenticateOwnerSession;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.mapError(
(cause) =>
new OrchestrationGetSnapshotError({
message: "Failed to load orchestration snapshot.",
cause,
}),
),
);
return HttpServerResponse.jsonUnsafe(snapshot satisfies OrchestrationReadModel, {
status: 200,
});
}).pipe(
Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError),
Effect.catchTag("OrchestrationGetSnapshotError", respondToOrchestrationHttpError),
),
);
export const orchestrationDispatchRouteLayer = HttpRouter.add(
"POST",
"/api/orchestration/dispatch",
Effect.gen(function* () {
yield* authenticateOwnerSession;
const orchestrationEngine = yield* OrchestrationEngineService;
const command = yield* HttpServerRequest.schemaBodyJson(ClientOrchestrationCommand).pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: "Invalid orchestration command payload.",
cause,
}),
),
);
const normalizedCommand = yield* normalizeDispatchCommand(command);
const result = yield* orchestrationEngine.dispatch(normalizedCommand).pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: "Failed to dispatch orchestration command.",
cause,
}),
),
);
return HttpServerResponse.jsonUnsafe(result, { status: 200 });
}).pipe(Effect.catchTag("OrchestrationDispatchCommandError", respondToOrchestrationHttpError)),
);
@@ -0,0 +1,27 @@
import { Layer } from "effect";
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
OrchestrationCommandReceiptRepositoryLive,
);
export const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(
Layer.provide(OrchestrationEventStoreLive),
);
export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
export const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),
);
+43 -1
View File
@@ -1,4 +1,6 @@
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import { accessSync } from "node:fs";
import { delimiter, extname, join } from "node:path";
export interface ProcessRunOptions {
cwd?: string | undefined;
@@ -8,6 +10,7 @@ export interface ProcessRunOptions {
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
shell?: boolean | undefined;
}
export interface ProcessRunResult {
@@ -80,6 +83,45 @@ function normalizeBufferError(
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
/**
* On Windows, `.cmd` / `.bat` shims (created by npm, Scoop, etc.) can only be
* executed by `spawn` when `shell: true`. When the caller explicitly requests
* `shell: false` we still need to honour that for `.exe` binaries, but we must
* fall back to `shell: true` when the resolved command is a script shim.
*/
function resolveShellOption(command: string, explicit: boolean | undefined): boolean {
if (process.platform !== "win32") return explicit ?? false;
if (explicit === true) return true;
if (extname(command)) {
const ext = extname(command).toLowerCase();
return ext === ".cmd" || ext === ".bat";
}
const pathEnv = process.env["PATH"] ?? process.env["Path"] ?? "";
const dirs = pathEnv.split(delimiter).filter(Boolean);
for (const dir of dirs) {
for (const ext of [".cmd", ".bat"]) {
try {
accessSync(join(dir, `${command}${ext}`));
return true;
} catch {
// not found, continue
}
}
for (const ext of [".exe", ".com", ""]) {
try {
accessSync(join(dir, `${command}${ext}`));
return false;
} catch {
// not found, continue
}
}
}
return explicit ?? false;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
@@ -139,7 +181,7 @@ export async function runProcess(
cwd: options.cwd,
env: options.env,
stdio: "pipe",
shell: process.platform === "win32",
shell: resolveShellOption(command, options.shell),
});
let stdout = "";
+1
View File
@@ -331,6 +331,7 @@ const buildAppUnderTest = (options?: {
staticDir: undefined,
devUrl,
noBrowser: true,
startupPresentation: "browser",
desktopBootstrapToken: defaultDesktopBootstrapToken,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
+34 -25
View File
@@ -23,12 +23,7 @@ import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { OrchestrationEngineLive } from "./orchestration/Layers/OrchestrationEngine";
import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline";
import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore";
import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery";
import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
@@ -67,6 +62,16 @@ import {
} from "./auth/http";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore";
import { ServerAuthLive } from "./auth/Layers/ServerAuth";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
import {
clearPersistedServerRuntimeState,
makePersistedServerRuntimeState,
persistServerRuntimeState,
} from "./serverRuntimeState";
import {
orchestrationDispatchRouteLayer,
orchestrationSnapshotRouteLayer,
} from "./orchestration/http";
const PtyAdapterLive = Layer.unwrap(
Effect.gen(function* () {
@@ -124,26 +129,6 @@ const ReactorLayerLive = Layer.empty.pipe(
Layer.provideMerge(RuntimeReceiptBusLive),
);
const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
OrchestrationCommandReceiptRepositoryLive,
);
const OrchestrationProjectionPipelineLayerLive = OrchestrationProjectionPipelineLive.pipe(
Layer.provide(OrchestrationEventStoreLive),
);
const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
);
const OrchestrationLayerLive = Layer.mergeAll(
OrchestrationInfrastructureLayerLive,
OrchestrationEngineLive.pipe(Layer.provide(OrchestrationInfrastructureLayerLive)),
);
const CheckpointingLayerLive = Layer.empty.pipe(
Layer.provideMerge(CheckpointDiffQueryLive),
Layer.provideMerge(CheckpointStoreLive),
@@ -248,6 +233,8 @@ export const makeRoutesLayer = Layer.mergeAll(
authSessionRouteLayer,
authWebSocketTokenRouteLayer,
attachmentsRouteLayer,
orchestrationDispatchRouteLayer,
orchestrationSnapshotRouteLayer,
otlpTracesProxyRouteLayer,
projectFaviconRouteLayer,
serverEnvironmentRouteLayer,
@@ -268,12 +255,34 @@ export const makeServerLayer = Layer.unwrap(
yield* startup.markHttpListening;
}),
);
const runtimeStateLayer = Layer.effectDiscard(
Effect.acquireRelease(
Effect.gen(function* () {
const server = yield* HttpServer.HttpServer;
const address = server.address;
if (typeof address === "string" || !("port" in address)) {
return;
}
const state = makePersistedServerRuntimeState({
config,
port: address.port,
});
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state,
});
}),
() => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
),
);
const serverApplicationLayer = Layer.mergeAll(
HttpRouter.serve(makeRoutesLayer, {
disableLogger: !config.logWebSocketEvents,
}),
httpListeningLayer,
runtimeStateLayer,
);
return serverApplicationLayer.pipe(
+22 -12
View File
@@ -18,6 +18,7 @@ import {
Ref,
Scope,
ServiceMap,
Console,
} from "effect";
import { ServerConfig } from "./config";
@@ -31,12 +32,12 @@ import { ServerSettingsService } from "./serverSettings";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { ServerAuth } from "./auth/Services/ServerAuth";
const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
import {
formatHeadlessServeOutput,
formatHostForUrl,
isWildcardHost,
issueHeadlessServeAccessInfo,
} from "./startupAccess";
export class ServerRuntimeStartupError extends Data.TaggedError("ServerRuntimeStartupError")<{
readonly message: string;
@@ -383,14 +384,23 @@ const makeServerRuntimeStartup = Effect.gen(function* () {
yield* Effect.logDebug("startup phase: recording startup heartbeat");
yield* launchStartupHeartbeat;
yield* Effect.logDebug("startup phase: browser open check");
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
yield* Effect.logInfo("Authentication required. Open T3 Code using the pairing URL.").pipe(
Effect.annotateLogs({ pairingUrl: startupBrowserTarget }),
if (serverConfig.startupPresentation === "headless") {
yield* Effect.logDebug("startup phase: headless access info");
const accessInfo = yield* issueHeadlessServeAccessInfo();
yield* runStartupPhase(
"headless.output",
Console.log(formatHeadlessServeOutput(accessInfo)),
);
} else {
yield* Effect.logDebug("startup phase: browser open check");
const startupBrowserTarget = yield* resolveStartupBrowserTarget;
if (serverConfig.mode !== "desktop") {
yield* Effect.logInfo(
"Authentication required. Open T3 Code using the pairing URL.",
).pipe(Effect.annotateLogs({ pairingUrl: startupBrowserTarget }));
}
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
}
yield* runStartupPhase("browser.open", maybeOpenBrowser(startupBrowserTarget));
yield* Effect.logDebug("startup phase: complete");
}),
);
+77
View File
@@ -0,0 +1,77 @@
import { Effect, FileSystem, Option, Path, Schema } from "effect";
import { type ServerConfigShape } from "./config";
import { formatHostForUrl, isWildcardHost } from "./startupAccess";
export const PersistedServerRuntimeState = Schema.Struct({
version: Schema.Literal(1),
pid: Schema.Int,
host: Schema.optional(Schema.String),
port: Schema.Int,
origin: Schema.String,
startedAt: Schema.String,
});
export type PersistedServerRuntimeState = typeof PersistedServerRuntimeState.Type;
const decodePersistedServerRuntimeState = Schema.decodeUnknownEffect(
Schema.fromJsonString(PersistedServerRuntimeState),
);
const runtimeOriginForConfig = (
config: Pick<ServerConfigShape, "host">,
port: number,
): PersistedServerRuntimeState["origin"] => {
const hostname =
config.host && !isWildcardHost(config.host) ? formatHostForUrl(config.host) : "127.0.0.1";
return `http://${hostname}:${port}`;
};
export const makePersistedServerRuntimeState = (input: {
readonly config: Pick<ServerConfigShape, "host">;
readonly port: number;
}): PersistedServerRuntimeState => ({
version: 1,
pid: process.pid,
...(input.config.host ? { host: input.config.host } : {}),
port: input.port,
origin: runtimeOriginForConfig(input.config, input.port),
startedAt: new Date().toISOString(),
});
export const persistServerRuntimeState = (input: {
readonly path: string;
readonly state: PersistedServerRuntimeState;
}) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const tempPath = `${input.path}.${process.pid}.${Date.now()}.tmp`;
return yield* fs.makeDirectory(pathService.dirname(input.path), { recursive: true }).pipe(
Effect.flatMap(() => fs.writeFileString(tempPath, `${JSON.stringify(input.state)}\n`)),
Effect.flatMap(() => fs.rename(tempPath, input.path)),
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
);
});
export const clearPersistedServerRuntimeState = (path: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.remove(path, { force: true }).pipe(Effect.ignore({ log: true }));
});
export const readPersistedServerRuntimeState = (path: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(path).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return Option.none<PersistedServerRuntimeState>();
}
const raw = yield* fs.readFileString(path).pipe(Effect.orElseSucceed(() => ""));
const trimmed = raw.trim();
if (trimmed.length === 0) {
return Option.none<PersistedServerRuntimeState>();
}
return yield* decodePersistedServerRuntimeState(trimmed).pipe(Effect.option);
});
+79
View File
@@ -0,0 +1,79 @@
import { assert, expect, it } from "@effect/vitest";
import {
buildPairingUrl,
formatHeadlessServeOutput,
renderTerminalQrCode,
resolveHeadlessConnectionHost,
resolveHeadlessConnectionString,
resolveListeningPort,
} from "./startupAccess";
it("prefers localhost when no explicit host is configured", () => {
expect(resolveHeadlessConnectionHost(undefined)).toBe("localhost");
expect(resolveHeadlessConnectionString(undefined, 3773)).toBe("http://localhost:3773");
});
it("keeps explicit bind hosts in the connection string", () => {
expect(resolveHeadlessConnectionString("127.0.0.1", 3773)).toBe("http://127.0.0.1:3773");
expect(resolveHeadlessConnectionString("::1", 3773)).toBe("http://[::1]:3773");
});
it("resolves wildcard hosts to a concrete external interface when one is available", () => {
const connectionString = resolveHeadlessConnectionString("0.0.0.0", 3773, {
en0: [
{
address: "192.168.1.42",
netmask: "255.255.255.0",
family: "IPv4",
mac: "00:00:00:00:00:00",
internal: false,
cidr: "192.168.1.42/24",
},
],
lo0: [
{
address: "127.0.0.1",
netmask: "255.0.0.0",
family: "IPv4",
mac: "00:00:00:00:00:00",
internal: true,
cidr: "127.0.0.1/8",
},
],
});
expect(connectionString).toBe("http://192.168.1.42:3773");
});
it("prefers the actual bound port when an http server address is available", () => {
expect(resolveListeningPort({ port: 4123 }, 3773)).toBe(4123);
expect(resolveListeningPort("pipe", 3773)).toBe(3773);
expect(resolveListeningPort(null, 3773)).toBe(3773);
});
it("builds a pairing URL that embeds the token in the hash", () => {
expect(buildPairingUrl("http://192.168.1.42:3773", "PAIRCODE")).toBe(
"http://192.168.1.42:3773/pair#token=PAIRCODE",
);
});
it("renders terminal QR codes as a multi-line unicode block grid", () => {
const qrCode = renderTerminalQrCode("http://192.168.1.42:3773/pair#token=PAIRCODE");
assert.isTrue(qrCode.includes("█"));
assert.isTrue(qrCode.split("\n").length > 10);
});
it("formats headless serve output with the connection string, token, pairing url, and qr code", () => {
const output = formatHeadlessServeOutput({
connectionString: "http://192.168.1.42:3773",
token: "PAIRCODE",
pairingUrl: "http://192.168.1.42:3773/pair#token=PAIRCODE",
});
expect(output).toContain("Connection string: http://192.168.1.42:3773");
expect(output).toContain("Token: PAIRCODE");
expect(output).toContain("Pairing URL: http://192.168.1.42:3773/pair#token=PAIRCODE");
assert.isTrue(output.includes("█") || output.includes("▀") || output.includes("▄"));
});
+148
View File
@@ -0,0 +1,148 @@
import { networkInterfaces } from "node:os";
import { QrCode } from "@t3tools/shared/qrCode";
import { Effect } from "effect";
import { HttpServer } from "effect/unstable/http";
import { ServerConfig } from "./config";
import { ServerAuth } from "./auth/Services/ServerAuth";
export interface HeadlessServeAccessInfo {
readonly connectionString: string;
readonly token: string;
readonly pairingUrl: string;
}
type NetworkInterfacesMap = ReturnType<typeof networkInterfaces>;
export const isLoopbackHost = (host: string | undefined): boolean => {
if (!host || host.length === 0) {
return true;
}
return (
host === "localhost" ||
host === "127.0.0.1" ||
host === "::1" ||
host === "[::1]" ||
host.startsWith("127.")
);
};
export const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
export const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
const normalizeHost = (host: string): string =>
host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4;
const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6;
export const resolveHeadlessConnectionHost = (
host: string | undefined,
interfaces: NetworkInterfacesMap = networkInterfaces(),
): string => {
if (!host) {
return "localhost";
}
if (!isWildcardHost(host)) {
return normalizeHost(host);
}
const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);
const externalIpv4 = interfaceEntries.find(
(entry) => !entry.internal && isIpv4Family(entry.family),
);
if (externalIpv4) {
return externalIpv4.address;
}
const externalIpv6 = interfaceEntries.find(
(entry) => !entry.internal && isIpv6Family(entry.family),
);
return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost";
};
export const resolveHeadlessConnectionString = (
host: string | undefined,
port: number,
interfaces: NetworkInterfacesMap = networkInterfaces(),
): string => {
const connectionHost = resolveHeadlessConnectionHost(host, interfaces);
return `http://${formatHostForUrl(connectionHost)}:${port}`;
};
export const resolveListeningPort = (address: unknown, fallbackPort: number): number => {
if (
typeof address === "object" &&
address !== null &&
"port" in address &&
typeof address.port === "number"
) {
return address.port;
}
return fallbackPort;
};
export const buildPairingUrl = (connectionString: string, token: string): string => {
const url = new URL(connectionString);
url.pathname = "/pair";
url.searchParams.delete("token");
url.hash = new URLSearchParams([["token", token]]).toString();
return url.toString();
};
export const renderTerminalQrCode = (value: string, margin = 2): string => {
const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);
const rows: Array<string> = [];
const isDark = (x: number, y: number): boolean =>
x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);
for (let y = -margin; y < qrCode.size + margin; y += 2) {
let row = "";
for (let x = -margin; x < qrCode.size + margin; x += 1) {
const topDark = isDark(x, y);
const bottomDark = isDark(x, y + 1);
row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " ";
}
rows.push(row);
}
return rows.join("\n");
};
export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>
[
"T3 Code server is ready.",
`Connection string: ${accessInfo.connectionString}`,
`Token: ${accessInfo.token}`,
`Pairing URL: ${accessInfo.pairingUrl}`,
"",
renderTerminalQrCode(accessInfo.pairingUrl),
"",
].join("\n");
export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
const serverConfig = yield* ServerConfig;
const httpServer = yield* HttpServer.HttpServer;
const serverAuth = yield* ServerAuth;
const connectionString = resolveHeadlessConnectionString(
serverConfig.host,
resolveListeningPort(httpServer.address, serverConfig.port),
);
const issued = yield* serverAuth.issuePairingCredential({ role: "owner" });
return {
connectionString,
token: issued.credential,
pairingUrl: buildPairingUrl(connectionString, issued.credential),
} satisfies HeadlessServeAccessInfo;
});
@@ -0,0 +1,80 @@
import { EnvironmentId, type PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
const testEnvironmentId = EnvironmentId.makeUnsafe("environment-1");
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
environmentId: testEnvironmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
};
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function getTestWindow(): Window & typeof globalThis {
const localStorage = createLocalStorageStub();
const testWindow = {
localStorage,
} as Window & typeof globalThis;
vi.stubGlobal("window", testWindow);
vi.stubGlobal("localStorage", localStorage);
return testWindow;
}
afterEach(() => {
vi.resetModules();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
describe("clientPersistenceStorage", () => {
it("stores browser secrets inline with the saved environment record", async () => {
const testWindow = getTestWindow();
const {
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
readBrowserSavedEnvironmentRegistry,
readBrowserSavedEnvironmentSecret,
writeBrowserSavedEnvironmentRegistry,
writeBrowserSavedEnvironmentSecret,
} = await import("./clientPersistenceStorage");
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
expect(writeBrowserSavedEnvironmentSecret(testEnvironmentId, "bearer-token")).toBe(true);
writeBrowserSavedEnvironmentRegistry([savedRegistryRecord]);
expect(readBrowserSavedEnvironmentRegistry()).toEqual([savedRegistryRecord]);
expect(readBrowserSavedEnvironmentSecret(testEnvironmentId)).toBe("bearer-token");
expect(
JSON.parse(testWindow.localStorage.getItem(SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY)!),
).toEqual({
version: 1,
records: [
{
...savedRegistryRecord,
bearerToken: "bearer-token",
},
],
});
});
});
+194
View File
@@ -0,0 +1,194 @@
import {
ClientSettingsSchema,
EnvironmentId,
type ClientSettings,
type EnvironmentId as EnvironmentIdValue,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
export const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
const BrowserSavedEnvironmentRecordSchema = Schema.Struct({
environmentId: EnvironmentId,
label: Schema.String,
httpBaseUrl: Schema.String,
wsBaseUrl: Schema.String,
createdAt: Schema.String,
lastConnectedAt: Schema.NullOr(Schema.String),
bearerToken: Schema.optionalKey(Schema.String),
});
type BrowserSavedEnvironmentRecord = typeof BrowserSavedEnvironmentRecordSchema.Type;
const BrowserSavedEnvironmentRegistryDocumentSchema = Schema.Struct({
version: Schema.optionalKey(Schema.Number),
records: Schema.optionalKey(Schema.Array(BrowserSavedEnvironmentRecordSchema)),
});
type BrowserSavedEnvironmentRegistryDocument =
typeof BrowserSavedEnvironmentRegistryDocumentSchema.Type;
function hasWindow(): boolean {
return typeof window !== "undefined";
}
function toPersistedSavedEnvironmentRecord(
record: PersistedSavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export function readBrowserClientSettings(): ClientSettings | null {
if (!hasWindow()) {
return null;
}
try {
return getLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, ClientSettingsSchema);
} catch {
return null;
}
}
export function writeBrowserClientSettings(settings: ClientSettings): void {
if (!hasWindow()) {
return;
}
setLocalStorageItem(CLIENT_SETTINGS_STORAGE_KEY, settings, ClientSettingsSchema);
}
function readBrowserSavedEnvironmentRegistryDocument(): BrowserSavedEnvironmentRegistryDocument {
if (!hasWindow()) {
return {};
}
try {
const parsed = getLocalStorageItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
BrowserSavedEnvironmentRegistryDocumentSchema,
);
return parsed ?? {};
} catch {
return {};
}
}
function writeBrowserSavedEnvironmentRegistryDocument(
document: BrowserSavedEnvironmentRegistryDocument,
): void {
if (!hasWindow()) {
return;
}
setLocalStorageItem(
SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
document,
BrowserSavedEnvironmentRegistryDocumentSchema,
);
}
function readBrowserSavedEnvironmentRecordsWithSecrets(): ReadonlyArray<BrowserSavedEnvironmentRecord> {
return readBrowserSavedEnvironmentRegistryDocument().records ?? [];
}
function writeBrowserSavedEnvironmentRecords(
records: ReadonlyArray<BrowserSavedEnvironmentRecord>,
): void {
writeBrowserSavedEnvironmentRegistryDocument({
version: 1,
records,
});
}
export function readBrowserSavedEnvironmentRegistry(): ReadonlyArray<PersistedSavedEnvironmentRecord> {
return readBrowserSavedEnvironmentRecordsWithSecrets().map((record) =>
toPersistedSavedEnvironmentRecord(record),
);
}
export function writeBrowserSavedEnvironmentRegistry(
records: ReadonlyArray<PersistedSavedEnvironmentRecord>,
): void {
const existing = new Map(
readBrowserSavedEnvironmentRecordsWithSecrets().map(
(record) => [record.environmentId, record] as const,
),
);
writeBrowserSavedEnvironmentRecords(
records.map((record) => {
const bearerToken = existing.get(record.environmentId)?.bearerToken;
return bearerToken
? {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken,
}
: toPersistedSavedEnvironmentRecord(record);
}),
);
}
export function readBrowserSavedEnvironmentSecret(
environmentId: EnvironmentIdValue,
): string | null {
return (
readBrowserSavedEnvironmentRecordsWithSecrets().find(
(record) => record.environmentId === environmentId,
)?.bearerToken ?? null
);
}
export function writeBrowserSavedEnvironmentSecret(
environmentId: EnvironmentIdValue,
secret: string,
): boolean {
const document = readBrowserSavedEnvironmentRegistryDocument();
const records = document.records ?? [];
let found = false;
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
records: records.map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
found = true;
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
bearerToken: secret,
} satisfies BrowserSavedEnvironmentRecord;
}),
});
return found;
}
export function removeBrowserSavedEnvironmentSecret(environmentId: EnvironmentIdValue): void {
const document = readBrowserSavedEnvironmentRegistryDocument();
writeBrowserSavedEnvironmentRegistryDocument({
version: document.version ?? 1,
records: (document.records ?? []).map((record) => {
if (record.environmentId !== environmentId) {
return record;
}
return toPersistedSavedEnvironmentRecord(record);
}),
});
}
@@ -1,14 +1,21 @@
import type { GitBranch } from "@t3tools/contracts";
import { EnvironmentId, type GitBranch } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
dedupeRemoteBranchesWithLocalMatches,
deriveLocalBranchNameFromRemoteRef,
resolveEnvironmentOptionLabel,
resolveBranchSelectionTarget,
resolveCurrentWorkspaceLabel,
resolveDraftEnvModeAfterBranchChange,
resolveEffectiveEnvMode,
resolveEnvModeLabel,
resolveBranchToolbarValue,
shouldIncludeBranchPickerItem,
} from "./BranchToolbar.logic";
const localEnvironmentId = EnvironmentId.makeUnsafe("environment-local");
const remoteEnvironmentId = EnvironmentId.makeUnsafe("environment-remote");
describe("resolveDraftEnvModeAfterBranchChange", () => {
it("switches to local mode when returning from an existing worktree to the main worktree", () => {
expect(
@@ -76,6 +83,80 @@ describe("resolveBranchToolbarValue", () => {
});
});
describe("resolveEnvironmentOptionLabel", () => {
it("prefers the primary environment's machine label", () => {
expect(
resolveEnvironmentOptionLabel({
isPrimary: true,
environmentId: localEnvironmentId,
runtimeLabel: "Julius's Mac mini",
savedLabel: "Local environment",
}),
).toBe("Julius's Mac mini");
});
it("falls back to 'This device' for generic primary labels", () => {
expect(
resolveEnvironmentOptionLabel({
isPrimary: true,
environmentId: localEnvironmentId,
runtimeLabel: "Local environment",
savedLabel: "Local",
}),
).toBe("This device");
});
it("keeps configured labels for non-primary environments", () => {
expect(
resolveEnvironmentOptionLabel({
isPrimary: false,
environmentId: remoteEnvironmentId,
runtimeLabel: null,
savedLabel: "Build box",
}),
).toBe("Build box");
});
});
describe("resolveEffectiveEnvMode", () => {
it("treats draft threads already attached to a worktree as current-checkout mode", () => {
expect(
resolveEffectiveEnvMode({
activeWorktreePath: "/repo/.t3/worktrees/feature-a",
hasServerThread: false,
draftThreadEnvMode: "worktree",
}),
).toBe("local");
});
it("keeps explicit new-worktree mode for draft threads without a worktree path", () => {
expect(
resolveEffectiveEnvMode({
activeWorktreePath: null,
hasServerThread: false,
draftThreadEnvMode: "worktree",
}),
).toBe("worktree");
});
});
describe("resolveEnvModeLabel", () => {
it("uses explicit workspace labels", () => {
expect(resolveEnvModeLabel("local")).toBe("Current checkout");
expect(resolveEnvModeLabel("worktree")).toBe("New worktree");
});
});
describe("resolveCurrentWorkspaceLabel", () => {
it("describes the main repo checkout when no worktree path is active", () => {
expect(resolveCurrentWorkspaceLabel(null)).toBe("Current checkout");
});
it("describes the active checkout as a worktree when one is attached", () => {
expect(resolveCurrentWorkspaceLabel("/repo/.t3/worktrees/feature-a")).toBe("Current worktree");
});
});
describe("deriveLocalBranchNameFromRemoteRef", () => {
it("strips the remote prefix from a remote ref", () => {
expect(deriveLocalBranchNameFromRemoteRef("origin/feature/demo")).toBe("feature/demo");
+42 -3
View File
@@ -15,15 +15,54 @@ export interface EnvironmentOption {
export const EnvMode = Schema.Literals(["local", "worktree"]);
export type EnvMode = typeof EnvMode.Type;
const GENERIC_LOCAL_ENVIRONMENT_LABELS = new Set(["local", "local environment"]);
function normalizeDisplayLabel(value: string | null | undefined): string | null {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
}
export function resolveEnvironmentOptionLabel(input: {
isPrimary: boolean;
environmentId: EnvironmentId;
runtimeLabel?: string | null;
savedLabel?: string | null;
}): string {
const runtimeLabel = normalizeDisplayLabel(input.runtimeLabel);
const savedLabel = normalizeDisplayLabel(input.savedLabel);
if (input.isPrimary) {
const preferredLocalLabel = [runtimeLabel, savedLabel].find((label) => {
if (!label) return false;
return !GENERIC_LOCAL_ENVIRONMENT_LABELS.has(label.toLowerCase());
});
return preferredLocalLabel ?? "This device";
}
return runtimeLabel ?? savedLabel ?? input.environmentId;
}
export function resolveEnvModeLabel(mode: EnvMode): string {
return mode === "worktree" ? "New worktree" : "Current checkout";
}
export function resolveCurrentWorkspaceLabel(activeWorktreePath: string | null): string {
return activeWorktreePath ? "Current worktree" : resolveEnvModeLabel("local");
}
export function resolveEffectiveEnvMode(input: {
activeWorktreePath: string | null;
hasServerThread: boolean;
draftThreadEnvMode: EnvMode | undefined;
}): EnvMode {
const { activeWorktreePath, hasServerThread, draftThreadEnvMode } = input;
return activeWorktreePath || (!hasServerThread && draftThreadEnvMode === "worktree")
? "worktree"
: "local";
if (!hasServerThread) {
if (activeWorktreePath) {
return "local";
}
return draftThreadEnvMode === "worktree" ? "worktree" : "local";
}
return activeWorktreePath ? "worktree" : "local";
}
export function resolveDraftEnvModeAfterBranchChange(input: {
+6 -5
View File
@@ -1,6 +1,6 @@
import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { memo, useMemo } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useStore } from "../store";
@@ -27,7 +27,7 @@ interface BranchToolbarProps {
onEnvironmentChange?: (environmentId: EnvironmentId) => void;
}
export function BranchToolbar({
export const BranchToolbar = memo(function BranchToolbar({
environmentId,
threadId,
draftId,
@@ -62,6 +62,7 @@ export function BranchToolbar({
hasServerThread: serverThread !== undefined,
draftThreadEnvMode: draftThread?.envMode,
});
const envModeLocked = envLocked || (serverThread !== undefined && activeWorktreePath !== null);
const showEnvironmentPicker =
availableEnvironments && availableEnvironments.length > 1 && onEnvironmentChange;
@@ -69,7 +70,7 @@ export function BranchToolbar({
if (!hasActiveThread || !activeProject) return null;
return (
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
<div className="mx-auto flex w-full max-w-208 items-center justify-between px-2.5 pb-3 pt-1 sm:px-3">
<div className="flex items-center gap-1">
{showEnvironmentPicker && (
<>
@@ -83,7 +84,7 @@ export function BranchToolbar({
</>
)}
<BranchToolbarEnvModeSelector
envLocked={envLocked}
envLocked={envModeLocked}
effectiveEnvMode={effectiveEnvMode}
activeWorktreePath={activeWorktreePath}
onEnvModeChange={onEnvModeChange}
@@ -100,4 +101,4 @@ export function BranchToolbar({
/>
</div>
);
}
});
@@ -144,7 +144,7 @@ export function BranchToolbarBranchSelector({
});
}
if (hasServerThread) {
setThreadBranchAction(activeThreadId, branch, worktreePath);
setThreadBranchAction(threadRef, branch, worktreePath);
return;
}
const nextDraftEnvMode = resolveDraftEnvModeAfterBranchChange({
@@ -1,13 +1,20 @@
import { FolderIcon, GitForkIcon } from "lucide-react";
import { memo } from "react";
import { FolderGit2Icon, FolderGitIcon, FolderIcon } from "lucide-react";
import { memo, useMemo } from "react";
import type { EnvMode } from "./BranchToolbar.logic";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
const envModeItems = [
{ value: "local", label: "Local" },
{ value: "worktree", label: "New worktree" },
] as const;
import {
resolveCurrentWorkspaceLabel,
resolveEnvModeLabel,
type EnvMode,
} from "./BranchToolbar.logic";
import {
Select,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "./ui/select";
interface BranchToolbarEnvModeSelectorProps {
envLocked: boolean;
@@ -22,18 +29,26 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
activeWorktreePath,
onEnvModeChange,
}: BranchToolbarEnvModeSelectorProps) {
if (envLocked || activeWorktreePath) {
const envModeItems = useMemo(
() => [
{ value: "local", label: resolveCurrentWorkspaceLabel(activeWorktreePath) },
{ value: "worktree", label: resolveEnvModeLabel("worktree") },
],
[activeWorktreePath],
);
if (envLocked) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
{activeWorktreePath ? (
<>
<GitForkIcon className="size-3" />
Worktree
<FolderGitIcon className="size-3" />
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</>
) : (
<>
<FolderIcon className="size-3" />
Local
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</>
)}
</span>
@@ -46,27 +61,36 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
items={envModeItems}
>
<SelectTrigger variant="ghost" size="xs" className="font-medium">
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Workspace">
{effectiveEnvMode === "worktree" ? (
<GitForkIcon className="size-3" />
<FolderGit2Icon className="size-3" />
) : activeWorktreePath ? (
<FolderGitIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
<SelectValue />
</SelectTrigger>
<SelectPopup>
<SelectItem value="local">
<span className="inline-flex items-center gap-1.5">
<FolderIcon className="size-3" />
Local
</span>
</SelectItem>
<SelectItem value="worktree">
<span className="inline-flex items-center gap-1.5">
<GitForkIcon className="size-3" />
New worktree
</span>
</SelectItem>
<SelectGroup>
<SelectGroupLabel>Workspace</SelectGroupLabel>
<SelectItem value="local">
<span className="inline-flex items-center gap-1.5">
{activeWorktreePath ? (
<FolderGitIcon className="size-3" />
) : (
<FolderIcon className="size-3" />
)}
{resolveCurrentWorkspaceLabel(activeWorktreePath)}
</span>
</SelectItem>
<SelectItem value="worktree">
<span className="inline-flex items-center gap-1.5">
<FolderGit2Icon className="size-3" />
{resolveEnvModeLabel("worktree")}
</span>
</SelectItem>
</SelectGroup>
</SelectPopup>
</Select>
);
@@ -1,9 +1,17 @@
import type { EnvironmentId } from "@t3tools/contracts";
import { CloudIcon, FolderIcon, ServerIcon } from "lucide-react";
import { CloudIcon, MonitorIcon } from "lucide-react";
import { memo, useMemo } from "react";
import type { EnvironmentOption } from "./BranchToolbar.logic";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
import {
Select,
SelectGroup,
SelectGroupLabel,
SelectItem,
SelectPopup,
SelectTrigger,
SelectValue,
} from "./ui/select";
interface BranchToolbarEnvironmentSelectorProps {
envLocked: boolean;
@@ -18,8 +26,8 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
availableEnvironments,
onEnvironmentChange,
}: BranchToolbarEnvironmentSelectorProps) {
const activeEnvironmentLabel = useMemo(() => {
return availableEnvironments.find((env) => env.environmentId === environmentId)?.label ?? null;
const activeEnvironment = useMemo(() => {
return availableEnvironments.find((env) => env.environmentId === environmentId) ?? null;
}, [availableEnvironments, environmentId]);
const environmentItems = useMemo(
@@ -34,8 +42,12 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
if (envLocked) {
return (
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
<ServerIcon className="size-3" />
{activeEnvironmentLabel ?? "Environment"}
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3" />
) : (
<CloudIcon className="size-3" />
)}
{activeEnvironment?.label ?? "Run on"}
</span>
);
}
@@ -46,19 +58,30 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
onValueChange={(value) => onEnvironmentChange(value as EnvironmentId)}
items={environmentItems}
>
<SelectTrigger variant="ghost" size="xs" className="font-medium">
<ServerIcon className="size-3" />
<SelectTrigger variant="ghost" size="xs" className="font-medium" aria-label="Run on">
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3" />
) : (
<CloudIcon className="size-3" />
)}
<SelectValue />
</SelectTrigger>
<SelectPopup>
{availableEnvironments.map((env) => (
<SelectItem key={env.environmentId} value={env.environmentId}>
<span className="inline-flex items-center gap-1.5">
{env.isPrimary ? <FolderIcon className="size-3" /> : <CloudIcon className="size-3" />}
{env.label}
</span>
</SelectItem>
))}
<SelectGroup>
<SelectGroupLabel>Run on</SelectGroupLabel>
{availableEnvironments.map((env) => (
<SelectItem key={env.environmentId} value={env.environmentId}>
<span className="inline-flex items-center gap-1.5">
{env.isPrimary ? (
<MonitorIcon className="size-3" />
) : (
<CloudIcon className="size-3" />
)}
{env.label}
</span>
</SelectItem>
))}
</SelectGroup>
</SelectPopup>
</Select>
);
@@ -0,0 +1,79 @@
import "../index.css";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const { openInPreferredEditorMock, readLocalApiMock } = vi.hoisted(() => ({
openInPreferredEditorMock: vi.fn(async () => "vscode"),
readLocalApiMock: vi.fn(() => ({
server: { getConfig: vi.fn(async () => ({ availableEditors: ["vscode"] })) },
shell: { openInEditor: vi.fn(async () => undefined) },
})),
}));
vi.mock("../editorPreferences", () => ({
openInPreferredEditor: openInPreferredEditorMock,
}));
vi.mock("../localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: readLocalApiMock,
}));
import ChatMarkdown from "./ChatMarkdown";
describe("ChatMarkdown", () => {
afterEach(() => {
openInPreferredEditorMock.mockClear();
readLocalApiMock.mockClear();
localStorage.clear();
document.body.innerHTML = "";
});
it("rewrites file uri hrefs into direct paths before rendering", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts](file://${filePath})`} cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "PermissionRule.ts" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", filePath);
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), filePath);
});
} finally {
await screen.unmount();
}
});
it("keeps line anchors working after rewriting file uri hrefs", async () => {
const filePath =
"/Users/yashsingh/p/sco/claude-code-extract/src/utils/permissions/PermissionRule.ts";
const screen = await render(
<ChatMarkdown text={`[PermissionRule.ts:1](file://${filePath}#L1)`} cwd="/repo/project" />,
);
try {
const link = page.getByRole("link", { name: "PermissionRule.ts:1" });
await expect.element(link).toBeInTheDocument();
await expect.element(link).toHaveAttribute("href", `${filePath}#L1`);
await link.click();
await vi.waitFor(() => {
expect(openInPreferredEditorMock).toHaveBeenCalledWith(expect.anything(), `${filePath}:1`);
});
} finally {
await screen.unmount();
}
});
});
+11 -3
View File
@@ -15,13 +15,14 @@ import React, {
} from "react";
import type { Components } from "react-markdown";
import ReactMarkdown from "react-markdown";
import { defaultUrlTransform } from "react-markdown";
import remarkGfm from "remark-gfm";
import { openInPreferredEditor } from "../editorPreferences";
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
import { fnv1a32 } from "../lib/diffRendering";
import { LRUCache } from "../lib/lruCache";
import { useTheme } from "../hooks/useTheme";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "../markdown-links";
import { readLocalApi } from "../localApi";
class CodeHighlightErrorBoundary extends React.Component<
@@ -164,7 +165,7 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
);
return (
<div className="chat-markdown-codeblock">
<div className="chat-markdown-codeblock leading-snug">
<button
type="button"
className="chat-markdown-copy-button"
@@ -238,6 +239,9 @@ function SuspenseShikiCodeBlock({
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownUrlTransform = useCallback((href: string) => {
return rewriteMarkdownFileUriHref(href) ?? defaultUrlTransform(href);
}, []);
const markdownComponents = useMemo<Components>(
() => ({
a({ node: _node, href, ...props }) {
@@ -290,7 +294,11 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
return (
<div className="chat-markdown w-full min-w-0 text-sm leading-relaxed text-foreground/80">
<ReactMarkdown remarkPlugins={[remarkGfm]} components={markdownComponents}>
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={markdownComponents}
urlTransform={markdownUrlTransform}
>
{text}
</ReactMarkdown>
</div>
+374 -2
View File
@@ -915,13 +915,189 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
);
}
async function pressComposerKey(key: string): Promise<void> {
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
const keydownEvent = new KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
});
composerEditor.dispatchEvent(keydownEvent);
if (keydownEvent.defaultPrevented) {
await waitForLayout();
return;
}
const beforeInputEvent = new InputEvent("beforeinput", {
data: key,
inputType: "insertText",
bubbles: true,
cancelable: true,
});
composerEditor.dispatchEvent(beforeInputEvent);
if (beforeInputEvent.defaultPrevented) {
await waitForLayout();
return;
}
if (
typeof document.execCommand === "function" &&
document.execCommand("insertText", false, key)
) {
await waitForLayout();
return;
}
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) {
throw new Error("Unable to resolve composer selection for text input.");
}
const range = selection.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(key);
range.insertNode(textNode);
range.setStartAfter(textNode);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
composerEditor.dispatchEvent(
new InputEvent("input", {
data: key,
inputType: "insertText",
bubbles: true,
}),
);
await waitForLayout();
}
async function pressComposerUndo(): Promise<void> {
const composerEditor = await waitForComposerEditor();
const useMetaForMod = isMacPlatform(navigator.platform);
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "z",
metaKey: useMetaForMod,
ctrlKey: !useMetaForMod,
bubbles: true,
cancelable: true,
}),
);
await waitForLayout();
}
async function waitForComposerText(expectedText: string): Promise<void> {
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftsByThreadKey[THREAD_KEY]?.prompt ?? "").toBe(
expectedText,
);
},
{ timeout: 8_000, interval: 16 },
);
}
async function setComposerSelectionByTextOffsets(options: {
start: number;
end: number;
direction?: "forward" | "backward";
}): Promise<void> {
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
const resolvePoint = (targetOffset: number) => {
const traversedRef = { value: 0 };
const visitNode = (node: Node): { node: Node; offset: number } | null => {
if (node.nodeType === Node.TEXT_NODE) {
const textLength = node.textContent?.length ?? 0;
if (targetOffset <= traversedRef.value + textLength) {
return {
node,
offset: Math.max(0, Math.min(targetOffset - traversedRef.value, textLength)),
};
}
traversedRef.value += textLength;
return null;
}
if (node instanceof HTMLBRElement) {
const parent = node.parentNode;
if (!parent) {
return null;
}
const siblingIndex = Array.prototype.indexOf.call(parent.childNodes, node);
if (targetOffset <= traversedRef.value) {
return { node: parent, offset: siblingIndex };
}
if (targetOffset <= traversedRef.value + 1) {
return { node: parent, offset: siblingIndex + 1 };
}
traversedRef.value += 1;
return null;
}
if (node instanceof Element || node instanceof DocumentFragment) {
for (const child of node.childNodes) {
const point = visitNode(child);
if (point) {
return point;
}
}
}
return null;
};
return (
visitNode(composerEditor) ?? {
node: composerEditor,
offset: composerEditor.childNodes.length,
}
);
};
const startPoint = resolvePoint(options.start);
const endPoint = resolvePoint(options.end);
const selection = window.getSelection();
if (!selection) {
throw new Error("Unable to resolve window selection.");
}
selection.removeAllRanges();
if (options.direction === "backward" && "setBaseAndExtent" in selection) {
selection.setBaseAndExtent(endPoint.node, endPoint.offset, startPoint.node, startPoint.offset);
await waitForLayout();
return;
}
const range = document.createRange();
range.setStart(startPoint.node, startPoint.offset);
range.setEnd(endPoint.node, endPoint.offset);
selection.addRange(range);
await waitForLayout();
}
async function selectAllComposerContent(): Promise<void> {
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
const selection = window.getSelection();
if (!selection) {
throw new Error("Unable to resolve window selection.");
}
selection.removeAllRanges();
const range = document.createRange();
range.selectNodeContents(composerEditor);
selection.addRange(range);
await waitForLayout();
}
async function waitForComposerMenuItem(itemId: string): Promise<HTMLElement> {
return waitForElement(
() => document.querySelector<HTMLElement>(`[data-composer-item-id="${itemId}"]`),
`Unable to find composer menu item "${itemId}".`,
);
}
async function waitForSendButton(): Promise<HTMLButtonElement> {
return waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
@@ -1993,7 +2169,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
viewport: WIDE_FOOTER_VIEWPORT,
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
{
id: "setup",
@@ -2336,6 +2512,202 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("surrounds selected plain text and preserves the inner selection for repeated wrapping", async () => {
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-basic" as MessageId,
targetText: "surround basic",
}),
});
try {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected");
await waitForComposerText("selected");
await setComposerSelectionByTextOffsets({ start: 0, end: "selected".length });
await pressComposerKey("(");
await waitForComposerText("(selected)");
await pressComposerKey("[");
await waitForComposerText("([selected])");
} finally {
await mounted.cleanup();
}
});
it("leaves collapsed-caret typing unchanged for surround symbols", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "selected");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-collapsed" as MessageId,
targetText: "surround collapsed",
}),
});
try {
await waitForComposerText("selected");
await setComposerSelectionByTextOffsets({
start: "selected".length,
end: "selected".length,
});
await pressComposerKey("(");
await waitForComposerText("selected(");
} finally {
await mounted.cleanup();
}
});
it("supports symmetric and backward-selection surrounds", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "backward");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-backward" as MessageId,
targetText: "surround backward",
}),
});
try {
await waitForComposerText("backward");
await setComposerSelectionByTextOffsets({
start: 0,
end: "backward".length,
direction: "backward",
});
await pressComposerKey("*");
await waitForComposerText("*backward*");
} finally {
await mounted.cleanup();
}
});
it("supports option-produced surround symbols like guillemets", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-guillemet" as MessageId,
targetText: "surround guillemet",
}),
});
try {
await waitForComposerText("quoted");
await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length });
await pressComposerKey("«");
await waitForComposerText("«quoted»");
} finally {
await mounted.cleanup();
}
});
it("supports dead-key composition that resolves to another surround symbol without an extra undo step", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "quoted");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-dead-quote" as MessageId,
targetText: "surround dead quote",
}),
});
try {
await waitForComposerText("quoted");
await setComposerSelectionByTextOffsets({ start: 0, end: "quoted".length });
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
composerEditor.dispatchEvent(
new KeyboardEvent("keydown", {
key: "Dead",
bubbles: true,
cancelable: true,
}),
);
composerEditor.dispatchEvent(
new InputEvent("beforeinput", {
data: "'",
inputType: "insertCompositionText",
bubbles: true,
cancelable: true,
}),
);
const resolvedInputEvent = new InputEvent("beforeinput", {
data: "'",
inputType: "insertText",
bubbles: true,
cancelable: true,
});
composerEditor.dispatchEvent(resolvedInputEvent);
expect(resolvedInputEvent.defaultPrevented).toBe(true);
await waitForComposerText("'quoted'");
await pressComposerUndo();
await waitForComposerText("quoted");
} finally {
await mounted.cleanup();
}
});
it("surrounds text after a mention using the correct expanded offsets", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-after-mention" as MessageId,
targetText: "surround after mention",
}),
});
try {
await vi.waitFor(
() => {
expect(document.body.textContent).toContain("package.json");
},
{ timeout: 8_000, interval: 16 },
);
await waitForComposerText("hi @package.json there");
await setComposerSelectionByTextOffsets({
start: "hi package.json ".length,
end: "hi package.json there".length,
});
await pressComposerKey("(");
await waitForComposerText("hi @package.json (there)");
} finally {
await mounted.cleanup();
}
});
it("falls back to normal replacement when the selection includes a mention token", async () => {
useComposerDraftStore.getState().setPrompt(THREAD_REF, "hi @package.json there ");
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: createSnapshotForTargetUser({
targetMessageId: "msg-user-surround-token" as MessageId,
targetText: "surround token",
}),
});
try {
await vi.waitFor(
() => {
expect(document.body.textContent).toContain("package.json");
},
{ timeout: 8_000, interval: 16 },
);
await selectAllComposerContent();
await pressComposerKey("(");
await waitForComposerText("(");
} finally {
await mounted.cleanup();
}
});
it("shows runtime mode descriptions in the desktop composer access select", async () => {
setDraftThreadWithoutWorktree();
+12
View File
@@ -2,6 +2,7 @@ import {
type EnvironmentId,
ProjectId,
type ModelSelection,
type ProviderKind,
type ScopedThreadRef,
type ThreadId,
type TurnId,
@@ -225,6 +226,17 @@ export function threadHasStarted(thread: Thread | null | undefined): boolean {
);
}
export function deriveLockedProvider(input: {
thread: Thread | null | undefined;
selectedProvider: ProviderKind | null;
threadProvider: ProviderKind | null;
}): ProviderKind | null {
if (!threadHasStarted(input.thread)) {
return null;
}
return input.thread?.session?.provider ?? input.threadProvider ?? input.selectedProvider ?? null;
}
export async function waitForStartedServerThread(
threadRef: ScopedThreadRef,
timeoutMs = 1_000,
File diff suppressed because it is too large. Load diff
@@ -26,6 +26,7 @@ import {
COMMAND_PRIORITY_HIGH,
KEY_BACKSPACE_COMMAND,
$getRoot,
HISTORY_MERGE_TAG,
DecoratorNode,
type ElementNode,
type LexicalNode,
@@ -58,7 +59,10 @@ import {
expandCollapsedComposerCursor,
isCollapsedCursorAdjacentToInlineToken,
} from "~/composer-logic";
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
import {
selectionTouchesMentionBoundary,
splitPromptIntoComposerSegments,
} from "~/composer-editor-mentions";
import {
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
type TerminalContextDraft,
@@ -73,6 +77,21 @@ import {
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
const SURROUND_SYMBOLS: [string, string][] = [
["(", ")"],
["[", "]"],
["{", "}"],
["'", "'"],
['"', '"'],
["“", "”"],
["`", "`"],
["<", ">"],
["«", "»"],
["*", "*"],
["_", "_"],
];
const SURROUND_SYMBOLS_MAP = new Map<string, string>(SURROUND_SYMBOLS);
const BACKTICK_SURROUND_CLOSE_SYMBOL = SURROUND_SYMBOLS_MAP.get("`") ?? null;
type SerializedComposerMentionNode = Spread<
{
@@ -553,6 +572,53 @@ function $setSelectionAtComposerOffset(nextOffset: number): void {
$setSelection(selection);
}
function $setSelectionRangeAtComposerOffsets(startOffset: number, endOffset: number): void {
const root = $getRoot();
const composerLength = $getComposerRootLength();
const boundedStart = Math.max(0, Math.min(startOffset, composerLength));
const boundedEnd = Math.max(0, Math.min(endOffset, composerLength));
const anchorRemainingRef = { value: boundedStart };
const focusRemainingRef = { value: boundedEnd };
const anchorPoint = findSelectionPointAtOffset(root, anchorRemainingRef) ?? {
key: root.getKey(),
offset: root.getChildren().length,
type: "element" as const,
};
const focusPoint = findSelectionPointAtOffset(root, focusRemainingRef) ?? {
key: root.getKey(),
offset: root.getChildren().length,
type: "element" as const,
};
const selection = $createRangeSelection();
selection.anchor.set(anchorPoint.key, anchorPoint.offset, anchorPoint.type);
selection.focus.set(focusPoint.key, focusPoint.offset, focusPoint.type);
$setSelection(selection);
}
function getSelectionRangeForExpandedComposerOffsets(selection: ReturnType<typeof $getSelection>): {
start: number;
end: number;
} | null {
if (!$isRangeSelection(selection)) {
return null;
}
const anchorNode = selection.anchor.getNode();
const focusNode = selection.focus.getNode();
const anchorOffset = getExpandedAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
const focusOffset = getExpandedAbsoluteOffsetForPoint(focusNode, selection.focus.offset);
return {
start: Math.min(anchorOffset, focusOffset),
end: Math.max(anchorOffset, focusOffset),
};
}
function $selectionTouchesInlineToken(selection: ReturnType<typeof $getSelection>): boolean {
if (!$isRangeSelection(selection)) {
return false;
}
return selection.getNodes().some((node) => isComposerInlineTokenNode(node));
}
function $readSelectionOffsetFromEditorState(fallback: number): number {
const selection = $getSelection();
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
@@ -878,6 +944,269 @@ function ComposerInlineTokenBackspacePlugin() {
return null;
}
function ComposerSurroundSelectionPlugin(props: {
terminalContexts: ReadonlyArray<TerminalContextDraft>;
}) {
const [editor] = useLexicalComposerContext();
const terminalContextsRef = useRef(props.terminalContexts);
const pendingSurroundSelectionRef = useRef<{
value: string;
expandedStart: number;
expandedEnd: number;
} | null>(null);
const pendingDeadKeySelectionRef = useRef<{
value: string;
expandedStart: number;
expandedEnd: number;
} | null>(null);
useEffect(() => {
terminalContextsRef.current = props.terminalContexts;
}, [props.terminalContexts]);
const applySurroundInsertion = useCallback(
(inputData: string): boolean => {
const surroundCloseSymbol = SURROUND_SYMBOLS_MAP.get(inputData);
const pendingSurroundSelection = pendingSurroundSelectionRef.current;
if (!surroundCloseSymbol) {
pendingSurroundSelectionRef.current = null;
return false;
}
let handled = false;
editor.update(() => {
const selectionSnapshot =
pendingSurroundSelection ??
(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || selection.isCollapsed()) {
return null;
}
if ($selectionTouchesInlineToken(selection)) {
return null;
}
const range = getSelectionRangeForExpandedComposerOffsets(selection);
if (!range || range.start === range.end) {
return null;
}
const value = $getRoot().getTextContent();
if (selectionTouchesMentionBoundary(value, range.start, range.end)) {
return null;
}
return {
value,
expandedStart: range.start,
expandedEnd: range.end,
};
})();
if (!selectionSnapshot || !surroundCloseSymbol) {
return;
}
const selectedText = selectionSnapshot.value.slice(
selectionSnapshot.expandedStart,
selectionSnapshot.expandedEnd,
);
const nextValue = `${selectionSnapshot.value.slice(0, selectionSnapshot.expandedStart)}${inputData}${selectedText}${surroundCloseSymbol}${selectionSnapshot.value.slice(selectionSnapshot.expandedEnd)}`;
$setComposerEditorPrompt(nextValue, terminalContextsRef.current);
const selectionStart = collapseExpandedComposerCursor(
nextValue,
selectionSnapshot.expandedStart,
);
$setSelectionRangeAtComposerOffsets(
selectionStart + inputData.length,
selectionStart + inputData.length + selectedText.length,
);
handled = true;
pendingSurroundSelectionRef.current = null;
});
return handled;
},
[editor],
);
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
if (pendingDeadKeySelectionRef.current) {
if (event.key === "Dead" || event.key === " " || event.code === "Space") {
return;
}
pendingDeadKeySelectionRef.current = null;
}
if (event.defaultPrevented || event.isComposing || event.metaKey || event.ctrlKey) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
editor.getEditorState().read(() => {
const selection = $getSelection();
if (!$isRangeSelection(selection) || selection.isCollapsed()) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
if ($selectionTouchesInlineToken(selection)) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
const range = getSelectionRangeForExpandedComposerOffsets(selection);
if (!range || range.start === range.end) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
const value = $getRoot().getTextContent();
if (selectionTouchesMentionBoundary(value, range.start, range.end)) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
const snapshot = {
value,
expandedStart: range.start,
expandedEnd: range.end,
};
pendingSurroundSelectionRef.current = snapshot;
pendingDeadKeySelectionRef.current = null;
});
};
const onBeforeInput = (event: InputEvent) => {
if (
event.inputType === "insertCompositionText" &&
event.data === "`" &&
BACKTICK_SURROUND_CLOSE_SYMBOL !== null &&
pendingSurroundSelectionRef.current
) {
pendingDeadKeySelectionRef.current = pendingSurroundSelectionRef.current;
return;
}
if (pendingDeadKeySelectionRef.current) {
return;
}
if (event.inputType === "insertCompositionText") {
return;
}
if (typeof event.data !== "string") {
pendingSurroundSelectionRef.current = null;
return;
}
const inputData = event.inputType === "insertText" ? event.data : null;
if (!inputData || inputData.length !== 1) {
pendingSurroundSelectionRef.current = null;
return;
}
if (!applySurroundInsertion(inputData)) {
return;
}
event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();
};
const tryApplyDeadKeyBacktickSurround = (options?: { finalAttempt?: boolean }) => {
queueMicrotask(() => {
editor.update(
() => {
const pendingDeadKeySelection = pendingDeadKeySelectionRef.current;
if (!pendingDeadKeySelection) {
return;
}
const currentValue = $getRoot().getTextContent();
const backtickCloseSymbol = BACKTICK_SURROUND_CLOSE_SYMBOL;
if (backtickCloseSymbol === null) {
pendingDeadKeySelectionRef.current = null;
return;
}
const expectedResolvedValue = `${pendingDeadKeySelection.value.slice(0, pendingDeadKeySelection.expandedStart)}\`${pendingDeadKeySelection.value.slice(pendingDeadKeySelection.expandedEnd)}`;
if (currentValue !== expectedResolvedValue) {
if (options?.finalAttempt) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
}
return;
}
const selectedText = pendingDeadKeySelection.value.slice(
pendingDeadKeySelection.expandedStart,
pendingDeadKeySelection.expandedEnd,
);
const replacementStart = collapseExpandedComposerCursor(
currentValue,
pendingDeadKeySelection.expandedStart,
);
$setSelectionRangeAtComposerOffsets(replacementStart, replacementStart + 1);
const replacementSelection = $getSelection();
if (!$isRangeSelection(replacementSelection)) {
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
return;
}
replacementSelection.insertText(`\`${selectedText}${backtickCloseSymbol}`);
$setSelectionRangeAtComposerOffsets(
replacementStart + 1,
replacementStart + 1 + selectedText.length,
);
pendingSurroundSelectionRef.current = null;
pendingDeadKeySelectionRef.current = null;
},
{ tag: HISTORY_MERGE_TAG },
);
});
};
const onInput = (event: Event) => {
const inputEvent = event as InputEvent;
if (
inputEvent.inputType === "insertText" ||
inputEvent.inputType === "insertCompositionText"
) {
tryApplyDeadKeyBacktickSurround();
}
};
const onCompositionEnd = () => {
tryApplyDeadKeyBacktickSurround({ finalAttempt: true });
};
let activeRootElement: HTMLElement | null = null;
const unregisterRootListener = editor.registerRootListener((rootElement, prevRootElement) => {
prevRootElement?.removeEventListener("keydown", onKeyDown);
prevRootElement?.removeEventListener("beforeinput", onBeforeInput, true);
prevRootElement?.removeEventListener("input", onInput);
prevRootElement?.removeEventListener("compositionend", onCompositionEnd);
rootElement?.addEventListener("keydown", onKeyDown);
rootElement?.addEventListener("beforeinput", onBeforeInput, true);
rootElement?.addEventListener("input", onInput);
rootElement?.addEventListener("compositionend", onCompositionEnd);
activeRootElement = rootElement;
});
return () => {
if (activeRootElement) {
activeRootElement.removeEventListener("keydown", onKeyDown);
activeRootElement.removeEventListener("beforeinput", onBeforeInput, true);
activeRootElement.removeEventListener("input", onInput);
activeRootElement.removeEventListener("compositionend", onCompositionEnd);
}
unregisterRootListener();
};
}, [applySurroundInsertion, editor]);
return null;
}
function ComposerPromptEditorInner({
value,
cursor,
@@ -1113,6 +1442,7 @@ function ComposerPromptEditorInner({
/>
<OnChangePlugin onChange={handleEditorChange} />
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
<ComposerSurroundSelectionPlugin terminalContexts={terminalContexts} />
<ComposerInlineTokenArrowPlugin />
<ComposerInlineTokenSelectionNormalizePlugin />
<ComposerInlineTokenBackspacePlugin />
@@ -4,9 +4,9 @@ import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
const THREAD_A = ThreadId.makeUnsafe("thread-a");
const THREAD_B = ThreadId.makeUnsafe("thread-b");
const ENVIRONMENT_ID = "environment-local" as never;
const SHARED_THREAD_ID = ThreadId.makeUnsafe("thread-shared");
const ENVIRONMENT_A = "environment-local" as never;
const ENVIRONMENT_B = "environment-remote" as never;
const GIT_CWD = "/repo/project";
const BRANCH_NAME = "feature/toast-scope";
@@ -24,9 +24,12 @@ function createDeferredPromise<T>() {
const {
activeRunStackedActionDeferredRef,
activeDraftThreadRef,
hasServerThreadRef,
invalidateGitQueriesSpy,
refreshGitStatusSpy,
runStackedActionMutateAsyncSpy,
setDraftThreadContextSpy,
setThreadBranchSpy,
toastAddSpy,
toastCloseSpy,
@@ -34,9 +37,12 @@ const {
toastUpdateSpy,
} = vi.hoisted(() => ({
activeRunStackedActionDeferredRef: { current: createDeferredPromise<never>() },
activeDraftThreadRef: { current: null as unknown },
hasServerThreadRef: { current: true },
invalidateGitQueriesSpy: vi.fn(() => Promise.resolve()),
refreshGitStatusSpy: vi.fn(() => Promise.resolve(null)),
runStackedActionMutateAsyncSpy: vi.fn(() => activeRunStackedActionDeferredRef.current.promise),
setDraftThreadContextSpy: vi.fn(),
setThreadBranchSpy: vi.fn(),
toastAddSpy: vi.fn(() => "toast-1"),
toastCloseSpy: vi.fn(),
@@ -120,9 +126,42 @@ vi.mock("~/lib/gitStatusState", () => ({
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: vi.fn(() => null),
}));
vi.mock("~/composerDraftStore", async () => {
const draftStoreState = {
getDraftThreadByRef: () => activeDraftThreadRef.current,
getDraftSession: () => activeDraftThreadRef.current,
getDraftThread: () => activeDraftThreadRef.current,
getDraftSessionByLogicalProjectKey: () => null,
setDraftThreadContext: setDraftThreadContextSpy,
setLogicalProjectDraftThreadId: vi.fn(),
setProjectDraftThreadId: vi.fn(),
hasDraftThreadsInEnvironment: () => false,
clearDraftThread: vi.fn(),
};
return {
DraftId: {
makeUnsafe: (value: string) => value,
},
useComposerDraftStore: Object.assign(
(selector: (state: unknown) => unknown) => selector(draftStoreState),
{ getState: () => draftStoreState },
),
markPromotedDraftThread: vi.fn(),
markPromotedDraftThreadByRef: vi.fn(),
markPromotedDraftThreads: vi.fn(),
markPromotedDraftThreadsByRef: vi.fn(),
finalizePromotedDraftThreadByRef: vi.fn(),
finalizePromotedDraftThreadsByRef: vi.fn(),
};
});
vi.mock("~/store", () => ({
selectEnvironmentState: (
state: { environmentStateById: Record<string, unknown> },
@@ -154,11 +193,37 @@ vi.mock("~/store", () => ({
selector({
setThreadBranch: setThreadBranchSpy,
environmentStateById: {
[ENVIRONMENT_ID]: {
threadShellById: {
[THREAD_A]: { id: THREAD_A, branch: BRANCH_NAME, worktreePath: null },
[THREAD_B]: { id: THREAD_B, branch: BRANCH_NAME, worktreePath: null },
},
[ENVIRONMENT_A]: {
threadShellById: hasServerThreadRef.current
? {
[SHARED_THREAD_ID]: {
id: SHARED_THREAD_ID,
branch: BRANCH_NAME,
worktreePath: null,
},
}
: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
messageByThreadId: {},
activityIdsByThreadId: {},
activityByThreadId: {},
proposedPlanIdsByThreadId: {},
proposedPlanByThreadId: {},
turnDiffIdsByThreadId: {},
turnDiffSummaryByThreadId: {},
},
[ENVIRONMENT_B]: {
threadShellById: hasServerThreadRef.current
? {
[SHARED_THREAD_ID]: {
id: SHARED_THREAD_ID,
branch: BRANCH_NAME,
worktreePath: null,
},
}
: {},
threadSessionById: {},
threadTurnStateById: {},
messageIdsByThreadId: {},
@@ -187,17 +252,19 @@ function findButtonByText(text: string): HTMLButtonElement | null {
}
function Harness() {
const [activeThreadId, setActiveThreadId] = useState(THREAD_A);
const [activeThreadRef, setActiveThreadRef] = useState(
scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
);
return (
<>
<button type="button" onClick={() => setActiveThreadId(THREAD_B)}>
Switch thread
<button
type="button"
onClick={() => setActiveThreadRef(scopeThreadRef(ENVIRONMENT_B, SHARED_THREAD_ID))}
>
Switch environment
</button>
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, activeThreadId)}
/>
<GitActionsControl gitCwd={GIT_CWD} activeThreadRef={activeThreadRef} />
</>
);
}
@@ -207,10 +274,12 @@ describe("GitActionsControl thread-scoped progress toast", () => {
vi.useRealTimers();
vi.clearAllMocks();
activeRunStackedActionDeferredRef.current = createDeferredPromise<never>();
activeDraftThreadRef.current = null;
hasServerThreadRef.current = true;
document.body.innerHTML = "";
});
it("keeps an in-flight git action toast pinned to the thread that started it", async () => {
it("keeps an in-flight git action toast pinned to the thread ref that started it", async () => {
vi.useFakeTimers();
const host = document.createElement("div");
@@ -227,7 +296,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
expect(toastAddSpy).toHaveBeenCalledWith(
expect.objectContaining({
data: { threadId: THREAD_A },
data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
title: "Pushing...",
type: "loading",
}),
@@ -238,24 +307,27 @@ describe("GitActionsControl thread-scoped progress toast", () => {
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
title: "Pushing...",
type: "loading",
}),
);
const switchThreadButton = findButtonByText("Switch thread");
expect(switchThreadButton, 'Unable to find button containing "Switch thread"').toBeTruthy();
if (!(switchThreadButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Switch thread"');
const switchEnvironmentButton = findButtonByText("Switch environment");
expect(
switchEnvironmentButton,
'Unable to find button containing "Switch environment"',
).toBeTruthy();
if (!(switchEnvironmentButton instanceof HTMLButtonElement)) {
throw new Error('Unable to find button containing "Switch environment"');
}
switchThreadButton.click();
switchEnvironmentButton.click();
await vi.advanceTimersByTimeAsync(1_000);
expect(toastUpdateSpy).toHaveBeenLastCalledWith(
"toast-1",
expect.objectContaining({
data: { threadId: THREAD_A },
data: { threadRef: scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID) },
title: "Pushing...",
type: "loading",
}),
@@ -284,7 +356,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_ID, THREAD_A)}
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
/>,
{
container: host,
@@ -304,7 +376,7 @@ describe("GitActionsControl thread-scoped progress toast", () => {
await vi.advanceTimersByTimeAsync(1);
expect(refreshGitStatusSpy).toHaveBeenCalledTimes(1);
expect(refreshGitStatusSpy).toHaveBeenCalledWith({
environmentId: ENVIRONMENT_ID,
environmentId: ENVIRONMENT_A,
cwd: GIT_CWD,
});
} finally {
@@ -316,4 +388,42 @@ describe("GitActionsControl thread-scoped progress toast", () => {
host.remove();
}
});
it("syncs the live branch into the active draft thread when no server thread exists", async () => {
hasServerThreadRef.current = false;
activeDraftThreadRef.current = {
threadId: SHARED_THREAD_ID,
environmentId: ENVIRONMENT_A,
branch: null,
worktreePath: null,
};
const host = document.createElement("div");
document.body.append(host);
const screen = await render(
<GitActionsControl
gitCwd={GIT_CWD}
activeThreadRef={scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID)}
/>,
{
container: host,
},
);
try {
await Promise.resolve();
expect(setDraftThreadContextSpy).toHaveBeenCalledWith(
scopeThreadRef(ENVIRONMENT_A, SHARED_THREAD_ID),
{
branch: BRANCH_NAME,
worktreePath: null,
},
);
expect(setThreadBranchSpy).not.toHaveBeenCalled();
} finally {
await screen.unmount();
host.remove();
}
});
});
+44 -18
View File
@@ -49,6 +49,7 @@ import {
import { refreshGitStatus, useGitStatus } from "~/lib/gitStatusState";
import { newCommandId, randomUUID } from "~/lib/utils";
import { resolvePathLinkTarget } from "~/terminal-links";
import { useComposerDraftStore } from "~/composerDraftStore";
import { readEnvironmentApi } from "~/environmentApi";
import { readLocalApi } from "~/localApi";
import { useStore } from "~/store";
@@ -209,17 +210,20 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
}
export default function GitActionsControl({ gitCwd, activeThreadRef }: GitActionsControlProps) {
const activeThreadId = activeThreadRef?.threadId ?? null;
const activeEnvironmentId = activeThreadRef?.environmentId ?? null;
const threadToastData = useMemo(
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
[activeThreadId],
() => (activeThreadRef ? { threadRef: activeThreadRef } : undefined),
[activeThreadRef],
);
const activeServerThreadSelector = useMemo(
() => createThreadSelectorByRef(activeThreadRef),
[activeThreadRef],
);
const activeServerThread = useStore(activeServerThreadSelector);
const activeDraftThread = useComposerDraftStore((store) =>
activeThreadRef ? store.getDraftThreadByRef(activeThreadRef) : null,
);
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
const setThreadBranch = useStore((store) => store.setThreadBranch);
const queryClient = useQueryClient();
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
@@ -247,27 +251,49 @@ export default function GitActionsControl({ gitCwd, activeThreadRef }: GitAction
const persistThreadBranchSync = useCallback(
(branch: string | null) => {
if (!activeThreadId || !activeServerThread || activeServerThread.branch === branch) {
if (!activeThreadRef) {
return;
}
const worktreePath = activeServerThread.worktreePath;
const api = activeEnvironmentId ? readEnvironmentApi(activeEnvironmentId) : undefined;
if (api) {
void api.orchestration
.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadId,
branch,
worktreePath,
})
.catch(() => undefined);
if (activeServerThread) {
if (activeServerThread.branch === branch) {
return;
}
const worktreePath = activeServerThread.worktreePath;
const api = readEnvironmentApi(activeThreadRef.environmentId);
if (api) {
void api.orchestration
.dispatchCommand({
type: "thread.meta.update",
commandId: newCommandId(),
threadId: activeThreadRef.threadId,
branch,
worktreePath,
})
.catch(() => undefined);
}
setThreadBranch(activeThreadRef, branch, worktreePath);
return;
}
setThreadBranch(activeThreadId, branch, worktreePath);
if (!activeDraftThread || activeDraftThread.branch === branch) {
return;
}
setDraftThreadContext(activeThreadRef, {
branch,
worktreePath: activeDraftThread.worktreePath,
});
},
[activeEnvironmentId, activeServerThread, activeThreadId, setThreadBranch],
[
activeDraftThread,
activeServerThread,
activeThreadRef,
setDraftThreadContext,
setThreadBranch,
],
);
const syncThreadBranchAfterGitAction = useCallback(
@@ -21,7 +21,7 @@ import { render } from "vitest-browser-react";
import { useComposerDraftStore } from "../composerDraftStore";
import { __resetLocalApiForTests } from "../localApi";
import { AppAtomRegistryProvider } from "../rpc/atomRegistry";
import { getServerConfig } from "../rpc/serverState";
import { getServerConfig, getServerConfigUpdatedNotification } from "../rpc/serverState";
import { getWsConnectionStatus } from "../rpc/wsConnectionState";
import { getRouter } from "../router";
import { useStore } from "../store";
@@ -303,11 +303,6 @@ async function waitForNoToasts(): Promise<void> {
);
}
async function warmServerConfigUpdateStream(): Promise<void> {
sendServerConfigUpdatedPush([]);
await new Promise((resolve) => setTimeout(resolve, 50));
}
async function waitForInitialWsSubscriptions(): Promise<void> {
await vi.waitFor(
() => {
@@ -331,6 +326,33 @@ async function waitForServerConfigSnapshot(): Promise<void> {
);
}
async function waitForServerConfigStreamReady(): Promise<void> {
const previousNotificationId = getServerConfigUpdatedNotification()?.id ?? 0;
for (let attempt = 0; attempt < 20; attempt += 1) {
rpcHarness.emitStreamValue(WS_METHODS.subscribeServerConfig, {
version: 1,
type: "settingsUpdated",
payload: { settings: fixture.serverConfig.settings },
});
try {
await vi.waitFor(
() => {
const notification = getServerConfigUpdatedNotification();
expect(notification?.id).toBeGreaterThan(previousNotificationId);
expect(notification?.source).toBe("settingsUpdated");
},
{ timeout: 200, interval: 16 },
);
return;
} catch {
await new Promise((resolve) => setTimeout(resolve, 25));
}
}
throw new Error("Timed out waiting for the server config stream to deliver updates.");
}
async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
const host = document.createElement("div");
host.style.position = "fixed";
@@ -356,6 +378,7 @@ async function mountApp(): Promise<{ cleanup: () => Promise<void> }> {
await waitForInitialWsSubscriptions();
await waitForWsConnection();
await waitForServerConfigSnapshot();
await waitForServerConfigStreamReady();
await waitForNoToasts();
return {
@@ -429,8 +452,6 @@ describe("Keybindings update toast", () => {
const mounted = await mountApp();
try {
await warmServerConfigUpdateStream();
sendServerConfigUpdatedPush([]);
await waitForToast("Keybindings updated", 1);
+55 -23
View File
@@ -79,7 +79,7 @@ import {
import { useGitStatus } from "../lib/gitStatusState";
import { readLocalApi } from "../localApi";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useThreadActions } from "../hooks/useThreadActions";
import {
@@ -932,7 +932,7 @@ interface SidebarProjectItemProps {
isThreadListExpanded: boolean;
activeRouteThreadKey: string | null;
newThreadShortcutLabel: string | null;
handleNewThread: ReturnType<typeof useHandleNewThread>["handleNewThread"];
handleNewThread: ReturnType<typeof useNewThreadHandler>["handleNewThread"];
archiveThread: ReturnType<typeof useThreadActions>["archiveThread"];
deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
threadJumpLabelByKey: ReadonlyMap<string, string>;
@@ -2033,7 +2033,7 @@ interface SidebarProjectsContentProps {
handleProjectDragStart: (event: DragStartEvent) => void;
handleProjectDragEnd: (event: DragEndEvent) => void;
handleProjectDragCancel: (event: DragCancelEvent) => void;
handleNewThread: ReturnType<typeof useHandleNewThread>["handleNewThread"];
handleNewThread: ReturnType<typeof useNewThreadHandler>["handleNewThread"];
archiveThread: ReturnType<typeof useThreadActions>["archiveThread"];
deleteThread: ReturnType<typeof useThreadActions>["deleteThread"];
sortedProjects: readonly SidebarProjectSnapshot[];
@@ -2338,7 +2338,7 @@ export default function Sidebar() {
const sidebarProjectSortOrder = useSettings((s) => s.sidebarProjectSortOrder);
const defaultThreadEnvMode = useSettings((s) => s.defaultThreadEnvMode);
const { updateSettings } = useUpdateSettings();
const { handleNewThread } = useHandleNewThread();
const { handleNewThread } = useNewThreadHandler();
const { archiveThread, deleteThread } = useThreadActions();
const routeThreadRef = useParams({
strict: false,
@@ -2827,31 +2827,62 @@ export default function Sidebar() {
);
const [threadJumpLabelByKey, setThreadJumpLabelByKey] =
useState<ReadonlyMap<string, string>>(EMPTY_THREAD_JUMP_LABELS);
const threadJumpLabelsRef = useRef<ReadonlyMap<string, string>>(EMPTY_THREAD_JUMP_LABELS);
threadJumpLabelsRef.current = threadJumpLabelByKey;
const showThreadJumpHintsRef = useRef(showThreadJumpHints);
showThreadJumpHintsRef.current = showThreadJumpHints;
const visibleThreadJumpLabelByKey = showThreadJumpHints
? threadJumpLabelByKey
: EMPTY_THREAD_JUMP_LABELS;
const orderedSidebarThreadKeys = visibleSidebarThreadKeys;
useEffect(() => {
const clearThreadJumpHints = () => {
setThreadJumpLabelByKey((current) =>
current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS,
);
updateThreadJumpHintsVisibility(false);
};
const shouldIgnoreThreadJumpHintUpdate = (event: globalThis.KeyboardEvent) =>
!event.metaKey &&
!event.ctrlKey &&
!event.altKey &&
!event.shiftKey &&
event.key !== "Meta" &&
event.key !== "Control" &&
event.key !== "Alt" &&
event.key !== "Shift" &&
!showThreadJumpHintsRef.current &&
threadJumpLabelsRef.current === EMPTY_THREAD_JUMP_LABELS;
const onWindowKeyDown = (event: globalThis.KeyboardEvent) => {
if (shouldIgnoreThreadJumpHintUpdate(event)) {
return;
}
const shortcutContext = getCurrentSidebarShortcutContext();
const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, {
platform,
context: shortcutContext,
});
setThreadJumpLabelByKey((current) => {
if (!shouldShowHints) {
return current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS;
if (!shouldShowHints) {
if (
showThreadJumpHintsRef.current ||
threadJumpLabelsRef.current !== EMPTY_THREAD_JUMP_LABELS
) {
clearThreadJumpHints();
}
const nextLabelMap = buildThreadJumpLabelMap({
keybindings,
platform,
terminalOpen: shortcutContext.terminalOpen,
threadJumpCommandByKey,
} else {
setThreadJumpLabelByKey((current) => {
const nextLabelMap = buildThreadJumpLabelMap({
keybindings,
platform,
terminalOpen: shortcutContext.terminalOpen,
threadJumpCommandByKey,
});
return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap;
});
return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap;
});
updateThreadJumpHintsVisibility(shouldShowHints);
updateThreadJumpHintsVisibility(true);
}
if (event.defaultPrevented || event.repeat) {
return;
@@ -2902,15 +2933,19 @@ export default function Sidebar() {
};
const onWindowKeyUp = (event: globalThis.KeyboardEvent) => {
if (shouldIgnoreThreadJumpHintUpdate(event)) {
return;
}
const shortcutContext = getCurrentSidebarShortcutContext();
const shouldShowHints = shouldShowThreadJumpHints(event, keybindings, {
platform,
context: shortcutContext,
});
if (!shouldShowHints) {
clearThreadJumpHints();
return;
}
setThreadJumpLabelByKey((current) => {
if (!shouldShowHints) {
return current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS;
}
const nextLabelMap = buildThreadJumpLabelMap({
keybindings,
platform,
@@ -2919,14 +2954,11 @@ export default function Sidebar() {
});
return threadJumpLabelMapsEqual(current, nextLabelMap) ? current : nextLabelMap;
});
updateThreadJumpHintsVisibility(shouldShowHints);
updateThreadJumpHintsVisibility(true);
};
const onWindowBlur = () => {
setThreadJumpLabelByKey((current) =>
current === EMPTY_THREAD_JUMP_LABELS ? current : EMPTY_THREAD_JUMP_LABELS,
);
updateThreadJumpHintsVisibility(false);
clearThreadJumpHints();
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -113,6 +113,9 @@ vi.mock("~/environmentApi", () => ({
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: vi.fn(() => {
throw new Error("ensureLocalApi not implemented in browser test");
}),
readLocalApi: readLocalApiMock,
}));
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { WsConnectionStatus } from "../rpc/wsConnectionState";
import { shouldAutoReconnect } from "./WebSocketConnectionSurface";
import { shouldAutoReconnect, shouldRestartStalledReconnect } from "./WebSocketConnectionSurface";
function makeStatus(overrides: Partial<WsConnectionStatus> = {}): WsConnectionStatus {
return {
@@ -80,4 +80,34 @@ describe("WebSocketConnectionSurface.logic", () => {
),
).toBe(true);
});
it("restarts a stalled reconnect window after the scheduled retry time passes", () => {
expect(
shouldRestartStalledReconnect(
makeStatus({
hasConnected: true,
nextRetryAt: "2026-04-03T20:00:01.000Z",
online: true,
phase: "disconnected",
reconnectAttemptCount: 3,
reconnectPhase: "waiting",
}),
"2026-04-03T20:00:01.000Z",
),
).toBe(true);
expect(
shouldRestartStalledReconnect(
makeStatus({
hasConnected: true,
nextRetryAt: "2026-04-03T20:00:01.000Z",
online: true,
phase: "disconnected",
reconnectAttemptCount: 3,
reconnectPhase: "attempting",
}),
"2026-04-03T20:00:01.000Z",
),
).toBe(false);
});
});
@@ -2,7 +2,6 @@ import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from "rea
import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
import {
exhaustWsReconnectIfStillWaiting,
getWsConnectionStatus,
getWsConnectionUiState,
setBrowserOnlineStatus,
@@ -105,6 +104,18 @@ export function shouldAutoReconnect(
);
}
export function shouldRestartStalledReconnect(
status: WsConnectionStatus,
expectedNextRetryAt: string,
): boolean {
return (
status.reconnectPhase === "waiting" &&
status.nextRetryAt === expectedNextRetryAt &&
status.online &&
status.hasConnected
);
}
export function WebSocketConnectionCoordinator() {
const status = useWsConnectionStatus();
const [nowMs, setNowMs] = useState(() => Date.now());
@@ -205,7 +216,12 @@ export function WebSocketConnectionCoordinator() {
const nextRetryAt = status.nextRetryAt;
const timeoutMs = Math.max(0, new Date(nextRetryAt).getTime() - Date.now()) + 1_500;
const timeoutId = window.setTimeout(() => {
exhaustWsReconnectIfStillWaiting(nextRetryAt);
const currentStatus = getWsConnectionStatus();
if (!shouldRestartStalledReconnect(currentStatus, nextRetryAt)) {
return;
}
runReconnect(false);
}, timeoutMs);
return () => {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,120 @@
import { memo, useCallback, useEffect, useState } from "react";
import { ChevronLeftIcon, ChevronRightIcon, XIcon } from "lucide-react";
import { Button } from "../ui/button";
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
interface ExpandedImageDialogProps {
preview: ExpandedImagePreview;
onClose: () => void;
}
export const ExpandedImageDialog = memo(function ExpandedImageDialog({
preview: initialPreview,
onClose,
}: ExpandedImageDialogProps) {
const [preview, setPreview] = useState(initialPreview);
// Sync when the parent hands us a new preview reference.
useEffect(() => {
setPreview(initialPreview);
}, [initialPreview]);
const navigateImage = useCallback((direction: -1 | 1) => {
setPreview((existing) => {
if (existing.images.length <= 1) return existing;
const nextIndex =
(existing.index + direction + existing.images.length) % existing.images.length;
if (nextIndex === existing.index) return existing;
return { ...existing, index: nextIndex };
});
}, []);
useEffect(() => {
const onKeyDown = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onClose();
return;
}
if (preview.images.length <= 1) return;
if (event.key === "ArrowLeft") {
event.preventDefault();
event.stopPropagation();
navigateImage(-1);
return;
}
if (event.key !== "ArrowRight") return;
event.preventDefault();
event.stopPropagation();
navigateImage(1);
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [navigateImage, onClose, preview.images.length]);
const item = preview.images[preview.index];
if (!item) return null;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 px-4 py-6 [-webkit-app-region:no-drag]"
role="dialog"
aria-modal="true"
aria-label="Expanded image preview"
>
<button
type="button"
className="absolute inset-0 z-0 cursor-zoom-out"
aria-label="Close image preview"
onClick={onClose}
/>
{preview.images.length > 1 && (
<Button
type="button"
size="icon"
variant="ghost"
className="absolute left-2 top-1/2 z-20 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:left-6"
aria-label="Previous image"
onClick={() => navigateImage(-1)}
>
<ChevronLeftIcon className="size-5" />
</Button>
)}
<div className="relative isolate z-10 max-h-[92vh] max-w-[92vw]">
<Button
type="button"
size="icon-xs"
variant="ghost"
className="absolute right-2 top-2"
onClick={onClose}
aria-label="Close image preview"
>
<XIcon />
</Button>
<img
src={item.src}
alt={item.name}
className="max-h-[86vh] max-w-[92vw] select-none rounded-lg border border-border/70 bg-background object-contain shadow-2xl"
draggable={false}
/>
<p className="mt-2 max-w-[92vw] truncate text-center text-xs text-muted-foreground/80">
{item.name}
{preview.images.length > 1 ? ` (${preview.index + 1}/${preview.images.length})` : ""}
</p>
</div>
{preview.images.length > 1 && (
<Button
type="button"
size="icon"
variant="ghost"
className="absolute right-2 top-1/2 z-20 -translate-y-1/2 text-white/90 hover:bg-white/10 hover:text-white sm:right-6"
aria-label="Next image"
onClick={() => navigateImage(1)}
>
<ChevronRightIcon className="size-5" />
</Button>
)}
</div>
);
});
@@ -428,7 +428,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
</Button>
)}
</div>
<p className="text-right text-[10px] text-muted-foreground/30">
<p className="text-right text-xs text-muted-foreground/50">
{formatTimestamp(row.message.createdAt, timestampFormat)}
</p>
</div>
@@ -515,7 +515,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
</div>
);
})()}
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
<p className="mt-1.5 text-xs text-muted-foreground/50">
{formatMessageMeta(
row.message.createdAt,
row.message.streaming
@@ -703,7 +703,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
{inlineNodes}
</div>
);
@@ -731,7 +731,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
<div className="wrap-break-word whitespace-pre-wrap font-mono text-sm leading-relaxed text-foreground">
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
{inlineNodes}
</div>
);
@@ -742,9 +742,9 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
{props.text}
</pre>
</div>
);
});
@@ -871,7 +871,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
<div className="max-w-full">
<p
className={cn(
"truncate text-[11px] leading-5",
"truncate text-xs leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
@@ -282,6 +282,13 @@ const createDesktopBridgeStub = (overrides?: {
wsBaseUrl: "ws://127.0.0.1:3773",
bootstrapToken: "desktop-bootstrap-token",
}),
getClientSettings: vi.fn().mockResolvedValue(null),
setClientSettings: vi.fn().mockResolvedValue(undefined),
getSavedEnvironmentRegistry: vi.fn().mockResolvedValue([]),
setSavedEnvironmentRegistry: vi.fn().mockResolvedValue(undefined),
getSavedEnvironmentSecret: vi.fn().mockResolvedValue(null),
setSavedEnvironmentSecret: vi.fn().mockResolvedValue(true),
removeSavedEnvironmentSecret: vi.fn().mockResolvedValue(undefined),
getServerExposureState: vi.fn().mockResolvedValue(
overrides?.serverExposureState ?? {
mode: "local-only",
@@ -361,8 +368,8 @@ describe("GeneralSettingsPanel observability", () => {
browser: "Chrome",
ipAddress: "127.0.0.1",
},
issuedAt: "2026-04-07T00:00:00.000Z",
expiresAt: "2026-05-07T00:00:00.000Z",
issuedAt: "2036-04-07T00:00:00.000Z",
expiresAt: "2036-05-07T00:00:00.000Z",
connected: true,
current: true,
}),
@@ -377,7 +384,7 @@ describe("GeneralSettingsPanel observability", () => {
auth: createBaseServerConfig().auth,
role: "owner",
sessionMethod: "browser-session-cookie",
expiresAt: "2026-05-07T00:00:00.000Z",
expiresAt: "2036-05-07T00:00:00.000Z",
}),
{
status: 200,
@@ -458,8 +465,8 @@ describe("GeneralSettingsPanel observability", () => {
browser: "Electron",
ipAddress: "127.0.0.1",
},
issuedAt: "2026-04-07T00:00:00.000Z",
expiresAt: "2026-05-07T00:00:00.000Z",
issuedAt: "2036-04-07T00:00:00.000Z",
expiresAt: "2036-05-07T00:00:00.000Z",
connected: true,
current: true,
}),
@@ -481,8 +488,8 @@ describe("GeneralSettingsPanel observability", () => {
role: "client",
subject: "one-time-token",
label: "Julius iPhone",
createdAt: "2026-04-07T00:00:00.000Z",
expiresAt: "2026-04-10T00:05:00.000Z",
createdAt: "2036-04-07T00:00:00.000Z",
expiresAt: "2036-04-10T00:05:00.000Z",
}),
];
clientSessions = [
@@ -499,8 +506,8 @@ describe("GeneralSettingsPanel observability", () => {
browser: "Safari",
ipAddress: "192.168.1.88",
},
issuedAt: "2026-04-07T00:01:00.000Z",
expiresAt: "2026-05-07T00:01:00.000Z",
issuedAt: "2036-04-07T00:01:00.000Z",
expiresAt: "2036-05-07T00:01:00.000Z",
connected: false,
current: false,
}),
@@ -514,7 +521,7 @@ describe("GeneralSettingsPanel observability", () => {
id: "pairing-link-1",
credential: "pairing-token",
label: "Julius iPhone",
expiresAt: "2026-04-10T00:05:00.000Z",
expiresAt: "2036-04-10T00:05:00.000Z",
}),
{
status: 200,
@@ -547,7 +554,7 @@ describe("GeneralSettingsPanel observability", () => {
.element(page.getByText("Client · Mobile · iOS · Safari · 192.168.1.88"))
.toBeInTheDocument();
await expect
.element(page.getByRole("button", { name: "Copy", exact: true }))
.element(page.getByRole("button", { name: /^(Copy|Show link)$/ }))
.toBeInTheDocument();
await expect.element(page.getByText("Revoke others")).toBeInTheDocument();
});
@@ -572,8 +579,8 @@ describe("GeneralSettingsPanel observability", () => {
os: "macOS",
browser: "Electron",
},
issuedAt: "2026-04-05T00:00:00.000Z",
expiresAt: "2026-05-05T00:00:00.000Z",
issuedAt: "2036-04-05T00:00:00.000Z",
expiresAt: "2036-05-05T00:00:00.000Z",
connected: true,
current: true,
}),
@@ -589,8 +596,8 @@ describe("GeneralSettingsPanel observability", () => {
browser: "Safari",
ipAddress: "192.168.1.88",
},
issuedAt: "2026-04-05T00:01:00.000Z",
expiresAt: "2026-05-05T00:01:00.000Z",
issuedAt: "2036-04-05T00:01:00.000Z",
expiresAt: "2036-05-05T00:01:00.000Z",
connected: false,
current: false,
}),
+1 -1
View File
@@ -1,5 +1,5 @@
import { memo } from "react";
import { QrCode } from "../../lib/vendor/qrcodegen";
import { QrCode } from "@t3tools/shared/qrCode";
type QRCodeSvgProps = {
value: string;
+52 -1
View File
@@ -1,5 +1,10 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { assert, describe, it } from "vitest";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
import {
buildVisibleToastLayout,
shouldHideCollapsedToastContent,
shouldRenderThreadScopedToast,
} from "./toast.logic";
describe("shouldHideCollapsedToastContent", () => {
it("keeps a single visible toast readable", () => {
@@ -61,3 +66,49 @@ describe("buildVisibleToastLayout", () => {
);
});
});
describe("shouldRenderThreadScopedToast", () => {
const activeThreadRef = {
environmentId: "environment-a",
threadId: "thread-1",
} as ScopedThreadRef;
it("renders a toast scoped to the active thread ref", () => {
assert.equal(
shouldRenderThreadScopedToast(
{
threadRef: activeThreadRef,
},
activeThreadRef,
),
true,
);
});
it("hides a scoped toast when the environment differs", () => {
assert.equal(
shouldRenderThreadScopedToast(
{
threadRef: {
environmentId: "environment-b",
threadId: "thread-1",
} as ScopedThreadRef,
},
activeThreadRef,
),
false,
);
});
it("keeps legacy thread-id scoped toasts working", () => {
assert.equal(
shouldRenderThreadScopedToast(
{
threadId: "thread-1" as never,
},
activeThreadRef,
),
true,
);
});
});
+27
View File
@@ -1,3 +1,5 @@
import type { ScopedThreadRef, ThreadId } from "@t3tools/contracts";
export function shouldHideCollapsedToastContent(
visibleToastIndex: number,
visibleToastCount: number,
@@ -44,3 +46,28 @@ export function buildVisibleToastLayout<TToast extends object>(
function normalizeToastHeight(height: number | null | undefined): number {
return typeof height === "number" && Number.isFinite(height) && height > 0 ? height : 0;
}
export function shouldRenderThreadScopedToast(
data:
| {
threadRef?: ScopedThreadRef | null;
threadId?: ThreadId | null;
}
| undefined,
activeThreadRef: ScopedThreadRef | null,
): boolean {
if (data?.threadRef) {
return (
activeThreadRef !== null &&
data.threadRef.environmentId === activeThreadRef.environmentId &&
data.threadRef.threadId === activeThreadRef.threadId
);
}
const toastThreadId = data?.threadId;
if (!toastThreadId) {
return true;
}
return activeThreadRef?.threadId === toastThreadId;
}
+33 -20
View File
@@ -1,9 +1,9 @@
"use client";
import { Toast } from "@base-ui/react/toast";
import { useEffect, type CSSProperties } from "react";
import { useEffect, useMemo, type CSSProperties } from "react";
import { useParams } from "@tanstack/react-router";
import { ThreadId } from "@t3tools/contracts";
import { type ScopedThreadRef, type ThreadId } from "@t3tools/contracts";
import {
CheckIcon,
CircleAlertIcon,
@@ -16,10 +16,17 @@ import {
import { cn } from "~/lib/utils";
import { buttonVariants } from "~/components/ui/button";
import { useComposerDraftStore } from "~/composerDraftStore";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
import { resolveThreadRouteTarget } from "~/threadRoutes";
import {
buildVisibleToastLayout,
shouldHideCollapsedToastContent,
shouldRenderThreadScopedToast,
} from "./toast.logic";
export type ThreadToastData = {
threadRef?: ScopedThreadRef | null;
threadId?: ThreadId | null;
tooltipStyle?: boolean;
dismissAfterVisibleMs?: number;
@@ -70,21 +77,27 @@ interface ToastProviderProps extends Toast.Provider.Props {
position?: ToastPosition;
}
function shouldRenderForActiveThread(
data: ThreadToastData | undefined,
activeThreadId: ThreadId | null,
): boolean {
const toastThreadId = data?.threadId;
if (!toastThreadId) return true;
return toastThreadId === activeThreadId;
}
function useActiveThreadIdFromRoute(): ThreadId | null {
return useParams({
function useActiveThreadRefFromRoute(): ScopedThreadRef | null {
const routeTarget = useParams({
strict: false,
select: (params) =>
typeof params.threadId === "string" ? ThreadId.makeUnsafe(params.threadId) : null,
select: (params) => resolveThreadRouteTarget(params),
});
const activeDraftSession = useComposerDraftStore((store) =>
routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null,
);
return useMemo(() => {
if (routeTarget?.kind === "server") {
return routeTarget.threadRef;
}
if (routeTarget?.kind === "draft" && activeDraftSession) {
return {
environmentId: activeDraftSession.environmentId,
threadId: activeDraftSession.threadId,
};
}
return null;
}, [activeDraftSession, routeTarget]);
}
function ThreadToastVisibleAutoDismiss({
@@ -176,10 +189,10 @@ function ToastProvider({ children, position = "top-right", ...props }: ToastProv
function Toasts({ position = "top-right" }: { position: ToastPosition }) {
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = useActiveThreadIdFromRoute();
const activeThreadRef = useActiveThreadRefFromRoute();
const isTop = position.startsWith("top");
const visibleToasts = toasts.filter((toast) =>
shouldRenderForActiveThread(toast.data, activeThreadId),
shouldRenderThreadScopedToast(toast.data, activeThreadRef),
);
const visibleToastLayout = buildVisibleToastLayout(visibleToasts);
@@ -350,13 +363,13 @@ function AnchoredToastProvider({ children, ...props }: Toast.Provider.Props) {
function AnchoredToasts() {
const { toasts } = Toast.useToastManager<ThreadToastData>();
const activeThreadId = useActiveThreadIdFromRoute();
const activeThreadRef = useActiveThreadRefFromRoute();
return (
<Toast.Portal data-slot="toast-portal-anchored">
<Toast.Viewport className="outline-none" data-slot="toast-viewport-anchored">
{toasts
.filter((toast) => shouldRenderForActiveThread(toast.data, activeThreadId))
.filter((toast) => shouldRenderThreadScopedToast(toast.data, activeThreadRef))
.map((toast) => {
const Icon = toast.type ? TOAST_ICONS[toast.type as keyof typeof TOAST_ICONS] : null;
const tooltipStyle = toast.data?.tooltipStyle ?? false;
+59 -1
View File
@@ -1,6 +1,9 @@
import { describe, expect, it } from "vitest";
import { splitPromptIntoComposerSegments } from "./composer-editor-mentions";
import {
selectionTouchesMentionBoundary,
splitPromptIntoComposerSegments,
} from "./composer-editor-mentions";
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
describe("splitPromptIntoComposerSegments", () => {
@@ -38,4 +41,59 @@ describe("splitPromptIntoComposerSegments", () => {
{ type: "text", text: " please" },
]);
});
it("preserves consecutive terminal context placeholders without dropping positions", () => {
expect(
splitPromptIntoComposerSegments(
`${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}tail`,
),
).toEqual([
{ type: "terminal-context", context: null },
{ type: "terminal-context", context: null },
{ type: "text", text: "tail" },
]);
});
});
describe("selectionTouchesMentionBoundary", () => {
it("returns true when selection includes the whitespace after a mention", () => {
expect(
selectionTouchesMentionBoundary(
"hi @package.json there",
"hi @package.json".length,
"hi @package.json there".length,
),
).toBe(true);
});
it("returns true when selection includes the whitespace before a mention", () => {
expect(
selectionTouchesMentionBoundary(
"hi there @package.json later",
"hi there".length,
"hi there ".length,
),
).toBe(true);
});
it("returns false when selection starts after the mention boundary whitespace", () => {
expect(
selectionTouchesMentionBoundary(
"hi @package.json there",
"hi @package.json ".length,
"hi @package.json there".length,
),
).toBe(false);
});
it("returns true when selection includes whitespace after a mention following a terminal placeholder", () => {
const prompt = `${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}@AGENTS.md there`;
expect(
selectionTouchesMentionBoundary(
prompt,
`${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}@AGENTS.md`.length,
prompt.length,
),
).toBe(true);
});
});
+125 -14
View File
@@ -19,6 +19,10 @@ export type ComposerPromptSegment =
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
function rangeIncludesIndex(start: number, end: number, index: number): boolean {
return start <= index && index < end;
}
function pushTextSegment(segments: ComposerPromptSegment[], text: string): void {
if (!text) return;
const last = segments[segments.length - 1];
@@ -29,6 +33,84 @@ function pushTextSegment(segments: ComposerPromptSegment[], text: string): void
segments.push({ type: "text", text });
}
function forEachPromptSegmentSlice(
prompt: string,
visitor: (
slice:
| {
type: "text";
text: string;
promptOffset: number;
}
| {
type: "terminal-context";
promptOffset: number;
},
) => boolean | void,
): boolean {
let textCursor = 0;
for (let index = 0; index < prompt.length; index += 1) {
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
continue;
}
if (
index > textCursor &&
visitor({
type: "text",
text: prompt.slice(textCursor, index),
promptOffset: textCursor,
}) === true
) {
return true;
}
if (visitor({ type: "terminal-context", promptOffset: index }) === true) {
return true;
}
textCursor = index + 1;
}
if (
textCursor < prompt.length &&
visitor({
type: "text",
text: prompt.slice(textCursor),
promptOffset: textCursor,
}) === true
) {
return true;
}
return false;
}
function forEachPromptTextSlice(
prompt: string,
visitor: (text: string, promptOffset: number) => boolean | void,
): boolean {
return forEachPromptSegmentSlice(prompt, (slice) => {
if (slice.type !== "text") {
return false;
}
return visitor(slice.text, slice.promptOffset);
});
}
function forEachMentionMatch(
prompt: string,
visitor: (match: RegExpMatchArray, promptOffset: number) => boolean | void,
): boolean {
return forEachPromptTextSlice(prompt, (text, promptOffset) => {
for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
if (visitor(match, promptOffset) === true) {
return true;
}
}
return false;
});
}
function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
const segments: ComposerPromptSegment[] = [];
if (!text) {
@@ -64,6 +146,43 @@ function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegmen
return segments;
}
export function selectionTouchesMentionBoundary(
prompt: string,
start: number,
end: number,
): boolean {
if (!prompt || start >= end) {
return false;
}
return forEachMentionMatch(prompt, (match, promptOffset) => {
const fullMatch = match[0];
const prefix = match[1] ?? "";
const matchIndex = match.index ?? 0;
const mentionStart = promptOffset + matchIndex + prefix.length;
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
const beforeMentionIndex = mentionStart - 1;
const afterMentionIndex = mentionEnd;
if (
beforeMentionIndex >= 0 &&
/\s/.test(prompt[beforeMentionIndex] ?? "") &&
rangeIncludesIndex(start, end, beforeMentionIndex)
) {
return true;
}
if (
afterMentionIndex < prompt.length &&
/\s/.test(prompt[afterMentionIndex] ?? "") &&
rangeIncludesIndex(start, end, afterMentionIndex)
) {
return true;
}
return false;
});
}
export function splitPromptIntoComposerSegments(
prompt: string,
terminalContexts: ReadonlyArray<TerminalContextDraft> = [],
@@ -73,28 +192,20 @@ export function splitPromptIntoComposerSegments(
}
const segments: ComposerPromptSegment[] = [];
let textCursor = 0;
let terminalContextIndex = 0;
for (let index = 0; index < prompt.length; index += 1) {
if (prompt[index] !== INLINE_TERMINAL_CONTEXT_PLACEHOLDER) {
continue;
forEachPromptSegmentSlice(prompt, (slice) => {
if (slice.type === "text") {
segments.push(...splitPromptTextIntoComposerSegments(slice.text));
return false;
}
if (index > textCursor) {
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor, index)));
}
segments.push({
type: "terminal-context",
context: terminalContexts[terminalContextIndex] ?? null,
});
terminalContextIndex += 1;
textCursor = index + 1;
}
if (textCursor < prompt.length) {
segments.push(...splitPromptTextIntoComposerSegments(prompt.slice(textCursor)));
}
return false;
});
return segments;
}
+29 -1
View File
@@ -38,6 +38,7 @@ import {
} from "./lib/terminalContext";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { useShallow } from "zustand/react/shallow";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
@@ -378,6 +379,11 @@ export interface EffectiveComposerModelState {
modelOptions: ProviderModelOptions | null;
}
interface ComposerDraftModelState {
activeProvider: ProviderKind | null;
modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;
}
function providerModelOptionsFromSelection(
modelSelection: ModelSelection | null | undefined,
): ProviderModelOptions | null {
@@ -420,6 +426,10 @@ Object.freeze(EMPTY_IDS);
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderKind, ModelSelection>> =
Object.freeze({});
const EMPTY_COMPOSER_DRAFT_MODEL_STATE = Object.freeze<ComposerDraftModelState>({
activeProvider: null,
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
});
const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
prompt: "",
@@ -2764,6 +2774,22 @@ export function useComposerThreadDraft(threadRef: ComposerThreadTarget): Compose
});
}
export function useComposerDraftModelState(
threadRef: ComposerThreadTarget,
): ComposerDraftModelState {
return useComposerDraftStore(
useShallow((state) => {
const draft = getComposerDraftState(state, threadRef);
return draft
? {
activeProvider: draft.activeProvider,
modelSelectionByProvider: draft.modelSelectionByProvider,
}
: EMPTY_COMPOSER_DRAFT_MODEL_STATE;
}),
);
}
export function useEffectiveComposerModelState(input: {
threadRef?: ComposerThreadTarget;
draftId?: DraftId;
@@ -2773,7 +2799,9 @@ export function useEffectiveComposerModelState(input: {
projectModelSelection: ModelSelection | null | undefined;
settings: UnifiedSettings;
}): EffectiveComposerModelState {
const draft = useComposerThreadDraft(input.threadRef ?? input.draftId ?? DraftId.makeUnsafe(""));
const draft = useComposerDraftModelState(
input.threadRef ?? input.draftId ?? DraftId.makeUnsafe(""),
);
return useMemo(
() =>
@@ -110,6 +110,32 @@ describe("environmentBootstrap", () => {
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
});
it("derives the websocket url when only VITE_HTTP_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_HTTP_URL", "https://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("derives the http url when only VITE_WS_URL is configured", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
vi.stubEnv("VITE_WS_URL", "wss://remote.example.com");
await expect(resolveInitialPrimaryEnvironmentDescriptor()).resolves.toEqual(BASE_ENVIRONMENT);
expect(fetchMock).toHaveBeenCalledWith("https://remote.example.com/.well-known/t3/environment");
expect(getPrimaryKnownEnvironment()?.target).toEqual({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
});
});
it("uses the current origin as the descriptor base for local dev environments", async () => {
const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(BASE_ENVIRONMENT));
vi.stubGlobal("fetch", fetchMock);
+23 -7
View File
@@ -16,6 +16,15 @@ function normalizeBaseUrl(rawValue: string): string {
return new URL(rawValue, window.location.origin).toString();
}
function swapBaseUrlProtocol(
rawValue: string,
nextProtocol: "http:" | "https:" | "ws:" | "wss:",
): string {
const url = new URL(normalizeBaseUrl(rawValue));
url.protocol = nextProtocol;
return url.toString();
}
function normalizeHostname(hostname: string): string {
return hostname
.trim()
@@ -54,22 +63,29 @@ function resolveHttpRequestBaseUrl(httpBaseUrl: string): string {
}
function resolveConfiguredPrimaryTarget(): PrimaryEnvironmentTarget | null {
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim();
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim();
const configuredHttpBaseUrl = import.meta.env.VITE_HTTP_URL?.trim() || undefined;
const configuredWsBaseUrl = import.meta.env.VITE_WS_URL?.trim() || undefined;
if (!configuredHttpBaseUrl && !configuredWsBaseUrl) {
return null;
}
if (!configuredHttpBaseUrl || !configuredWsBaseUrl) {
throw new Error("Configured primary environments require both VITE_HTTP_URL and VITE_WS_URL.");
}
const resolvedHttpBaseUrl =
configuredHttpBaseUrl ??
(configuredWsBaseUrl?.startsWith("wss:")
? swapBaseUrlProtocol(configuredWsBaseUrl, "https:")
: swapBaseUrlProtocol(configuredWsBaseUrl!, "http:"));
const resolvedWsBaseUrl =
configuredWsBaseUrl ??
(configuredHttpBaseUrl?.startsWith("https:")
? swapBaseUrlProtocol(configuredHttpBaseUrl, "wss:")
: swapBaseUrlProtocol(configuredHttpBaseUrl!, "ws:"));
return {
source: "configured",
target: {
httpBaseUrl: normalizeBaseUrl(configuredHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(configuredWsBaseUrl),
httpBaseUrl: normalizeBaseUrl(resolvedHttpBaseUrl),
wsBaseUrl: normalizeBaseUrl(resolvedWsBaseUrl),
},
};
}
@@ -1,17 +1,43 @@
import { EnvironmentId } from "@t3tools/contracts";
import { afterEach, describe, expect, it } from "vitest";
import {
EnvironmentId,
type LocalApi,
type PersistedSavedEnvironmentRecord,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
resetSavedEnvironmentRegistryStoreForTests,
resetSavedEnvironmentRuntimeStoreForTests,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
} from "./catalog";
describe("environment runtime catalog stores", () => {
afterEach(() => {
beforeEach(async () => {
vi.stubGlobal("window", {
nativeApi: {
persistence: {
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
},
} satisfies Pick<LocalApi, "persistence">,
});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
});
afterEach(async () => {
resetSavedEnvironmentRegistryStoreForTests();
resetSavedEnvironmentRuntimeStoreForTests();
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
vi.unstubAllGlobals();
});
it("resets the saved environment registry store state", () => {
@@ -22,7 +48,6 @@ describe("environment runtime catalog stores", () => {
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
bearerToken: "token",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
});
@@ -48,4 +73,69 @@ describe("environment runtime catalog stores", () => {
expect(useSavedEnvironmentRuntimeStore.getState().byId).toEqual({});
});
it("does not throw when local api lookup fails during registry persistence", async () => {
vi.unstubAllGlobals();
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
expect(() =>
useSavedEnvironmentRegistryStore.getState().upsert({
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
}),
).not.toThrow();
expect(errorSpy).toHaveBeenCalledWith("[SAVED_ENVIRONMENTS] persist failed", expect.any(Error));
});
it("does not let stale hydration overwrite records added while hydration is in flight", async () => {
let resolveRegistryRead: () => void = () => {
throw new Error("Registry read resolver was not initialized.");
};
vi.stubGlobal("window", {
nativeApi: {
persistence: {
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: () =>
new Promise<readonly PersistedSavedEnvironmentRecord[]>((resolve) => {
resolveRegistryRead = () => resolve([]);
}),
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
},
} satisfies Pick<LocalApi, "persistence">,
});
const { __resetLocalApiForTests } = await import("../../localApi");
await __resetLocalApiForTests();
const hydrationPromise = waitForSavedEnvironmentRegistryHydration();
const environmentId = EnvironmentId.makeUnsafe("environment-1");
const record = {
environmentId,
label: "Remote environment",
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
} as const;
useSavedEnvironmentRegistryStore.getState().upsert(record);
resolveRegistryRead();
await hydrationPromise;
expect(useSavedEnvironmentRegistryStore.getState().byId[environmentId]).toEqual(record);
});
});
+158 -68
View File
@@ -3,22 +3,19 @@ import type {
AuthSessionRole,
EnvironmentId,
ExecutionEnvironmentDescriptor,
PersistedSavedEnvironmentRecord,
ServerConfig,
} from "@t3tools/contracts";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { resolveStorage } from "../../lib/storage";
import { ensureLocalApi } from "../../localApi";
import { getPrimaryKnownEnvironment } from "../primary";
const SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY = "t3code:saved-environment-registry:v1";
export interface SavedEnvironmentRecord {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly wsBaseUrl: string;
readonly httpBaseUrl: string;
readonly bearerToken: string;
readonly createdAt: string;
readonly lastConnectedAt: string | null;
}
@@ -34,62 +31,133 @@ interface SavedEnvironmentRegistryStore extends SavedEnvironmentRegistryState {
readonly reset: () => void;
}
function createSavedEnvironmentRegistryStorage() {
return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined);
let savedEnvironmentRegistryHydrated = false;
let savedEnvironmentRegistryHydrationPromise: Promise<void> | null = null;
function toPersistedSavedEnvironmentRecord(
record: SavedEnvironmentRecord,
): PersistedSavedEnvironmentRecord {
return {
environmentId: record.environmentId,
label: record.label,
httpBaseUrl: record.httpBaseUrl,
wsBaseUrl: record.wsBaseUrl,
createdAt: record.createdAt,
lastConnectedAt: record.lastConnectedAt,
};
}
export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()(
persist(
(set) => ({
byId: {},
upsert: (record) =>
set((state) => ({
byId: {
...state.byId,
[record.environmentId]: record,
},
})),
remove: (environmentId) =>
set((state) => {
const { [environmentId]: _removed, ...remaining } = state.byId;
return {
byId: remaining,
};
}),
markConnected: (environmentId, connectedAt) =>
set((state) => {
const existing = state.byId[environmentId];
if (!existing) {
return state;
}
return {
byId: {
...state.byId,
[environmentId]: {
...existing,
lastConnectedAt: connectedAt,
},
},
};
}),
reset: () =>
set({
byId: {},
}),
}),
{
name: SAVED_ENVIRONMENT_REGISTRY_STORAGE_KEY,
version: 1,
storage: createJSONStorage(createSavedEnvironmentRegistryStorage),
partialize: (state) => ({
byId: state.byId,
}),
function valuesOfSavedEnvironmentRegistry(
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
): ReadonlyArray<SavedEnvironmentRecord> {
return Object.values(byId) as ReadonlyArray<SavedEnvironmentRecord>;
}
function persistSavedEnvironmentRegistryState(
byId: Record<EnvironmentId, SavedEnvironmentRecord>,
): void {
try {
void ensureLocalApi()
.persistence.setSavedEnvironmentRegistry(
valuesOfSavedEnvironmentRegistry(byId).map((record) =>
toPersistedSavedEnvironmentRecord(record),
),
)
.catch((error) => {
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
});
} catch (error) {
console.error("[SAVED_ENVIRONMENTS] persist failed", error);
}
}
function replaceSavedEnvironmentRegistryState(
records: ReadonlyArray<SavedEnvironmentRecord>,
): void {
const currentById = useSavedEnvironmentRegistryStore.getState().byId;
const hydratedById = Object.fromEntries(records.map((record) => [record.environmentId, record]));
useSavedEnvironmentRegistryStore.setState({
byId: {
...hydratedById,
...currentById,
},
),
);
});
}
async function hydrateSavedEnvironmentRegistry(): Promise<void> {
if (savedEnvironmentRegistryHydrated) {
return;
}
if (savedEnvironmentRegistryHydrationPromise) {
return savedEnvironmentRegistryHydrationPromise;
}
const nextHydration = (async () => {
try {
const persistedRecords = await ensureLocalApi().persistence.getSavedEnvironmentRegistry();
replaceSavedEnvironmentRegistryState(persistedRecords);
} catch (error) {
console.error("[SAVED_ENVIRONMENTS] hydrate failed", error);
} finally {
savedEnvironmentRegistryHydrated = true;
}
})();
const hydrationPromise = nextHydration.finally(() => {
if (savedEnvironmentRegistryHydrationPromise === hydrationPromise) {
savedEnvironmentRegistryHydrationPromise = null;
}
});
savedEnvironmentRegistryHydrationPromise = hydrationPromise;
return savedEnvironmentRegistryHydrationPromise;
}
export const useSavedEnvironmentRegistryStore = create<SavedEnvironmentRegistryStore>()((set) => ({
byId: {},
upsert: (record) =>
set((state) => {
const byId = {
...state.byId,
[record.environmentId]: record,
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
remove: (environmentId) =>
set((state) => {
const { [environmentId]: _removed, ...remaining } = state.byId;
persistSavedEnvironmentRegistryState(remaining);
return {
byId: remaining,
};
}),
markConnected: (environmentId, connectedAt) =>
set((state) => {
const existing = state.byId[environmentId];
if (!existing) {
return state;
}
const byId = {
...state.byId,
[environmentId]: {
...existing,
lastConnectedAt: connectedAt,
},
};
persistSavedEnvironmentRegistryState(byId);
return { byId };
}),
reset: () => {
persistSavedEnvironmentRegistryState({});
set({
byId: {},
});
},
}));
export function hasSavedEnvironmentRegistryHydrated(): boolean {
return useSavedEnvironmentRegistryStore.persist.hasHydrated();
return savedEnvironmentRegistryHydrated;
}
export function waitForSavedEnvironmentRegistryHydration(): Promise<void> {
@@ -97,17 +165,7 @@ export function waitForSavedEnvironmentRegistryHydration(): Promise<void> {
return Promise.resolve();
}
return new Promise((resolve) => {
const unsubscribe = useSavedEnvironmentRegistryStore.persist.onFinishHydration(() => {
unsubscribe();
resolve();
});
if (hasSavedEnvironmentRegistryHydrated()) {
unsubscribe();
resolve();
}
});
return hydrateSavedEnvironmentRegistry();
}
export function listSavedEnvironmentRecords(): ReadonlyArray<SavedEnvironmentRecord> {
@@ -150,7 +208,39 @@ export function resolveEnvironmentHttpUrl(input: {
}
export function resetSavedEnvironmentRegistryStoreForTests() {
useSavedEnvironmentRegistryStore.getState().reset();
savedEnvironmentRegistryHydrated = false;
savedEnvironmentRegistryHydrationPromise = null;
useSavedEnvironmentRegistryStore.setState({ byId: {} });
}
export async function persistSavedEnvironmentRecord(record: SavedEnvironmentRecord): Promise<void> {
const byId = {
...useSavedEnvironmentRegistryStore.getState().byId,
[record.environmentId]: record,
};
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
valuesOfSavedEnvironmentRegistry(byId).map((entry) => toPersistedSavedEnvironmentRecord(entry)),
);
}
export async function readSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<string | null> {
return ensureLocalApi().persistence.getSavedEnvironmentSecret(environmentId);
}
export async function writeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
bearerToken: string,
): Promise<boolean> {
return ensureLocalApi().persistence.setSavedEnvironmentSecret(environmentId, bearerToken);
}
export async function removeSavedEnvironmentBearerToken(
environmentId: EnvironmentId,
): Promise<void> {
await ensureLocalApi().persistence.removeSavedEnvironmentSecret(environmentId);
}
export type SavedEnvironmentConnectionState = "connecting" | "connected" | "disconnected" | "error";
@@ -6,10 +6,12 @@ import type { WsRpcClient } from "~/rpc/wsRpcClient";
function createTestClient(options?: {
readonly getSnapshot?: () => Promise<{ readonly snapshotSequence: number }>;
readonly replayEvents?: () => Promise<ReadonlyArray<any>>;
}) {
const lifecycleListeners = new Set<(event: any) => void>();
const configListeners = new Set<(event: any) => void>();
const terminalListeners = new Set<(event: any) => void>();
let domainResubscribe: (() => void) | undefined;
const getSnapshot = vi.fn(
options?.getSnapshot ??
@@ -20,6 +22,7 @@ function createTestClient(options?: {
threads: [],
}) as any),
);
const replayEvents = vi.fn(options?.replayEvents ?? (async () => []));
const client = {
dispose: vi.fn(async () => undefined),
@@ -49,8 +52,15 @@ function createTestClient(options?: {
dispatchCommand: vi.fn(async () => undefined),
getTurnDiff: vi.fn(async () => undefined),
getFullThreadDiff: vi.fn(async () => undefined),
replayEvents: vi.fn(async () => []),
onDomainEvent: () => () => undefined,
replayEvents,
onDomainEvent: vi.fn((_: (event: any) => void, options?: { onResubscribe?: () => void }) => {
domainResubscribe = options?.onResubscribe;
return () => {
if (domainResubscribe === options?.onResubscribe) {
domainResubscribe = undefined;
}
};
}),
},
terminal: {
open: vi.fn(async () => undefined),
@@ -90,6 +100,7 @@ function createTestClient(options?: {
return {
client,
getSnapshot,
replayEvents,
emitWelcome: (environmentId: EnvironmentId) => {
for (const listener of lifecycleListeners) {
listener({
@@ -114,6 +125,9 @@ function createTestClient(options?: {
});
}
},
triggerDomainResubscribe: () => {
domainResubscribe?.();
},
};
}
@@ -213,4 +227,121 @@ describe("createEnvironmentConnection", () => {
await connection.dispose();
});
it("retries replay recovery after transport disconnects during resubscribe", async () => {
const environmentId = EnvironmentId.makeUnsafe("env-1");
let replayAttempts = 0;
const applyEventBatch = vi.fn();
const { client, replayEvents, triggerDomainResubscribe } = createTestClient({
replayEvents: async () => {
replayAttempts += 1;
if (replayAttempts === 1) {
throw new Error("SocketCloseError: 1006");
}
return [
{
sequence: 2,
type: "thread.created",
payload: {},
},
];
},
});
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
id: "env-1",
label: "Remote env",
source: "manual",
target: {
httpBaseUrl: "http://example.test",
wsBaseUrl: "ws://example.test",
},
environmentId,
},
client,
applyEventBatch,
syncSnapshot: vi.fn(),
applyTerminalEvent: vi.fn(),
});
await Promise.resolve();
await Promise.resolve();
triggerDomainResubscribe();
await vi.waitFor(() => {
expect(replayEvents).toHaveBeenCalledTimes(2);
expect(applyEventBatch).toHaveBeenCalledWith(
[
expect.objectContaining({
sequence: 2,
}),
],
environmentId,
);
});
await connection.dispose();
});
it("swallows replay recovery failures triggered by resubscribe", async () => {
const environmentId = EnvironmentId.makeUnsafe("env-1");
const snapshotError = new Error("snapshot failed");
let snapshotCalls = 0;
const { client, triggerDomainResubscribe } = createTestClient({
getSnapshot: async () => {
snapshotCalls += 1;
if (snapshotCalls === 1) {
return {
snapshotSequence: 1,
projects: [],
threads: [],
} as any;
}
throw snapshotError;
},
replayEvents: async () => {
throw new Error("SocketCloseError: 1006");
},
});
const connection = createEnvironmentConnection({
kind: "saved",
knownEnvironment: {
id: "env-1",
label: "Remote env",
source: "manual",
target: {
httpBaseUrl: "http://example.test",
wsBaseUrl: "ws://example.test",
},
environmentId,
},
client,
applyEventBatch: vi.fn(),
syncSnapshot: vi.fn(),
applyTerminalEvent: vi.fn(),
});
await Promise.resolve();
await Promise.resolve();
const onUnhandledRejection = vi.fn();
process.on("unhandledRejection", onUnhandledRejection);
try {
triggerDomainResubscribe();
await new Promise((resolve) => setTimeout(resolve, 0));
await new Promise((resolve) => setTimeout(resolve, 0));
} finally {
process.off("unhandledRejection", onUnhandledRejection);
}
expect(onUnhandledRejection).not.toHaveBeenCalled();
await connection.dispose();
});
});
@@ -16,10 +16,13 @@ import {
createOrchestrationRecoveryCoordinator,
type ReplayRetryTracker,
} from "../../orchestrationRecovery";
import { isTransportConnectionErrorMessage } from "~/rpc/transportError";
import type { WsRpcClient } from "~/rpc/wsRpcClient";
const REPLAY_RECOVERY_RETRY_DELAY_MS = 100;
const MAX_NO_PROGRESS_REPLAY_RETRIES = 3;
const RECOVERY_TRANSPORT_RETRY_DELAY_MS = 250;
const MAX_RECOVERY_TRANSPORT_RETRIES = 20;
export interface EnvironmentConnection {
readonly kind: "primary" | "saved";
@@ -128,6 +131,34 @@ export function createEnvironmentConnection(
queueMicrotask(flushPendingDomainEvents);
};
const retryTransportRecoveryOperation = async <T>(operation: () => Promise<T>): Promise<T> => {
for (let attempt = 0; ; attempt += 1) {
try {
return await operation();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (
disposed ||
!isTransportConnectionErrorMessage(message) ||
attempt >= MAX_RECOVERY_TRANSPORT_RETRIES - 1
) {
throw error;
}
await new Promise<void>((resolve) => {
setTimeout(resolve, RECOVERY_TRANSPORT_RETRY_DELAY_MS);
});
if (disposed) {
throw error;
}
}
}
};
const scheduleReplayRecovery = (reason: "sequence-gap" | "resubscribe") => {
void runReplayRecovery(reason).catch(() => undefined);
};
const runReplayRecovery = async (reason: "sequence-gap" | "resubscribe"): Promise<void> => {
if (!recovery.beginReplayRecovery(reason)) {
return;
@@ -135,7 +166,9 @@ export function createEnvironmentConnection(
const fromSequenceExclusive = recovery.getState().latestSequence;
try {
const events = await input.client.orchestration.replayEvents({ fromSequenceExclusive });
const events = await retryTransportRecoveryOperation(() =>
input.client.orchestration.replayEvents({ fromSequenceExclusive }),
);
if (!disposed) {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length > 0) {
@@ -145,6 +178,9 @@ export function createEnvironmentConnection(
} catch {
replayRetryTracker = null;
recovery.failReplayRecovery();
if (disposed) {
return;
}
await snapshotBootstrap.ensureSnapshotRecovery("replay-failed");
return;
}
@@ -172,7 +208,7 @@ export function createEnvironmentConnection(
return;
}
}
void runReplayRecovery(reason);
scheduleReplayRecovery(reason);
} else if (replayCompletion.shouldReplay && import.meta.env.MODE !== "test") {
console.warn(
"[orchestration-recovery]",
@@ -194,11 +230,13 @@ export function createEnvironmentConnection(
}
try {
const snapshot = await input.client.orchestration.getSnapshot();
const snapshot = await retryTransportRecoveryOperation(() =>
input.client.orchestration.getSnapshot(),
);
if (!disposed) {
input.syncSnapshot(snapshot, environmentId);
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void runReplayRecovery("sequence-gap");
scheduleReplayRecovery("sequence-gap");
}
}
} catch (error) {
@@ -245,7 +283,7 @@ export function createEnvironmentConnection(
}
if (action === "recover") {
flushPendingDomainEvents();
void runReplayRecovery("sequence-gap");
scheduleReplayRecovery("sequence-gap");
}
},
{
@@ -254,7 +292,7 @@ export function createEnvironmentConnection(
return;
}
flushPendingDomainEvents();
void runReplayRecovery("resubscribe");
scheduleReplayRecovery("resubscribe");
},
},
);
@@ -0,0 +1,105 @@
import { EnvironmentId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockResolveRemotePairingTarget = vi.fn();
const mockFetchRemoteEnvironmentDescriptor = vi.fn();
const mockBootstrapRemoteBearerSession = vi.fn();
const mockPersistSavedEnvironmentRecord = vi.fn();
const mockWriteSavedEnvironmentBearerToken = vi.fn();
const mockSetSavedEnvironmentRegistry = vi.fn();
const mockUpsert = vi.fn();
const mockListSavedEnvironmentRecords = vi.fn();
vi.mock("../remote/target", () => ({
resolveRemotePairingTarget: mockResolveRemotePairingTarget,
}));
vi.mock("../remote/api", () => ({
bootstrapRemoteBearerSession: mockBootstrapRemoteBearerSession,
fetchRemoteEnvironmentDescriptor: mockFetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState: vi.fn(),
resolveRemoteWebSocketConnectionUrl: vi.fn(),
}));
vi.mock("~/localApi", () => ({
ensureLocalApi: () => ({
persistence: {
setSavedEnvironmentRegistry: mockSetSavedEnvironmentRegistry,
},
}),
}));
vi.mock("./catalog", () => ({
getSavedEnvironmentRecord: vi.fn(),
hasSavedEnvironmentRegistryHydrated: vi.fn(),
listSavedEnvironmentRecords: mockListSavedEnvironmentRecords,
persistSavedEnvironmentRecord: mockPersistSavedEnvironmentRecord,
readSavedEnvironmentBearerToken: vi.fn(),
removeSavedEnvironmentBearerToken: vi.fn(),
useSavedEnvironmentRegistryStore: {
getState: () => ({
upsert: mockUpsert,
remove: vi.fn(),
markConnected: vi.fn(),
}),
},
useSavedEnvironmentRuntimeStore: {
getState: () => ({
ensure: vi.fn(),
patch: vi.fn(),
clear: vi.fn(),
}),
},
waitForSavedEnvironmentRegistryHydration: vi.fn(),
writeSavedEnvironmentBearerToken: mockWriteSavedEnvironmentBearerToken,
}));
vi.mock("./connection", () => ({
createEnvironmentConnection: vi.fn(),
}));
describe("addSavedEnvironment", () => {
beforeEach(() => {
vi.resetModules();
vi.clearAllMocks();
mockResolveRemotePairingTarget.mockReturnValue({
httpBaseUrl: "https://remote.example.com/",
wsBaseUrl: "wss://remote.example.com/",
credential: "pairing-code",
});
mockFetchRemoteEnvironmentDescriptor.mockResolvedValue({
environmentId: EnvironmentId.makeUnsafe("environment-1"),
label: "Remote environment",
});
mockBootstrapRemoteBearerSession.mockResolvedValue({
sessionToken: "bearer-token",
role: "owner",
});
mockPersistSavedEnvironmentRecord.mockResolvedValue(undefined);
mockWriteSavedEnvironmentBearerToken.mockResolvedValue(false);
mockSetSavedEnvironmentRegistry.mockResolvedValue(undefined);
mockListSavedEnvironmentRecords.mockReturnValue([]);
});
it("rolls back persisted metadata when bearer token persistence fails", async () => {
const { addSavedEnvironment, resetEnvironmentServiceForTests } = await import("./service");
await expect(
addSavedEnvironment({
label: "Remote environment",
host: "remote.example.com",
pairingCode: "123456",
}),
).rejects.toThrow("Unable to persist saved environment credentials.");
expect(mockPersistSavedEnvironmentRecord).toHaveBeenCalledTimes(1);
expect(mockWriteSavedEnvironmentBearerToken).toHaveBeenCalledWith(
EnvironmentId.makeUnsafe("environment-1"),
"bearer-token",
);
expect(mockSetSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(mockUpsert).not.toHaveBeenCalled();
await resetEnvironmentServiceForTests();
});
});
+49 -6
View File
@@ -23,6 +23,7 @@ import {
markPromotedDraftThreadsByRef,
useComposerDraftStore,
} from "~/composerDraftStore";
import { ensureLocalApi } from "~/localApi";
import { collectActiveTerminalThreadIds } from "~/lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "~/orchestrationEventEffects";
import { projectQueryKeys } from "~/lib/projectReactQuery";
@@ -39,10 +40,14 @@ import {
getSavedEnvironmentRecord,
hasSavedEnvironmentRegistryHydrated,
listSavedEnvironmentRecords,
persistSavedEnvironmentRecord,
readSavedEnvironmentBearerToken,
removeSavedEnvironmentBearerToken,
type SavedEnvironmentRecord,
useSavedEnvironmentRegistryStore,
useSavedEnvironmentRuntimeStore,
waitForSavedEnvironmentRegistryHydration,
writeSavedEnvironmentBearerToken,
} from "./catalog";
import { createEnvironmentConnection, type EnvironmentConnection } from "./connection";
import {
@@ -306,7 +311,10 @@ function createPrimaryEnvironmentClient(
return createWsRpcClient(new WsTransport(wsBaseUrl));
}
function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClient {
function createSavedEnvironmentClient(
record: SavedEnvironmentRecord,
bearerToken: string,
): WsRpcClient {
useSavedEnvironmentRuntimeStore.getState().ensure(record.environmentId);
return createWsRpcClient(
@@ -315,7 +323,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
resolveRemoteWebSocketConnectionUrl({
wsBaseUrl: record.wsBaseUrl,
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
{
onAttempt: () => {
@@ -341,6 +349,7 @@ function createSavedEnvironmentClient(record: SavedEnvironmentRecord): WsRpcClie
async function refreshSavedEnvironmentMetadata(
record: SavedEnvironmentRecord,
bearerToken: string,
client: WsRpcClient,
roleHint?: AuthSessionRole | null,
configHint?: ServerConfig | null,
@@ -349,7 +358,7 @@ async function refreshSavedEnvironmentMetadata(
configHint ? Promise.resolve(configHint) : client.server.getConfig(),
fetchRemoteSessionState({
httpBaseUrl: record.httpBaseUrl,
bearerToken: record.bearerToken,
bearerToken,
}),
]);
@@ -408,6 +417,7 @@ async function ensureSavedEnvironmentConnection(
record: SavedEnvironmentRecord,
options?: {
readonly client?: WsRpcClient;
readonly bearerToken?: string;
readonly role?: AuthSessionRole | null;
readonly serverConfig?: ServerConfig | null;
},
@@ -417,7 +427,20 @@ async function ensureSavedEnvironmentConnection(
return existing;
}
const client = options?.client ?? createSavedEnvironmentClient(record);
const bearerToken =
options?.bearerToken ?? (await readSavedEnvironmentBearerToken(record.environmentId));
if (!bearerToken) {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
authState: "requires-auth",
role: null,
connectionState: "disconnected",
lastError: "Saved environment is missing its saved credential. Pair it again.",
lastErrorAt: isoNow(),
});
throw new Error("Saved environment is missing its saved credential.");
}
const client = options?.client ?? createSavedEnvironmentClient(record, bearerToken);
const knownEnvironment = createKnownEnvironment({
id: record.environmentId,
label: record.label,
@@ -435,7 +458,7 @@ async function ensureSavedEnvironmentConnection(
},
client,
refreshMetadata: async () => {
await refreshSavedEnvironmentMetadata(record, client);
await refreshSavedEnvironmentMetadata(record, bearerToken, client);
},
onConfigSnapshot: (config) => {
useSavedEnvironmentRuntimeStore.getState().patch(record.environmentId, {
@@ -456,6 +479,7 @@ async function ensureSavedEnvironmentConnection(
try {
await refreshSavedEnvironmentMetadata(
record,
bearerToken,
client,
options?.role ?? null,
options?.serverConfig ?? null,
@@ -552,6 +576,7 @@ export async function reconnectSavedEnvironment(environmentId: EnvironmentId): P
export async function removeSavedEnvironment(environmentId: EnvironmentId): Promise<void> {
useSavedEnvironmentRegistryStore.getState().remove(environmentId);
await removeSavedEnvironmentBearerToken(environmentId);
await disconnectSavedEnvironment(environmentId);
}
@@ -585,12 +610,30 @@ export async function addSavedEnvironment(input: {
label: input.label.trim() || descriptor.label,
wsBaseUrl: resolvedTarget.wsBaseUrl,
httpBaseUrl: resolvedTarget.httpBaseUrl,
bearerToken: bearerSession.sessionToken,
createdAt: isoNow(),
lastConnectedAt: isoNow(),
};
await persistSavedEnvironmentRecord(record);
const didPersistBearerToken = await writeSavedEnvironmentBearerToken(
environmentId,
bearerSession.sessionToken,
);
if (!didPersistBearerToken) {
await ensureLocalApi().persistence.setSavedEnvironmentRegistry(
listSavedEnvironmentRecords().map((entry) => ({
environmentId: entry.environmentId,
label: entry.label,
httpBaseUrl: entry.httpBaseUrl,
wsBaseUrl: entry.wsBaseUrl,
createdAt: entry.createdAt,
lastConnectedAt: entry.lastConnectedAt,
})),
);
throw new Error("Unable to persist saved environment credentials.");
}
await ensureSavedEnvironmentConnection(record, {
bearerToken: bearerSession.sessionToken,
role: bearerSession.role,
});
useSavedEnvironmentRegistryStore.getState().upsert(record);
+39 -26
View File
@@ -16,39 +16,15 @@ import { createThreadSelectorByRef } from "../storeSelectors";
import { resolveThreadRouteTarget } from "../threadRoutes";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
function useNewThreadState() {
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const router = useRouter();
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const activeThread = useStore(
useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const activeDraftThread = useComposerDraftStore(() =>
routeTarget
? routeTarget.kind === "server"
? getDraftThread(routeTarget.threadRef)
: useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
: null,
);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
preferredIds: projectOrder,
getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
});
}, [projectOrder, projects]);
const getCurrentRouteTarget = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
return resolveThreadRouteTarget(currentRouteParams);
}, [router]);
const handleNewThread = useCallback(
return useCallback(
(
projectRef: ScopedProjectRef,
options?: {
@@ -154,6 +130,43 @@ export function useHandleNewThread() {
},
[getCurrentRouteTarget, router, projects],
);
}
export function useNewThreadHandler() {
const handleNewThread = useNewThreadState();
return {
handleNewThread,
};
}
export function useHandleNewThread() {
const projectOrder = useUiStateStore((store) => store.projectOrder);
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
});
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
const activeThread = useStore(
useMemo(() => createThreadSelectorByRef(routeThreadRef), [routeThreadRef]),
);
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
const activeDraftThread = useComposerDraftStore(() =>
routeTarget
? routeTarget.kind === "server"
? getDraftThread(routeTarget.threadRef)
: useComposerDraftStore.getState().getDraftSession(routeTarget.draftId)
: null,
);
const projects = useStore(useShallow((store) => selectProjectsAcrossEnvironments(store)));
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
preferredIds: projectOrder,
getId: (project) => scopedProjectKey(scopeProjectRef(project.environmentId, project.id)),
});
}, [projectOrder, projects]);
const handleNewThread = useNewThreadState();
return {
activeDraftThread,
-16
View File
@@ -1,16 +0,0 @@
import { describe, expect, it } from "vitest";
import { buildLegacyClientSettingsMigrationPatch } from "./useSettings";
describe("buildLegacyClientSettingsMigrationPatch", () => {
it("migrates archive confirmation from legacy local settings", () => {
expect(
buildLegacyClientSettingsMigrationPatch({
confirmThreadArchive: true,
confirmThreadDelete: false,
}),
).toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
});
});
});
+98 -172
View File
@@ -9,33 +9,88 @@
* write. The hook transparently routes reads/writes to the correct backing
* store.
*/
import { useCallback, useMemo } from "react";
import {
ServerSettings,
ServerSettingsPatch,
ModelSelection,
ThreadEnvMode,
} from "@t3tools/contracts";
import { useCallback, useMemo, useSyncExternalStore } from "react";
import { ServerSettings, ServerSettingsPatch } from "@t3tools/contracts";
import {
type ClientSettings,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_UNIFIED_SETTINGS,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
TimestampFormat,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { ensureLocalApi } from "~/localApi";
import { useLocalStorage } from "./useLocalStorage";
import { normalizeCustomModelSlugs } from "~/modelSelection";
import { Predicate, Schema, Struct } from "effect";
import { DeepMutable } from "effect/Types";
import { Struct } from "effect";
import { deepMerge } from "@t3tools/shared/Struct";
import { applySettingsUpdated, getServerConfig, useServerSettings } from "~/rpc/serverState";
const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
const clientSettingsListeners = new Set<() => void>();
let clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
let clientSettingsHydrated = false;
let clientSettingsHydrationPromise: Promise<void> | null = null;
function emitClientSettingsChange() {
for (const listener of clientSettingsListeners) {
listener();
}
}
function getClientSettingsSnapshot(): ClientSettings {
return clientSettingsSnapshot;
}
function replaceClientSettingsSnapshot(settings: ClientSettings): void {
clientSettingsSnapshot = settings;
emitClientSettingsChange();
}
function subscribeClientSettings(listener: () => void): () => void {
clientSettingsListeners.add(listener);
void hydrateClientSettings();
return () => {
clientSettingsListeners.delete(listener);
};
}
async function hydrateClientSettings(): Promise<void> {
if (clientSettingsHydrated) {
return;
}
if (clientSettingsHydrationPromise) {
return clientSettingsHydrationPromise;
}
const nextHydration = (async () => {
try {
const persistedSettings = await ensureLocalApi().persistence.getClientSettings();
if (persistedSettings) {
replaceClientSettingsSnapshot(persistedSettings);
}
} catch (error) {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} hydrate failed`, error);
} finally {
clientSettingsHydrated = true;
}
})();
const hydrationPromise = nextHydration.finally(() => {
if (clientSettingsHydrationPromise === hydrationPromise) {
clientSettingsHydrationPromise = null;
}
});
clientSettingsHydrationPromise = hydrationPromise;
return clientSettingsHydrationPromise;
}
function persistClientSettings(settings: ClientSettings): void {
replaceClientSettingsSnapshot(settings);
void ensureLocalApi()
.persistence.setClientSettings(settings)
.catch((error) => {
console.error(`${CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE} persist failed`, error);
});
}
// ── Key sets for routing patches ─────────────────────────────────────
@@ -69,10 +124,10 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const serverSettings = useServerSettings();
const [clientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
DEFAULT_CLIENT_SETTINGS,
ClientSettingsSchema,
const clientSettings = useSyncExternalStore(
subscribeClientSettings,
getClientSettingsSnapshot,
() => DEFAULT_CLIENT_SETTINGS,
);
const merged = useMemo<UnifiedSettings>(
@@ -90,34 +145,28 @@ export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings)
* Returns an updater that routes each key to the correct backing store.
*
* Server keys are optimistically patched in atom-backed server state, then
* persisted via RPC. Client keys go straight to localStorage.
* persisted via RPC. Client keys go through client persistence.
*/
export function useUpdateSettings() {
const [, setClientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
DEFAULT_CLIENT_SETTINGS,
ClientSettingsSchema,
);
const updateSettings = useCallback((patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
const updateSettings = useCallback(
(patch: Partial<UnifiedSettings>) => {
const { serverPatch, clientPatch } = splitPatch(patch);
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
if (Object.keys(serverPatch).length > 0) {
const currentServerConfig = getServerConfig();
if (currentServerConfig) {
applySettingsUpdated(deepMerge(currentServerConfig.settings, serverPatch));
}
// Fire-and-forget RPC — push will reconcile on success
void ensureLocalApi().server.updateSettings(serverPatch);
}
if (Object.keys(clientPatch).length > 0) {
setClientSettings((prev) => ({ ...prev, ...clientPatch }));
}
},
[setClientSettings],
);
if (Object.keys(clientPatch).length > 0) {
persistClientSettings({
...getClientSettingsSnapshot(),
...clientPatch,
});
}
}, []);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_UNIFIED_SETTINGS);
@@ -129,132 +178,9 @@ export function useUpdateSettings() {
};
}
// ── One-time migration from localStorage ─────────────────────────────
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
const patch: DeepMutable<ServerSettingsPatch> = {};
if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
}
if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
}
if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
}
if (typeof legacySettings.codexBinaryPath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
}
if (typeof legacySettings.codexHomePath === "string") {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.homePath = legacySettings.codexHomePath;
}
if (Array.isArray(legacySettings.customCodexModels)) {
patch.providers ??= {};
patch.providers.codex ??= {};
patch.providers.codex.customModels = normalizeCustomModelSlugs(
legacySettings.customCodexModels,
new Set<string>(),
"codex",
);
}
if (Predicate.isString(legacySettings.claudeBinaryPath)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
}
if (Array.isArray(legacySettings.customClaudeModels)) {
patch.providers ??= {};
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
legacySettings.customClaudeModels,
new Set<string>(),
"claudeAgent",
);
}
return patch;
}
export function buildLegacyClientSettingsMigrationPatch(
legacySettings: Record<string, unknown>,
): Partial<DeepMutable<ClientSettings>> {
const patch: Partial<DeepMutable<ClientSettings>> = {};
if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) {
patch.confirmThreadArchive = legacySettings.confirmThreadArchive;
}
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
}
if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
patch.diffWordWrap = legacySettings.diffWordWrap;
}
if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
}
if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
}
if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
patch.timestampFormat = legacySettings.timestampFormat;
}
return patch;
}
/**
* Call once on app startup.
* If the legacy localStorage key exists, migrate its values to the new server
* and client storage formats, then remove the legacy key so this only runs once.
*/
export function migrateLocalSettingsToServer(): void {
if (typeof window === "undefined") return;
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
if (!raw) return;
try {
const old = JSON.parse(raw);
if (!Predicate.isObject(old)) return;
// Migrate server-relevant keys via RPC
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
if (Object.keys(serverPatch).length > 0) {
const api = ensureLocalApi();
void api.server.updateSettings(serverPatch);
}
// Migrate client-only keys to the new localStorage key
const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
if (Object.keys(clientPatch).length > 0) {
const existing = localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
const current = existing ? (JSON.parse(existing) as Record<string, unknown>) : {};
localStorage.setItem(
CLIENT_SETTINGS_STORAGE_KEY,
JSON.stringify({ ...current, ...clientPatch }),
);
}
} catch (error) {
console.error("[MIGRATION] Error migrating local settings:", error);
} finally {
// Remove the legacy key regardless to keep migration one-shot behavior.
localStorage.removeItem(OLD_SETTINGS_KEY);
}
export function __resetClientSettingsPersistenceForTests(): void {
clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;
clientSettingsHydrated = false;
clientSettingsHydrationPromise = null;
clientSettingsListeners.clear();
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { useCallback } from "react";
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { useHandleNewThread } from "./useHandleNewThread";
import { useNewThreadHandler } from "./useHandleNewThread";
import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi";
import { invalidateGitQueries } from "../lib/gitReactQuery";
import { newCommandId } from "../lib/utils";
@@ -32,7 +32,7 @@ export function useThreadActions() {
);
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
const router = useRouter();
const { handleNewThread } = useHandleNewThread();
const { handleNewThread } = useNewThreadHandler();
const queryClient = useQueryClient();
const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
+1 -2
View File
@@ -335,8 +335,7 @@ label:has(> select#reasoning-effort) select {
border: none;
background: transparent;
padding: 0;
line-height: 1.5;
font-size: 0.875rem;
font-size: 0.75rem;
}
.chat-markdown .chat-markdown-codeblock {
-996
View File
@@ -1,996 +0,0 @@
// @ts-nocheck
/* oxlint-disable eslint/no-useless-escape */
/*
* QR Code generator library (TypeScript)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
"use strict";
namespace qrcodegen {
type bit = number;
type byte = number;
type int = number;
/*---- QR Code symbol class ----*/
/*
* A QR Code symbol, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* Instances of this class represent an immutable square grid of dark and light cells.
* The class provides static factory functions to create a QR Code from text or binary data.
* The class covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
* - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
* - Low level: Custom-make the array of data codeword bytes (including
* segment headers and final padding, excluding error correction codewords),
* supply the appropriate version number, and call the QrCode() constructor.
* (Note that all ways require supplying the desired error correction level.)
*/
export class QrCode {
/*-- Static factory functions (high level) --*/
// Returns a QR Code representing the given Unicode text string at the given error correction level.
// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
// ecl argument if it can be done without increasing the version.
public static encodeText(text: string, ecl: QrCode.Ecc): QrCode {
const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text);
return QrCode.encodeSegments(segs, ecl);
}
// Returns a QR Code representing the given binary data at the given error correction level.
// This function always encodes using the binary segment mode, not any text mode. The maximum number of
// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode {
const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data);
return QrCode.encodeSegments([seg], ecl);
}
/*-- Static factory functions (mid level) --*/
// Returns a QR Code representing the given segments with the given encoding parameters.
// The smallest possible QR Code version within the given range is automatically
// chosen for the output. Iff boostEcl is true, then the ECC level of the result
// may be higher than the ecl argument if it can be done without increasing the
// version. The mask number is either between 0 to 7 (inclusive) to force that
// mask, or -1 to automatically choose an appropriate mask (which may be slow).
// This function allows the user to create a custom sequence of segments that switches
// between modes (such as alphanumeric and byte) to encode text in less space.
// This is a mid-level API; the high-level API is encodeText() and encodeBinary().
public static encodeSegments(segs: Readonly<Array<QrSegment>>, ecl: QrCode.Ecc,
minVersion: int = 1, maxVersion: int = 40,
mask: int = -1, boostEcl: boolean = true): QrCode {
if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
|| mask < -1 || mask > 7)
throw new RangeError("Invalid value");
// Find the minimal version number to use
let version: int;
let dataUsedBits: int;
for (version = minVersion; ; version++) {
const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
const usedBits: number = QrSegment.getTotalBits(segs, version);
if (usedBits <= dataCapacityBits) {
dataUsedBits = usedBits;
break; // This version number is found to be suitable
}
if (version >= maxVersion) // All versions in the range could not fit the given data
throw new RangeError("Data too long");
}
// Increase the error correction level while the data still fits in the current version number
for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high
if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
ecl = newEcl;
}
// Concatenate all segments to create the data bit string
let bb: Array<bit> = []
for (const seg of segs) {
appendBits(seg.mode.modeBits, 4, bb);
appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
for (const b of seg.getData())
bb.push(b);
}
assert(bb.length == dataUsedBits);
// Add terminator and pad up to a byte if applicable
const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;
assert(bb.length <= dataCapacityBits);
appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
appendBits(0, (8 - bb.length % 8) % 8, bb);
assert(bb.length % 8 == 0);
// Pad with alternating bytes until data capacity is reached
for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
appendBits(padByte, 8, bb);
// Pack bits into bytes in big endian
let dataCodewords: Array<byte> = [];
while (dataCodewords.length * 8 < bb.length)
dataCodewords.push(0);
bb.forEach((b: bit, i: int) =>
dataCodewords[i >>> 3] |= b << (7 - (i & 7)));
// Create the QR Code object
return new QrCode(version, ecl, dataCodewords, mask);
}
/*-- Fields --*/
// The width and height of this QR Code, measured in modules, between
// 21 and 177 (inclusive). This is equal to version * 4 + 17.
public readonly size: int;
// The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
// Even if a QR Code is created with automatic masking requested (mask = -1),
// the resulting object still has a mask value between 0 and 7.
public readonly mask: int;
// The modules of this QR Code (false = light, true = dark).
// Immutable after constructor finishes. Accessed through getModule().
private readonly modules : Array<Array<boolean>> = [];
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
private readonly isFunction: Array<Array<boolean>> = [];
/*-- Constructor (low level) and fields --*/
// Creates a new QR Code with the given version number,
// error correction level, data codeword bytes, and mask number.
// This is a low-level API that most users should not use directly.
// A mid-level API is the encodeSegments() function.
public constructor(
// The version number of this QR Code, which is between 1 and 40 (inclusive).
// This determines the size of this barcode.
public readonly version: int,
// The error correction level used in this QR Code.
public readonly errorCorrectionLevel: QrCode.Ecc,
dataCodewords: Readonly<Array<byte>>,
msk: int) {
// Check scalar arguments
if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
throw new RangeError("Version value out of range");
if (msk < -1 || msk > 7)
throw new RangeError("Mask value out of range");
this.size = version * 4 + 17;
// Initialize both grids to be size*size arrays of Boolean false
let row: Array<boolean> = [];
for (let i = 0; i < this.size; i++)
row.push(false);
for (let i = 0; i < this.size; i++) {
this.modules .push(row.slice()); // Initially all light
this.isFunction.push(row.slice());
}
// Compute ECC, draw modules
this.drawFunctionPatterns();
const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);
this.drawCodewords(allCodewords);
// Do masking
if (msk == -1) { // Automatically choose best mask
let minPenalty: int = 1000000000;
for (let i = 0; i < 8; i++) {
this.applyMask(i);
this.drawFormatBits(i);
const penalty: int = this.getPenaltyScore();
if (penalty < minPenalty) {
msk = i;
minPenalty = penalty;
}
this.applyMask(i); // Undoes the mask due to XOR
}
}
assert(0 <= msk && msk <= 7);
this.mask = msk;
this.applyMask(msk); // Apply the final choice of mask
this.drawFormatBits(msk); // Overwrite old format bits
this.isFunction = [];
}
/*-- Accessor methods --*/
// Returns the color of the module (pixel) at the given coordinates, which is false
// for light or true for dark. The top left corner has the coordinates (x=0, y=0).
// If the given coordinates are out of bounds, then false (light) is returned.
public getModule(x: int, y: int): boolean {
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
}
/*-- Private helper methods for constructor: Drawing function modules --*/
// Reads this object's version field, and draws and marks all function modules.
private drawFunctionPatterns(): void {
// Draw horizontal and vertical timing patterns
for (let i = 0; i < this.size; i++) {
this.setFunctionModule(6, i, i % 2 == 0);
this.setFunctionModule(i, 6, i % 2 == 0);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
this.drawFinderPattern(3, 3);
this.drawFinderPattern(this.size - 4, 3);
this.drawFinderPattern(3, this.size - 4);
// Draw numerous alignment patterns
const alignPatPos: Array<int> = this.getAlignmentPatternPositions();
const numAlign: int = alignPatPos.length;
for (let i = 0; i < numAlign; i++) {
for (let j = 0; j < numAlign; j++) {
// Don't draw on the three finder corners
if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
}
}
// Draw configuration data
this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
this.drawVersion();
}
// Draws two copies of the format bits (with its own error correction code)
// based on the given mask and this object's error correction level field.
private drawFormatBits(mask: int): void {
// Calculate error correction code and pack bits
const data: int = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
let rem: int = data;
for (let i = 0; i < 10; i++)
rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
const bits = (data << 10 | rem) ^ 0x5412; // uint15
assert(bits >>> 15 == 0);
// Draw first copy
for (let i = 0; i <= 5; i++)
this.setFunctionModule(8, i, getBit(bits, i));
this.setFunctionModule(8, 7, getBit(bits, 6));
this.setFunctionModule(8, 8, getBit(bits, 7));
this.setFunctionModule(7, 8, getBit(bits, 8));
for (let i = 9; i < 15; i++)
this.setFunctionModule(14 - i, 8, getBit(bits, i));
// Draw second copy
for (let i = 0; i < 8; i++)
this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
for (let i = 8; i < 15; i++)
this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
this.setFunctionModule(8, this.size - 8, true); // Always dark
}
// Draws two copies of the version bits (with its own error correction code),
// based on this object's version field, iff 7 <= version <= 40.
private drawVersion(): void {
if (this.version < 7)
return;
// Calculate error correction code and pack bits
let rem: int = this.version; // version is uint6, in the range [7, 40]
for (let i = 0; i < 12; i++)
rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
const bits: int = this.version << 12 | rem; // uint18
assert(bits >>> 18 == 0);
// Draw two copies
for (let i = 0; i < 18; i++) {
const color: boolean = getBit(bits, i);
const a: int = this.size - 11 + i % 3;
const b: int = Math.floor(i / 3);
this.setFunctionModule(a, b, color);
this.setFunctionModule(b, a, color);
}
}
// Draws a 9*9 finder pattern including the border separator,
// with the center module at (x, y). Modules can be out of bounds.
private drawFinderPattern(x: int, y: int): void {
for (let dy = -4; dy <= 4; dy++) {
for (let dx = -4; dx <= 4; dx++) {
const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
const xx: int = x + dx;
const yy: int = y + dy;
if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
}
}
}
// Draws a 5*5 alignment pattern, with the center module
// at (x, y). All modules must be in bounds.
private drawAlignmentPattern(x: int, y: int): void {
for (let dy = -2; dy <= 2; dy++) {
for (let dx = -2; dx <= 2; dx++)
this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
}
}
// Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in bounds.
private setFunctionModule(x: int, y: int, isDark: boolean): void {
this.modules[y][x] = isDark;
this.isFunction[y][x] = true;
}
/*-- Private helper methods for constructor: Codewords and masking --*/
// Returns a new byte string representing the given data with the appropriate error correction
// codewords appended to it, based on this object's version and error correction level.
private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {
const ver: int = this.version;
const ecl: QrCode.Ecc = this.errorCorrectionLevel;
if (data.length != QrCode.getNumDataCodewords(ver, ecl))
throw new RangeError("Invalid argument");
// Calculate parameter numbers
const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver];
const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
const numShortBlocks: int = numBlocks - rawCodewords % numBlocks;
const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);
// Split data into blocks and append ECC to each block
let blocks: Array<Array<byte>> = [];
const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);
for (let i = 0, k = 0; i < numBlocks; i++) {
let dat: Array<byte> = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
k += dat.length;
const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
if (i < numShortBlocks)
dat.push(0);
blocks.push(dat.concat(ecc));
}
// Interleave (not concatenate) the bytes from every block into a single sequence
let result: Array<byte> = [];
for (let i = 0; i < blocks[0].length; i++) {
blocks.forEach((block, j) => {
// Skip the padding byte in short blocks
if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
result.push(block[i]);
});
}
assert(result.length == rawCodewords);
return result;
}
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
// data area of this QR Code. Function modules need to be marked off before this is called.
private drawCodewords(data: Readonly<Array<byte>>): void {
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
throw new RangeError("Invalid argument");
let i: int = 0; // Bit index into the data
// Do the funny zigzag scan
for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
if (right == 6)
right = 5;
for (let vert = 0; vert < this.size; vert++) { // Vertical counter
for (let j = 0; j < 2; j++) {
const x: int = right - j; // Actual x coordinate
const upward: boolean = ((right + 1) & 2) == 0;
const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate
if (!this.isFunction[y][x] && i < data.length * 8) {
this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
i++;
}
// If this QR Code has any remainder bits (0 to 7), they were assigned as
// 0/false/light by the constructor and are left unchanged by this method
}
}
}
assert(i == data.length * 8);
}
// XORs the codeword modules in this QR Code with the given mask pattern.
// The function modules must be marked and the codeword bits must be drawn
// before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed
// QR Code needs exactly one (not zero, two, etc.) mask applied.
private applyMask(mask: int): void {
if (mask < 0 || mask > 7)
throw new RangeError("Mask value out of range");
for (let y = 0; y < this.size; y++) {
for (let x = 0; x < this.size; x++) {
let invert: boolean;
switch (mask) {
case 0: invert = (x + y) % 2 == 0; break;
case 1: invert = y % 2 == 0; break;
case 2: invert = x % 3 == 0; break;
case 3: invert = (x + y) % 3 == 0; break;
case 4: invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0; break;
case 5: invert = x * y % 2 + x * y % 3 == 0; break;
case 6: invert = (x * y % 2 + x * y % 3) % 2 == 0; break;
case 7: invert = ((x + y) % 2 + x * y % 3) % 2 == 0; break;
default: throw new Error("Unreachable");
}
if (!this.isFunction[y][x] && invert)
this.modules[y][x] = !this.modules[y][x];
}
}
}
// Calculates and returns the penalty score based on state of this QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private getPenaltyScore(): int {
let result: int = 0;
// Adjacent modules in row having same color, and finder-like patterns
for (let y = 0; y < this.size; y++) {
let runColor = false;
let runX = 0;
let runHistory = [0,0,0,0,0,0,0];
for (let x = 0; x < this.size; x++) {
if (this.modules[y][x] == runColor) {
runX++;
if (runX == 5)
result += QrCode.PENALTY_N1;
else if (runX > 5)
result++;
} else {
this.finderPenaltyAddHistory(runX, runHistory);
if (!runColor)
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
runColor = this.modules[y][x];
runX = 1;
}
}
result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
}
// Adjacent modules in column having same color, and finder-like patterns
for (let x = 0; x < this.size; x++) {
let runColor = false;
let runY = 0;
let runHistory = [0,0,0,0,0,0,0];
for (let y = 0; y < this.size; y++) {
if (this.modules[y][x] == runColor) {
runY++;
if (runY == 5)
result += QrCode.PENALTY_N1;
else if (runY > 5)
result++;
} else {
this.finderPenaltyAddHistory(runY, runHistory);
if (!runColor)
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
runColor = this.modules[y][x];
runY = 1;
}
}
result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
}
// 2*2 blocks of modules having same color
for (let y = 0; y < this.size - 1; y++) {
for (let x = 0; x < this.size - 1; x++) {
const color: boolean = this.modules[y][x];
if ( color == this.modules[y][x + 1] &&
color == this.modules[y + 1][x] &&
color == this.modules[y + 1][x + 1])
result += QrCode.PENALTY_N2;
}
}
// Balance of dark and light modules
let dark: int = 0;
for (const row of this.modules)
dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2
// Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
assert(0 <= k && k <= 9);
result += k * QrCode.PENALTY_N4;
assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
return result;
}
/*-- Private helper functions --*/
// Returns an ascending list of positions of alignment patterns for this version number.
// Each position is in the range [0,177), and are used on both the x and y axes.
// This could be implemented as lookup table of 40 variable-length lists of integers.
private getAlignmentPatternPositions(): Array<int> {
if (this.version == 1)
return [];
else {
const numAlign: int = Math.floor(this.version / 7) + 2;
const step: int = (this.version == 32) ? 26 :
Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
let result: Array<int> = [6];
for (let pos = this.size - 7; result.length < numAlign; pos -= step)
result.splice(1, 0, pos);
return result;
}
}
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
private static getNumRawDataModules(ver: int): int {
if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
throw new RangeError("Version number out of range");
let result: int = (16 * ver + 128) * ver + 64;
if (ver >= 2) {
const numAlign: int = Math.floor(ver / 7) + 2;
result -= (25 * numAlign - 10) * numAlign - 55;
if (ver >= 7)
result -= 36;
}
assert(208 <= result && result <= 29648);
return result;
}
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
// QR Code of the given version number and error correction level, with remainder bits discarded.
// This stateless pure function could be implemented as a (40*4)-cell lookup table.
private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int {
return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
QrCode.ECC_CODEWORDS_PER_BLOCK [ecl.ordinal][ver] *
QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
}
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
private static reedSolomonComputeDivisor(degree: int): Array<byte> {
if (degree < 1 || degree > 255)
throw new RangeError("Degree out of range");
// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
let result: Array<byte> = [];
for (let i = 0; i < degree - 1; i++)
result.push(0);
result.push(1); // Start off with the monomial x^0
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
// and drop the highest monomial term which is always 1x^degree.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
let root = 1;
for (let i = 0; i < degree; i++) {
// Multiply the current product by (x - r^i)
for (let j = 0; j < result.length; j++) {
result[j] = QrCode.reedSolomonMultiply(result[j], root);
if (j + 1 < result.length)
result[j] ^= result[j + 1];
}
root = QrCode.reedSolomonMultiply(root, 0x02);
}
return result;
}
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
private static reedSolomonComputeRemainder(data: Readonly<Array<byte>>, divisor: Readonly<Array<byte>>): Array<byte> {
let result: Array<byte> = divisor.map(_ => 0);
for (const b of data) { // Polynomial division
const factor: byte = b ^ (result.shift() as byte);
result.push(0);
divisor.forEach((coef, i) =>
result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
}
return result;
}
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
// are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
private static reedSolomonMultiply(x: byte, y: byte): byte {
if (x >>> 8 != 0 || y >>> 8 != 0)
throw new RangeError("Byte out of range");
// Russian peasant multiplication
let z: int = 0;
for (let i = 7; i >= 0; i--) {
z = (z << 1) ^ ((z >>> 7) * 0x11D);
z ^= ((y >>> i) & 1) * x;
}
assert(z >>> 8 == 0);
return z as byte;
}
// Can only be called immediately after a light run is added, and
// returns either 0, 1, or 2. A helper function for getPenaltyScore().
private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {
const n: int = runHistory[1];
assert(n <= this.size * 3);
const core: boolean = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
+ (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
}
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
private finderPenaltyTerminateAndCount(currentRunColor: boolean, currentRunLength: int, runHistory: Array<int>): int {
if (currentRunColor) { // Terminate dark run
this.finderPenaltyAddHistory(currentRunLength, runHistory);
currentRunLength = 0;
}
currentRunLength += this.size; // Add light border to final run
this.finderPenaltyAddHistory(currentRunLength, runHistory);
return this.finderPenaltyCountPatterns(runHistory);
}
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {
if (runHistory[0] == 0)
currentRunLength += this.size; // Add light border to initial run
runHistory.pop();
runHistory.unshift(currentRunLength);
}
/*-- Constants and tables --*/
// The minimum version number supported in the QR Code Model 2 standard.
public static readonly MIN_VERSION: int = 1;
// The maximum version number supported in the QR Code Model 2 standard.
public static readonly MAX_VERSION: int = 40;
// For use in getPenaltyScore(), when evaluating which mask is best.
private static readonly PENALTY_N1: int = 3;
private static readonly PENALTY_N2: int = 3;
private static readonly PENALTY_N3: int = 40;
private static readonly PENALTY_N4: int = 10;
private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
[-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
[-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
[-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
[-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
];
private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
[-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
[-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
[-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
[-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
];
}
// Appends the given number of low-order bits of the given value
// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
function appendBits(val: int, len: int, bb: Array<bit>): void {
if (len < 0 || len > 31 || val >>> len != 0)
throw new RangeError("Value out of range");
for (let i = len - 1; i >= 0; i--) // Append bit by bit
bb.push((val >>> i) & 1);
}
// Returns true iff the i'th bit of x is set to 1.
function getBit(x: int, i: int): boolean {
return ((x >>> i) & 1) != 0;
}
// Throws an exception if the given condition is false.
function assert(cond: boolean): void {
if (!cond)
throw new Error("Assertion error");
}
/*---- Data segment class ----*/
/*
* A segment of character/binary/control data in a QR Code symbol.
* Instances of this class are immutable.
* The mid-level way to create a segment is to take the payload data
* and call a static factory function such as QrSegment.makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and call the QrSegment() constructor with appropriate values.
* This segment class imposes no length restrictions, but QR Codes have restrictions.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
*/
export class QrSegment {
/*-- Static factory functions (mid level) --*/
// Returns a segment representing the given binary data encoded in
// byte mode. All input byte arrays are acceptable. Any text string
// can be converted to UTF-8 bytes and encoded as a byte mode segment.
public static makeBytes(data: Readonly<Array<byte>>): QrSegment {
let bb: Array<bit> = []
for (const b of data)
appendBits(b, 8, bb);
return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
}
// Returns a segment representing the given string of decimal digits encoded in numeric mode.
public static makeNumeric(digits: string): QrSegment {
if (!QrSegment.isNumeric(digits))
throw new RangeError("String contains non-numeric characters");
let bb: Array<bit> = []
for (let i = 0; i < digits.length; ) { // Consume up to 3 digits per iteration
const n: int = Math.min(digits.length - i, 3);
appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
i += n;
}
return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
}
// Returns a segment representing the given text string encoded in alphanumeric mode.
// The characters allowed are: 0 to 9, A to Z (uppercase only), space,
// dollar, percent, asterisk, plus, hyphen, period, slash, colon.
public static makeAlphanumeric(text: string): QrSegment {
if (!QrSegment.isAlphanumeric(text))
throw new RangeError("String contains unencodable characters in alphanumeric mode");
let bb: Array<bit> = []
let i: int;
for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
appendBits(temp, 11, bb);
}
if (i < text.length) // 1 character remaining
appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
}
// Returns a new mutable list of zero or more segments to represent the given Unicode text string.
// The result may use various segment modes and switch modes to optimize the length of the bit stream.
public static makeSegments(text: string): Array<QrSegment> {
// Select the most efficient segment encoding automatically
if (text == "")
return [];
else if (QrSegment.isNumeric(text))
return [QrSegment.makeNumeric(text)];
else if (QrSegment.isAlphanumeric(text))
return [QrSegment.makeAlphanumeric(text)];
else
return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
}
// Returns a segment representing an Extended Channel Interpretation
// (ECI) designator with the given assignment value.
public static makeEci(assignVal: int): QrSegment {
let bb: Array<bit> = []
if (assignVal < 0)
throw new RangeError("ECI assignment value out of range");
else if (assignVal < (1 << 7))
appendBits(assignVal, 8, bb);
else if (assignVal < (1 << 14)) {
appendBits(0b10, 2, bb);
appendBits(assignVal, 14, bb);
} else if (assignVal < 1000000) {
appendBits(0b110, 3, bb);
appendBits(assignVal, 21, bb);
} else
throw new RangeError("ECI assignment value out of range");
return new QrSegment(QrSegment.Mode.ECI, 0, bb);
}
// Tests whether the given string can be encoded as a segment in numeric mode.
// A string is encodable iff each character is in the range 0 to 9.
public static isNumeric(text: string): boolean {
return QrSegment.NUMERIC_REGEX.test(text);
}
// Tests whether the given string can be encoded as a segment in alphanumeric mode.
// A string is encodable iff each character is in the following set: 0 to 9, A to Z
// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
public static isAlphanumeric(text: string): boolean {
return QrSegment.ALPHANUMERIC_REGEX.test(text);
}
/*-- Constructor (low level) and fields --*/
// Creates a new QR Code segment with the given attributes and data.
// The character count (numChars) must agree with the mode and the bit buffer length,
// but the constraint isn't checked. The given bit buffer is cloned and stored.
public constructor(
// The mode indicator of this segment.
public readonly mode: QrSegment.Mode,
// The length of this segment's unencoded data. Measured in characters for
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
// Always zero or positive. Not the same as the data's bit length.
public readonly numChars: int,
// The data bits of this segment. Accessed through getData().
private readonly bitData: Array<bit>) {
if (numChars < 0)
throw new RangeError("Invalid argument");
this.bitData = bitData.slice(); // Make defensive copy
}
/*-- Methods --*/
// Returns a new copy of the data bits of this segment.
public getData(): Array<bit> {
return this.bitData.slice(); // Make defensive copy
}
// (Package-private) Calculates and returns the number of bits needed to encode the given segments at
// the given version. The result is infinity if a segment has too many characters to fit its length field.
public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {
let result: number = 0;
for (const seg of segs) {
const ccbits: int = seg.mode.numCharCountBits(version);
if (seg.numChars >= (1 << ccbits))
return Infinity; // The segment's length doesn't fit the field's bit width
result += 4 + ccbits + seg.bitData.length;
}
return result;
}
// Returns a new array of bytes representing the given string encoded in UTF-8.
private static toUtf8ByteArray(str: string): Array<byte> {
str = encodeURI(str);
let result: Array<byte> = [];
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) != "%")
result.push(str.charCodeAt(i));
else {
result.push(parseInt(str.substring(i + 1, i + 3), 16));
i += 2;
}
}
return result;
}
/*-- Constants --*/
// Describes precisely all strings that are encodable in numeric mode.
private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;
// Describes precisely all strings that are encodable in alphanumeric mode.
private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;
// The set of all legal characters in alphanumeric mode,
// where each character value maps to the index in the string.
private static readonly ALPHANUMERIC_CHARSET: string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
}
}
/*---- Public helper enumeration ----*/
namespace qrcodegen.QrCode {
type int = number;
/*
* The error correction level in a QR Code symbol. Immutable.
*/
export class Ecc {
/*-- Constants --*/
public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
/*-- Constructor and fields --*/
private constructor(
// In the range 0 to 3 (unsigned 2-bit integer).
public readonly ordinal: int,
// (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
public readonly formatBits: int) {}
}
}
/*---- Public helper enumeration ----*/
namespace qrcodegen.QrSegment {
type int = number;
/*
* Describes how a segment's data bits are interpreted. Immutable.
*/
export class Mode {
/*-- Constants --*/
public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]);
public static readonly ALPHANUMERIC = new Mode(0x2, [ 9, 11, 13]);
public static readonly BYTE = new Mode(0x4, [ 8, 16, 16]);
public static readonly KANJI = new Mode(0x8, [ 8, 10, 12]);
public static readonly ECI = new Mode(0x7, [ 0, 0, 0]);
/*-- Constructor and fields --*/
private constructor(
// The mode indicator bits, which is a uint4 value (range 0 to 15).
public readonly modeBits: int,
// Number of character count bits for three different version ranges.
private readonly numBitsCharCount: [int,int,int]) {}
/*-- Method --*/
// (Package-private) Returns the bit width of the character count field for a segment in
// this mode in a QR Code at the given version number. The result is in the range [0, 16].
public numCharCountBits(ver: int): int {
return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
}
}
}
export const QrCode = qrcodegen.QrCode;
export const QrSegment = qrcodegen.QrSegment;
+155 -1
View File
@@ -137,9 +137,36 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
return testGlobal.window;
}
function createLocalStorageStub(): Storage {
const store = new Map<string, string>();
return {
getItem: (key) => store.get(key) ?? null,
setItem: (key, value) => {
store.set(key, value);
},
removeItem: (key) => {
store.delete(key);
},
clear: () => {
store.clear();
},
key: (index) => [...store.keys()][index] ?? null,
get length() {
return store.size;
},
};
}
function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): DesktopBridge {
return {
getLocalEnvironmentBootstrap: () => null,
getClientSettings: async () => null,
setClientSettings: async () => undefined,
getSavedEnvironmentRegistry: async () => [],
setSavedEnvironmentRegistry: async () => undefined,
getSavedEnvironmentSecret: async () => null,
setSavedEnvironmentSecret: async () => true,
removeSavedEnvironmentSecret: async () => undefined,
getServerExposureState: async () => ({
mode: "local-only",
endpointUrl: null,
@@ -242,7 +269,12 @@ beforeEach(() => {
terminalEventListeners.clear();
orchestrationEventListeners.clear();
gitStatusListeners.clear();
Reflect.deleteProperty(getWindowForTest(), "desktopBridge");
const testWindow = getWindowForTest();
Reflect.deleteProperty(testWindow, "desktopBridge");
Object.defineProperty(testWindow, "localStorage", {
configurable: true,
value: createLocalStorageStub(),
});
});
afterEach(() => {
@@ -463,4 +495,126 @@ describe("wsApi", () => {
await expect(api.contextMenu.show(items, { x: 4, y: 5 })).resolves.toBe("rename");
expect(showContextMenuFallbackMock).toHaveBeenCalledWith(items, { x: 4, y: 5 });
});
it("reads and writes persistence through the desktop bridge when available", async () => {
const getClientSettings = vi.fn().mockResolvedValue({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
const setClientSettings = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentRegistry = vi.fn().mockResolvedValue([]);
const setSavedEnvironmentRegistry = vi.fn().mockResolvedValue(undefined);
const getSavedEnvironmentSecret = vi.fn().mockResolvedValue("bearer-token");
const setSavedEnvironmentSecret = vi.fn().mockResolvedValue(true);
const removeSavedEnvironmentSecret = vi.fn().mockResolvedValue(undefined);
getWindowForTest().desktopBridge = makeDesktopBridge({
getClientSettings,
setClientSettings,
getSavedEnvironmentRegistry,
setSavedEnvironmentRegistry,
getSavedEnvironmentSecret,
setSavedEnvironmentSecret,
removeSavedEnvironmentSecret,
});
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.getClientSettings();
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.getSavedEnvironmentRegistry();
await api.persistence.setSavedEnvironmentRegistry([]);
await api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local"));
await api.persistence.setSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
"bearer-token",
);
await api.persistence.removeSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
);
expect(getClientSettings).toHaveBeenCalledWith();
expect(setClientSettings).toHaveBeenCalledWith({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
expect(getSavedEnvironmentRegistry).toHaveBeenCalledWith();
expect(setSavedEnvironmentRegistry).toHaveBeenCalledWith([]);
expect(getSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
expect(setSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local", "bearer-token");
expect(removeSavedEnvironmentSecret).toHaveBeenCalledWith("environment-local");
});
it("falls back to browser storage for persistence when the desktop bridge is missing", async () => {
const { createLocalApi } = await import("./localApi");
const api = createLocalApi(rpcClientMock as never);
await api.persistence.setClientSettings({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await api.persistence.setSavedEnvironmentRegistry([
{
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Primary",
httpBaseUrl: "http://localhost:3000",
wsBaseUrl: "ws://localhost:3000",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
]);
await api.persistence.setSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
"bearer-token",
);
await expect(api.persistence.getClientSettings()).resolves.toEqual({
confirmThreadArchive: true,
confirmThreadDelete: false,
diffWordWrap: true,
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
timestampFormat: "24-hour",
});
await expect(api.persistence.getSavedEnvironmentRegistry()).resolves.toEqual([
{
environmentId: EnvironmentId.makeUnsafe("environment-local"),
label: "Primary",
httpBaseUrl: "http://localhost:3000",
wsBaseUrl: "ws://localhost:3000",
createdAt: "2026-04-09T00:00:00.000Z",
lastConnectedAt: null,
},
]);
await expect(
api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
).resolves.toBe("bearer-token");
await api.persistence.removeSavedEnvironmentSecret(
EnvironmentId.makeUnsafe("environment-local"),
);
await expect(
api.persistence.getSavedEnvironmentSecret(EnvironmentId.makeUnsafe("environment-local")),
).resolves.toBeNull();
});
});
+55
View File
@@ -14,6 +14,15 @@ import {
} from "./environments/runtime";
import { type WsRpcClient } from "./rpc/wsRpcClient";
import { showContextMenuFallback } from "./contextMenuFallback";
import {
readBrowserClientSettings,
readBrowserSavedEnvironmentRegistry,
readBrowserSavedEnvironmentSecret,
removeBrowserSavedEnvironmentSecret,
writeBrowserClientSettings,
writeBrowserSavedEnvironmentRegistry,
writeBrowserSavedEnvironmentSecret,
} from "./clientPersistenceStorage";
let cachedApi: LocalApi | undefined;
@@ -56,6 +65,50 @@ export function createLocalApi(rpcClient: WsRpcClient): LocalApi {
return showContextMenuFallback(items, position);
},
},
persistence: {
getClientSettings: async () => {
if (window.desktopBridge) {
return window.desktopBridge.getClientSettings();
}
return readBrowserClientSettings();
},
setClientSettings: async (settings) => {
if (window.desktopBridge) {
return window.desktopBridge.setClientSettings(settings);
}
writeBrowserClientSettings(settings);
},
getSavedEnvironmentRegistry: async () => {
if (window.desktopBridge) {
return window.desktopBridge.getSavedEnvironmentRegistry();
}
return readBrowserSavedEnvironmentRegistry();
},
setSavedEnvironmentRegistry: async (records) => {
if (window.desktopBridge) {
return window.desktopBridge.setSavedEnvironmentRegistry(records);
}
writeBrowserSavedEnvironmentRegistry(records);
},
getSavedEnvironmentSecret: async (environmentId) => {
if (window.desktopBridge) {
return window.desktopBridge.getSavedEnvironmentSecret(environmentId);
}
return readBrowserSavedEnvironmentSecret(environmentId);
},
setSavedEnvironmentSecret: async (environmentId, secret) => {
if (window.desktopBridge) {
return window.desktopBridge.setSavedEnvironmentSecret(environmentId, secret);
}
return writeBrowserSavedEnvironmentSecret(environmentId, secret);
},
removeSavedEnvironmentSecret: async (environmentId) => {
if (window.desktopBridge) {
return window.desktopBridge.removeSavedEnvironmentSecret(environmentId);
}
removeBrowserSavedEnvironmentSecret(environmentId);
},
},
server: {
getConfig: rpcClient.server.getConfig,
refreshProviders: rpcClient.server.refreshProviders,
@@ -89,6 +142,8 @@ export function ensureLocalApi(): LocalApi {
export async function __resetLocalApiForTests() {
cachedApi = undefined;
const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");
__resetClientSettingsPersistenceForTests();
await resetEnvironmentServiceForTests();
resetGitStatusStateForTests();
resetRequestLatencyStateForTests();
+15 -1
View File
@@ -1,6 +1,20 @@
import { describe, expect, it } from "vitest";
import { resolveMarkdownFileLinkTarget } from "./markdown-links";
import { resolveMarkdownFileLinkTarget, rewriteMarkdownFileUriHref } from "./markdown-links";
describe("rewriteMarkdownFileUriHref", () => {
it("rewrites file uri hrefs into direct path hrefs", () => {
expect(rewriteMarkdownFileUriHref("file:///Users/julius/project/src/main.ts#L42")).toBe(
"/Users/julius/project/src/main.ts#L42",
);
});
it("preserves encoded octets so file paths are decoded only once later", () => {
expect(rewriteMarkdownFileUriHref("file:///Users/julius/project/file%2520name.md")).toBe(
"/Users/julius/project/file%2520name.md",
);
});
});
describe("resolveMarkdownFileLinkTarget", () => {
it("resolves absolute posix file paths", () => {
+18 -7
View File
@@ -38,25 +38,36 @@ function stripSearchAndHash(value: string): { path: string; hash: string } {
return { path, hash: rawHash };
}
function parseFileUrlHref(href: string): { path: string; hash: string } | null {
function parseFileUrlHref(
href: string,
options?: { readonly decodePath?: boolean },
): { path: string; hash: string } | null {
try {
const parsed = new URL(href);
if (parsed.protocol.toLowerCase() !== "file:") return null;
const decodedPath = safeDecode(parsed.pathname);
if (decodedPath.length === 0) return null;
const rawPath = parsed.pathname;
if (rawPath.length === 0) return null;
// Browser URL parser encodes "C:/foo" as "/C:/foo" for file URLs.
const normalizedPath = /^\/[A-Za-z]:[\\/]/.test(decodedPath)
? decodedPath.slice(1)
: decodedPath;
const normalizedPath = /^\/[A-Za-z]:[\\/]/.test(rawPath) ? rawPath.slice(1) : rawPath;
return { path: normalizedPath, hash: parsed.hash };
return {
path: options?.decodePath === false ? normalizedPath : safeDecode(normalizedPath),
hash: parsed.hash,
};
} catch {
return null;
}
}
export function rewriteMarkdownFileUriHref(href: string | undefined): string | null {
if (!href) return null;
const target = parseFileUrlHref(href.trim(), { decodePath: false });
if (!target) return null;
return `${target.path}${target.hash}`;
}
function looksLikePosixFilesystemPath(path: string): boolean {
if (!path.startsWith("/")) return false;
if (POSIX_FILE_ROOT_PREFIXES.some((prefix) => path.startsWith(prefix))) return true;
-2
View File
@@ -31,7 +31,6 @@ import {
} from "../rpc/serverState";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { syncBrowserChromeTheme } from "../hooks/useTheme";
import {
ensureEnvironmentConnectionBootstrapped,
@@ -213,7 +212,6 @@ function EventRouter() {
updatePrimaryEnvironmentDescriptor(payload.environment);
setActiveEnvironmentId(payload.environment.environmentId);
migrateLocalSettingsToServer();
void (async () => {
await ensureEnvironmentConnectionBootstrapped(payload.environment.environmentId);
if (disposedRef.current) {
+26 -4
View File
@@ -62,14 +62,36 @@ function defaultLifecycleHandlers(): Required<WsProtocolLifecycleHandlers> {
};
}
function composeLifecycleHandlers(
handlers?: WsProtocolLifecycleHandlers,
): Required<WsProtocolLifecycleHandlers> {
const defaults = defaultLifecycleHandlers();
return {
onAttempt: (socketUrl) => {
defaults.onAttempt(socketUrl);
handlers?.onAttempt?.(socketUrl);
},
onOpen: () => {
defaults.onOpen();
handlers?.onOpen?.();
},
onError: (message) => {
defaults.onError(message);
handlers?.onError?.(message);
},
onClose: (details) => {
defaults.onClose(details);
handlers?.onClose?.(details);
},
};
}
export function createWsRpcProtocolLayer(
url: WsRpcProtocolSocketUrlProvider,
handlers?: WsProtocolLifecycleHandlers,
) {
const lifecycle = {
...defaultLifecycleHandlers(),
...handlers,
};
const lifecycle = composeLifecycleHandlers(handlers);
const resolvedUrl =
typeof url === "function"
? Effect.promise(() => url()).pipe(
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
exhaustWsReconnectIfStillWaiting,
getWsConnectionStatus,
getWsReconnectDelayMsForRetry,
getWsConnectionUiState,
@@ -73,40 +72,4 @@ describe("wsConnectionState", () => {
reconnectPhase: "exhausted",
});
});
it("can exhaust a stalled final retry window when no new attempt starts", () => {
recordWsConnectionAttempt("ws://localhost:3020/ws");
recordWsConnectionOpened();
for (let attempt = 0; attempt < WS_RECONNECT_MAX_ATTEMPTS - 1; attempt += 1) {
recordWsConnectionAttempt("ws://localhost:3020/ws");
recordWsConnectionErrored("Unable to connect to the T3 server WebSocket.");
}
const finalRetryDelayMs = getWsReconnectDelayMsForRetry(WS_RECONNECT_MAX_ATTEMPTS - 2);
if (finalRetryDelayMs === null) {
throw new Error("Expected a final retry delay.");
}
const statusBeforeExhaust = getWsConnectionStatus();
expect(statusBeforeExhaust).toMatchObject({
nextRetryAt: new Date(Date.now() + finalRetryDelayMs).toISOString(),
reconnectAttemptCount: 7,
reconnectPhase: "waiting",
});
const nextRetryAt = statusBeforeExhaust.nextRetryAt;
if (!nextRetryAt) {
throw new Error("Expected a scheduled retry.");
}
vi.setSystemTime(new Date(Date.now() + finalRetryDelayMs + 1_000));
exhaustWsReconnectIfStillWaiting(nextRetryAt);
expect(getWsConnectionStatus()).toMatchObject({
nextRetryAt: null,
reconnectAttemptCount: WS_RECONNECT_MAX_ATTEMPTS,
reconnectPhase: "exhausted",
});
});
});
-20
View File
@@ -149,26 +149,6 @@ export function resetWsReconnectBackoff(): WsConnectionStatus {
}));
}
export function exhaustWsReconnectIfStillWaiting(expectedNextRetryAt: string): WsConnectionStatus {
return updateWsConnectionStatus((current) => {
if (
current.reconnectPhase !== "waiting" ||
current.nextRetryAt !== expectedNextRetryAt ||
!current.online ||
!current.hasConnected
) {
return current;
}
return {
...current,
nextRetryAt: null,
reconnectAttemptCount: current.reconnectMaxAttempts,
reconnectPhase: "exhausted",
};
});
}
export function resetWsConnectionStateForTests(): void {
appAtomRegistry.set(wsConnectionStatusAtom, INITIAL_WS_CONNECTION_STATUS);
}
+99 -16
View File
@@ -83,6 +83,7 @@ class MockWebSocket {
const originalWebSocket = globalThis.WebSocket;
const originalFetch = globalThis.fetch;
const transports: WsTransport[] = [];
function getSocket(): MockWebSocket {
const socket = sockets.at(-1);
@@ -107,9 +108,16 @@ async function waitFor(assertion: () => void, timeoutMs = 1_000): Promise<void>
}
}
function createTransport(...args: ConstructorParameters<typeof WsTransport>): WsTransport {
const transport = new WsTransport(...args);
transports.push(transport);
return transport;
}
beforeEach(() => {
vi.useRealTimers();
sockets.length = 0;
transports.length = 0;
resetRequestLatencyStateForTests();
resetWsConnectionStateForTests();
@@ -134,6 +142,8 @@ beforeEach(() => {
});
afterEach(async () => {
await Promise.allSettled(transports.map((transport) => transport.dispose()));
transports.length = 0;
globalThis.WebSocket = originalWebSocket;
globalThis.fetch = originalFetch;
resetRequestLatencyStateForTests();
@@ -144,7 +154,7 @@ afterEach(async () => {
describe("WsTransport", () => {
it("normalizes root websocket urls to /ws and preserves query params", async () => {
const transport = new WsTransport("ws://localhost:3020/?token=secret-token");
const transport = createTransport("ws://localhost:3020/?token=secret-token");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -155,7 +165,7 @@ describe("WsTransport", () => {
});
it("uses an explicit secure websocket base url", async () => {
const transport = new WsTransport("wss://app.example.com");
const transport = createTransport("wss://app.example.com");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -166,7 +176,7 @@ describe("WsTransport", () => {
});
it("uses an explicit insecure websocket base url for remote backends", async () => {
const transport = new WsTransport("ws://192.168.1.44:3773");
const transport = createTransport("ws://192.168.1.44:3773");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -177,7 +187,7 @@ describe("WsTransport", () => {
});
it("supports async websocket url providers", async () => {
const transport = new WsTransport(async () => "wss://remote.example.com/?wsToken=dynamic");
const transport = createTransport(async () => "wss://remote.example.com/?wsToken=dynamic");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -188,7 +198,7 @@ describe("WsTransport", () => {
});
it("tracks initial connection failures for the app error state", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -219,7 +229,7 @@ describe("WsTransport", () => {
});
it("surfaces reconnecting state after a live socket disconnects", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -248,8 +258,48 @@ describe("WsTransport", () => {
await transport.dispose();
});
it("composes custom lifecycle handlers with default websocket state tracking", async () => {
const onOpen = vi.fn();
const onClose = vi.fn();
const transport = createTransport("ws://localhost:3020", {
onOpen,
onClose,
});
await waitFor(() => {
expect(sockets).toHaveLength(1);
});
const socket = getSocket();
socket.open();
await waitFor(() => {
expect(onOpen).toHaveBeenCalledOnce();
expect(getWsConnectionStatus()).toMatchObject({
hasConnected: true,
phase: "connected",
});
});
socket.close(1012, "service restart");
await waitFor(() => {
expect(onClose).toHaveBeenCalledWith({
code: 1012,
reason: "service restart",
});
expect(getWsConnectionStatus()).toMatchObject({
attemptCount: 2,
closeReason: "service restart",
phase: "connecting",
});
}, 2_000);
await transport.dispose();
});
it("reconnects the websocket session without disposing the transport", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
await waitFor(() => {
expect(sockets).toHaveLength(1);
@@ -314,7 +364,7 @@ describe("WsTransport", () => {
it("marks unary requests as slow until the first server ack arrives", async () => {
const slowAckThresholdMs = 25;
setSlowRpcAckThresholdMsForTests(slowAckThresholdMs);
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const requestPromise = transport.request((client) =>
client[WS_METHODS.serverUpsertKeybinding]({
@@ -368,7 +418,7 @@ describe("WsTransport", () => {
}, 5_000);
it("sends unary RPC requests and resolves successful exits", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const requestPromise = transport.request((client) =>
client[WS_METHODS.serverUpsertKeybinding]({
@@ -426,7 +476,7 @@ describe("WsTransport", () => {
});
it("delivers stream chunks to subscribers", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const listener = vi.fn();
const unsubscribe = transport.subscribe(
@@ -481,7 +531,7 @@ describe("WsTransport", () => {
});
it("re-subscribes stream listeners after the stream exits", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const listener = vi.fn();
const onResubscribe = vi.fn();
@@ -590,7 +640,7 @@ describe("WsTransport", () => {
});
it("does not fire onResubscribe when the first stream attempt exits before any value", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const listener = vi.fn();
const onResubscribe = vi.fn();
@@ -636,7 +686,7 @@ describe("WsTransport", () => {
});
it("does not retry stream subscriptions after application-level failures", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
let attempts = 0;
@@ -675,7 +725,7 @@ describe("WsTransport", () => {
});
it("keeps retrying stream subscriptions after transport failures", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
let attempts = 0;
@@ -707,8 +757,41 @@ describe("WsTransport", () => {
await transport.dispose();
});
it("logs a transport disconnect once even when multiple subscriptions fail together", async () => {
const transport = createTransport("ws://localhost:3020");
const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined);
const unsubscribeA = transport.subscribe(
() => Stream.fail(new Error("SocketCloseError: 1006")),
vi.fn(),
{ retryDelay: 10 },
);
const unsubscribeB = transport.subscribe(
() => Stream.fail(new Error("SocketCloseError: 1006")),
vi.fn(),
{ retryDelay: 10 },
);
await waitFor(() => {
expect(sockets).toHaveLength(1);
});
getSocket().open();
await waitFor(() => {
expect(warnSpy).toHaveBeenCalledTimes(1);
});
expect(warnSpy).toHaveBeenCalledWith("WebSocket RPC subscription disconnected", {
error: "SocketCloseError: 1006",
});
unsubscribeA();
unsubscribeB();
await transport.dispose();
});
it("streams finite request events without re-subscribing", async () => {
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const listener = vi.fn();
await waitFor(() => {
@@ -824,7 +907,7 @@ describe("WsTransport", () => {
exportIntervalMs: 10,
});
const transport = new WsTransport("ws://localhost:3020");
const transport = createTransport("ws://localhost:3020");
const requestPromise = transport.request((client) => client[WS_METHODS.serverGetSettings]({}));
await waitFor(() => {
+8 -3
View File
@@ -50,6 +50,7 @@ export class WsTransport {
private readonly url: WsRpcProtocolSocketUrlProvider;
private readonly lifecycleHandlers: WsProtocolLifecycleHandlers | undefined;
private disposed = false;
private hasReportedTransportDisconnect = false;
private reconnectChain: Promise<void> = Promise.resolve();
private session: TransportSession;
@@ -136,6 +137,7 @@ export class WsTransport {
listener,
() => active,
() => {
this.hasReportedTransportDisconnect = false;
hasReceivedValue = true;
},
);
@@ -156,9 +158,12 @@ export class WsTransport {
return;
}
console.warn("WebSocket RPC subscription disconnected", {
error: formattedError,
});
if (!this.hasReportedTransportDisconnect) {
console.warn("WebSocket RPC subscription disconnected", {
error: formattedError,
});
}
this.hasReportedTransportDisconnect = true;
await sleep(retryDelayMs);
}
}
+51 -2
View File
@@ -1,3 +1,4 @@
import { scopeThreadRef } from "@t3tools/client-runtime";
import {
CheckpointRef,
DEFAULT_MODEL_BY_PROVIDER,
@@ -17,6 +18,7 @@ import {
applyOrchestrationEvents,
selectEnvironmentState,
selectProjectsAcrossEnvironments,
setThreadBranch,
selectThreadsAcrossEnvironments,
syncServerReadModel,
type AppState,
@@ -25,6 +27,7 @@ import {
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
const localEnvironmentId = EnvironmentId.makeUnsafe("environment-local");
const remoteEnvironmentId = EnvironmentId.makeUnsafe("environment-remote");
function withActiveEnvironmentState(
environmentState: EnvironmentState,
@@ -86,7 +89,7 @@ function makeState(thread: Thread): AppState {
const projectId = ProjectId.makeUnsafe("project-1");
const project = {
id: projectId,
environmentId: localEnvironmentId,
environmentId: thread.environmentId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
@@ -171,7 +174,9 @@ function makeState(thread: Thread): AppState {
sidebarThreadSummaryById: {},
bootstrapComplete: true,
};
return withActiveEnvironmentState(environmentState);
return withActiveEnvironmentState(environmentState, {
activeEnvironmentId: thread.environmentId,
});
}
function makeEmptyState(overrides: Partial<AppState & EnvironmentState> = {}): AppState {
@@ -201,6 +206,10 @@ function localEnvironmentStateOf(state: AppState): EnvironmentState {
return selectEnvironmentState(state, localEnvironmentId);
}
function environmentStateOf(state: AppState, environmentId: EnvironmentId): EnvironmentState {
return selectEnvironmentState(state, environmentId);
}
function projectsOf(state: AppState) {
return selectProjectsAcrossEnvironments(state);
}
@@ -305,6 +314,46 @@ function makeReadModelProject(
};
}
describe("setThreadBranch", () => {
it("updates only the scoped thread environment", () => {
const sharedThreadId = ThreadId.makeUnsafe("thread-shared");
const localThread = makeThread({
id: sharedThreadId,
environmentId: localEnvironmentId,
branch: "local-branch",
});
const remoteThread = makeThread({
id: sharedThreadId,
environmentId: remoteEnvironmentId,
branch: "remote-branch",
});
const state: AppState = {
activeEnvironmentId: localEnvironmentId,
environmentStateById: {
[localEnvironmentId]: environmentStateOf(makeState(localThread), localEnvironmentId),
[remoteEnvironmentId]: environmentStateOf(makeState(remoteThread), remoteEnvironmentId),
},
};
const next = setThreadBranch(
state,
scopeThreadRef(remoteEnvironmentId, sharedThreadId),
"remote-next",
"/tmp/remote-worktree",
);
expect(
environmentStateOf(next, localEnvironmentId).threadShellById[sharedThreadId]?.branch,
).toBe("local-branch");
expect(
environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.branch,
).toBe("remote-next");
expect(
environmentStateOf(next, remoteEnvironmentId).threadShellById[sharedThreadId]?.worktreePath,
).toBe("/tmp/remote-worktree");
});
});
describe("store read model sync", () => {
it("marks bootstrap complete after snapshot sync", () => {
const initialState = withActiveEnvironmentState(
+11 -11
View File
@@ -1737,17 +1737,13 @@ export function setActiveEnvironmentId(state: AppState, environmentId: Environme
export function setThreadBranch(
state: AppState,
threadId: ThreadId,
threadRef: ScopedThreadRef,
branch: string | null,
worktreePath: string | null,
): AppState {
if (state.activeEnvironmentId === null) {
return state;
}
const nextEnvironmentState = updateThreadState(
getStoredEnvironmentState(state, state.activeEnvironmentId),
threadId,
getStoredEnvironmentState(state, threadRef.environmentId),
threadRef.threadId,
(thread) => {
if (thread.branch === branch && thread.worktreePath === worktreePath) return thread;
const cwdChanged = thread.worktreePath !== worktreePath;
@@ -1759,7 +1755,7 @@ export function setThreadBranch(
};
},
);
return commitEnvironmentState(state, state.activeEnvironmentId, nextEnvironmentState);
return commitEnvironmentState(state, threadRef.environmentId, nextEnvironmentState);
}
interface AppStore extends AppState {
@@ -1771,7 +1767,11 @@ interface AppStore extends AppState {
environmentId: EnvironmentId,
) => void;
setError: (threadId: ThreadId, error: string | null) => void;
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
setThreadBranch: (
threadRef: ScopedThreadRef,
branch: string | null,
worktreePath: string | null,
) => void;
}
export const useStore = create<AppStore>((set) => ({
@@ -1785,6 +1785,6 @@ export const useStore = create<AppStore>((set) => ({
applyOrchestrationEvents: (events, environmentId) =>
set((state) => applyOrchestrationEvents(state, events, environmentId)),
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
setThreadBranch: (threadId, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
setThreadBranch: (threadRef, branch, worktreePath) =>
set((state) => setThreadBranch(state, threadRef, branch, worktreePath)),
}));
+2
View File
@@ -7,6 +7,7 @@ import pkg from "./package.json" with { type: "json" };
const port = Number(process.env.PORT ?? 5733);
const host = process.env.HOST?.trim() || "localhost";
const configuredHttpUrl = process.env.VITE_HTTP_URL?.trim();
const configuredWsUrl = process.env.VITE_WS_URL?.trim();
const sourcemapEnv = process.env.T3CODE_WEB_SOURCEMAP?.trim().toLowerCase();
@@ -58,6 +59,7 @@ export default defineConfig({
include: ["@pierre/diffs", "@pierre/diffs/react", "@pierre/diffs/worker/worker.js"],
},
define: {
"import.meta.env.VITE_HTTP_URL": JSON.stringify(configuredHttpUrl ?? ""),
// In dev mode, tell the web app where the WebSocket server lives
"import.meta.env.VITE_WS_URL": JSON.stringify(configuredWsUrl ?? ""),
"import.meta.env.APP_VERSION": JSON.stringify(pkg.version),
+2
View File
@@ -185,6 +185,7 @@
"node-pty",
],
"overrides": {
"@effect/platform-node-shared": "catalog:",
"vite": "^8.0.0",
},
"catalog": {
@@ -192,6 +193,7 @@
"@effect/language-service": "0.84.2",
"@effect/platform-bun": "4.0.0-beta.43",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/platform-node-shared": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@types/bun": "^1.3.9",
+2
View File
@@ -12,6 +12,7 @@
"@effect/atom-react": "4.0.0-beta.43",
"@effect/platform-bun": "4.0.0-beta.43",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/platform-node-shared": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@effect/language-service": "0.84.2",
@@ -61,6 +62,7 @@
"vitest": "catalog:"
},
"overrides": {
"@effect/platform-node-shared": "catalog:",
"vite": "^8.0.0"
},
"engines": {
+31 -1
View File
@@ -49,8 +49,9 @@ import type {
OrchestrationEvent,
OrchestrationReadModel,
} from "./orchestration";
import type { EnvironmentId } from "./baseSchemas";
import { EditorId } from "./editor";
import { ServerSettings, ServerSettingsPatch } from "./settings";
import { ClientSettings, ServerSettings, ServerSettingsPatch } from "./settings";
export interface ContextMenuItem<T extends string = string> {
id: T;
@@ -112,6 +113,15 @@ export interface DesktopEnvironmentBootstrap {
bootstrapToken?: string;
}
export interface PersistedSavedEnvironmentRecord {
environmentId: EnvironmentId;
label: string;
wsBaseUrl: string;
httpBaseUrl: string;
createdAt: string;
lastConnectedAt: string | null;
}
export type DesktopServerExposureMode = "local-only" | "network-accessible";
export interface DesktopServerExposureState {
@@ -122,6 +132,15 @@ export interface DesktopServerExposureState {
export interface DesktopBridge {
getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null;
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
getSavedEnvironmentRegistry: () => Promise<readonly PersistedSavedEnvironmentRecord[]>;
setSavedEnvironmentRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Promise<void>;
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
getServerExposureState: () => Promise<DesktopServerExposureState>;
setServerExposureMode: (mode: DesktopServerExposureMode) => Promise<DesktopServerExposureState>;
pickFolder: () => Promise<string | null>;
@@ -165,6 +184,17 @@ export interface LocalApi {
position?: { x: number; y: number },
) => Promise<T | null>;
};
persistence: {
getClientSettings: () => Promise<ClientSettings | null>;
setClientSettings: (settings: ClientSettings) => Promise<void>;
getSavedEnvironmentRegistry: () => Promise<readonly PersistedSavedEnvironmentRecord[]>;
setSavedEnvironmentRegistry: (
records: readonly PersistedSavedEnvironmentRecord[],
) => Promise<void>;
getSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<string | null>;
setSavedEnvironmentSecret: (environmentId: EnvironmentId, secret: string) => Promise<boolean>;
removeSavedEnvironmentSecret: (environmentId: EnvironmentId) => Promise<void>;
};
server: {
getConfig: () => Promise<ServerConfig>;
refreshProviders: () => Promise<ServerProviderUpdatedPayload>;
+4
View File
@@ -51,6 +51,10 @@
"./projectScripts": {
"types": "./src/projectScripts.ts",
"import": "./src/projectScripts.ts"
},
"./qrCode": {
"types": "./src/qrCode.ts",
"import": "./src/qrCode.ts"
}
},
"scripts": {
+984
View File
@@ -0,0 +1,984 @@
// @ts-nocheck
/* oxlint-disable eslint/no-useless-escape */
/*
* QR Code generator library (TypeScript)
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/qr-code-generator-library
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* - The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* - The Software is provided "as is", without warranty of any kind, express or
* implied, including but not limited to the warranties of merchantability,
* fitness for a particular purpose and noninfringement. In no event shall the
* authors or copyright holders be liable for any claim, damages or other
* liability, whether in an action of contract, tort or otherwise, arising from,
* out of or in connection with the Software or the use or other dealings in the
* Software.
*/
"use strict";
namespace qrcodegen {
type bit = number;
type byte = number;
type int = number;
/*---- QR Code symbol class ----*/
/*
* A QR Code symbol, which is a type of two-dimension barcode.
* Invented by Denso Wave and described in the ISO/IEC 18004 standard.
* Instances of this class represent an immutable square grid of dark and light cells.
* The class provides static factory functions to create a QR Code from text or binary data.
* The class covers the QR Code Model 2 specification, supporting all versions (sizes)
* from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
*
* Ways to create a QR Code object:
* - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
* - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
* - Low level: Custom-make the array of data codeword bytes (including
* segment headers and final padding, excluding error correction codewords),
* supply the appropriate version number, and call the QrCode() constructor.
* (Note that all ways require supplying the desired error correction level.)
*/
export class QrCode {
/*-- Static factory functions (high level) --*/
// Returns a QR Code representing the given Unicode text string at the given error correction level.
// As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
// Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
// QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
// ecl argument if it can be done without increasing the version.
public static encodeText(text: string, ecl: QrCode.Ecc): QrCode {
const segs: Array<QrSegment> = qrcodegen.QrSegment.makeSegments(text);
return QrCode.encodeSegments(segs, ecl);
}
// Returns a QR Code representing the given binary data at the given error correction level.
// This function always encodes using the binary segment mode, not any text mode. The maximum number of
// bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
// The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
public static encodeBinary(data: Readonly<Array<byte>>, ecl: QrCode.Ecc): QrCode {
const seg: QrSegment = qrcodegen.QrSegment.makeBytes(data);
return QrCode.encodeSegments([seg], ecl);
}
/*-- Static factory functions (mid level) --*/
// Returns a QR Code representing the given segments with the given encoding parameters.
// The smallest possible QR Code version within the given range is automatically
// chosen for the output. Iff boostEcl is true, then the ECC level of the result
// may be higher than the ecl argument if it can be done without increasing the
// version. The mask number is either between 0 to 7 (inclusive) to force that
// mask, or -1 to automatically choose an appropriate mask (which may be slow).
// This function allows the user to create a custom sequence of segments that switches
// between modes (such as alphanumeric and byte) to encode text in less space.
// This is a mid-level API; the high-level API is encodeText() and encodeBinary().
public static encodeSegments(
segs: Readonly<Array<QrSegment>>,
ecl: QrCode.Ecc,
minVersion: int = 1,
maxVersion: int = 40,
mask: int = -1,
boostEcl: boolean = true,
): QrCode {
if (
!(
QrCode.MIN_VERSION <= minVersion &&
minVersion <= maxVersion &&
maxVersion <= QrCode.MAX_VERSION
) ||
mask < -1 ||
mask > 7
)
throw new RangeError("Invalid value");
// Find the minimal version number to use
let version: int;
let dataUsedBits: int;
for (version = minVersion; ; version++) {
const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
const usedBits: number = QrSegment.getTotalBits(segs, version);
if (usedBits <= dataCapacityBits) {
dataUsedBits = usedBits;
break; // This version number is found to be suitable
}
if (version >= maxVersion)
// All versions in the range could not fit the given data
throw new RangeError("Data too long");
}
// Increase the error correction level while the data still fits in the current version number
for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) {
// From low to high
if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
ecl = newEcl;
}
// Concatenate all segments to create the data bit string
let bb: Array<bit> = [];
for (const seg of segs) {
appendBits(seg.mode.modeBits, 4, bb);
appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
for (const b of seg.getData()) bb.push(b);
}
assert(bb.length == dataUsedBits);
// Add terminator and pad up to a byte if applicable
const dataCapacityBits: int = QrCode.getNumDataCodewords(version, ecl) * 8;
assert(bb.length <= dataCapacityBits);
appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
appendBits(0, (8 - (bb.length % 8)) % 8, bb);
assert(bb.length % 8 == 0);
// Pad with alternating bytes until data capacity is reached
for (let padByte = 0xec; bb.length < dataCapacityBits; padByte ^= 0xec ^ 0x11)
appendBits(padByte, 8, bb);
// Pack bits into bytes in big endian
let dataCodewords: Array<byte> = [];
while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);
bb.forEach((b: bit, i: int) => (dataCodewords[i >>> 3] |= b << (7 - (i & 7))));
// Create the QR Code object
return new QrCode(version, ecl, dataCodewords, mask);
}
/*-- Fields --*/
// The width and height of this QR Code, measured in modules, between
// 21 and 177 (inclusive). This is equal to version * 4 + 17.
public readonly size: int;
// The index of the mask pattern used in this QR Code, which is between 0 and 7 (inclusive).
// Even if a QR Code is created with automatic masking requested (mask = -1),
// the resulting object still has a mask value between 0 and 7.
public readonly mask: int;
// The modules of this QR Code (false = light, true = dark).
// Immutable after constructor finishes. Accessed through getModule().
private readonly modules: Array<Array<boolean>> = [];
// Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
private readonly isFunction: Array<Array<boolean>> = [];
/*-- Constructor (low level) and fields --*/
// Creates a new QR Code with the given version number,
// error correction level, data codeword bytes, and mask number.
// This is a low-level API that most users should not use directly.
// A mid-level API is the encodeSegments() function.
public constructor(
// The version number of this QR Code, which is between 1 and 40 (inclusive).
// This determines the size of this barcode.
public readonly version: int,
// The error correction level used in this QR Code.
public readonly errorCorrectionLevel: QrCode.Ecc,
dataCodewords: Readonly<Array<byte>>,
msk: int,
) {
// Check scalar arguments
if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
throw new RangeError("Version value out of range");
if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");
this.size = version * 4 + 17;
// Initialize both grids to be size*size arrays of Boolean false
let row: Array<boolean> = [];
for (let i = 0; i < this.size; i++) row.push(false);
for (let i = 0; i < this.size; i++) {
this.modules.push(row.slice()); // Initially all light
this.isFunction.push(row.slice());
}
// Compute ECC, draw modules
this.drawFunctionPatterns();
const allCodewords: Array<byte> = this.addEccAndInterleave(dataCodewords);
this.drawCodewords(allCodewords);
// Do masking
if (msk == -1) {
// Automatically choose best mask
let minPenalty: int = 1000000000;
for (let i = 0; i < 8; i++) {
this.applyMask(i);
this.drawFormatBits(i);
const penalty: int = this.getPenaltyScore();
if (penalty < minPenalty) {
msk = i;
minPenalty = penalty;
}
this.applyMask(i); // Undoes the mask due to XOR
}
}
assert(0 <= msk && msk <= 7);
this.mask = msk;
this.applyMask(msk); // Apply the final choice of mask
this.drawFormatBits(msk); // Overwrite old format bits
this.isFunction = [];
}
/*-- Accessor methods --*/
// Returns the color of the module (pixel) at the given coordinates, which is false
// for light or true for dark. The top left corner has the coordinates (x=0, y=0).
// If the given coordinates are out of bounds, then false (light) is returned.
public getModule(x: int, y: int): boolean {
return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
}
/*-- Private helper methods for constructor: Drawing function modules --*/
// Reads this object's version field, and draws and marks all function modules.
private drawFunctionPatterns(): void {
// Draw horizontal and vertical timing patterns
for (let i = 0; i < this.size; i++) {
this.setFunctionModule(6, i, i % 2 == 0);
this.setFunctionModule(i, 6, i % 2 == 0);
}
// Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
this.drawFinderPattern(3, 3);
this.drawFinderPattern(this.size - 4, 3);
this.drawFinderPattern(3, this.size - 4);
// Draw numerous alignment patterns
const alignPatPos: Array<int> = this.getAlignmentPatternPositions();
const numAlign: int = alignPatPos.length;
for (let i = 0; i < numAlign; i++) {
for (let j = 0; j < numAlign; j++) {
// Don't draw on the three finder corners
if (
!((i == 0 && j == 0) || (i == 0 && j == numAlign - 1) || (i == numAlign - 1 && j == 0))
)
this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
}
}
// Draw configuration data
this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
this.drawVersion();
}
// Draws two copies of the format bits (with its own error correction code)
// based on the given mask and this object's error correction level field.
private drawFormatBits(mask: int): void {
// Calculate error correction code and pack bits
const data: int = (this.errorCorrectionLevel.formatBits << 3) | mask; // errCorrLvl is uint2, mask is uint3
let rem: int = data;
for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
const bits = ((data << 10) | rem) ^ 0x5412; // uint15
assert(bits >>> 15 == 0);
// Draw first copy
for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));
this.setFunctionModule(8, 7, getBit(bits, 6));
this.setFunctionModule(8, 8, getBit(bits, 7));
this.setFunctionModule(7, 8, getBit(bits, 8));
for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));
// Draw second copy
for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
this.setFunctionModule(8, this.size - 8, true); // Always dark
}
// Draws two copies of the version bits (with its own error correction code),
// based on this object's version field, iff 7 <= version <= 40.
private drawVersion(): void {
if (this.version < 7) return;
// Calculate error correction code and pack bits
let rem: int = this.version; // version is uint6, in the range [7, 40]
for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
const bits: int = (this.version << 12) | rem; // uint18
assert(bits >>> 18 == 0);
// Draw two copies
for (let i = 0; i < 18; i++) {
const color: boolean = getBit(bits, i);
const a: int = this.size - 11 + (i % 3);
const b: int = Math.floor(i / 3);
this.setFunctionModule(a, b, color);
this.setFunctionModule(b, a, color);
}
}
// Draws a 9*9 finder pattern including the border separator,
// with the center module at (x, y). Modules can be out of bounds.
private drawFinderPattern(x: int, y: int): void {
for (let dy = -4; dy <= 4; dy++) {
for (let dx = -4; dx <= 4; dx++) {
const dist: int = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
const xx: int = x + dx;
const yy: int = y + dy;
if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
}
}
}
// Draws a 5*5 alignment pattern, with the center module
// at (x, y). All modules must be in bounds.
private drawAlignmentPattern(x: int, y: int): void {
for (let dy = -2; dy <= 2; dy++) {
for (let dx = -2; dx <= 2; dx++)
this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
}
}
// Sets the color of a module and marks it as a function module.
// Only used by the constructor. Coordinates must be in bounds.
private setFunctionModule(x: int, y: int, isDark: boolean): void {
this.modules[y][x] = isDark;
this.isFunction[y][x] = true;
}
/*-- Private helper methods for constructor: Codewords and masking --*/
// Returns a new byte string representing the given data with the appropriate error correction
// codewords appended to it, based on this object's version and error correction level.
private addEccAndInterleave(data: Readonly<Array<byte>>): Array<byte> {
const ver: int = this.version;
const ecl: QrCode.Ecc = this.errorCorrectionLevel;
if (data.length != QrCode.getNumDataCodewords(ver, ecl))
throw new RangeError("Invalid argument");
// Calculate parameter numbers
const numBlocks: int = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
const blockEccLen: int = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
const rawCodewords: int = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
const numShortBlocks: int = numBlocks - (rawCodewords % numBlocks);
const shortBlockLen: int = Math.floor(rawCodewords / numBlocks);
// Split data into blocks and append ECC to each block
let blocks: Array<Array<byte>> = [];
const rsDiv: Array<byte> = QrCode.reedSolomonComputeDivisor(blockEccLen);
for (let i = 0, k = 0; i < numBlocks; i++) {
let dat: Array<byte> = data.slice(
k,
k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1),
);
k += dat.length;
const ecc: Array<byte> = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
if (i < numShortBlocks) dat.push(0);
blocks.push(dat.concat(ecc));
}
// Interleave (not concatenate) the bytes from every block into a single sequence
let result: Array<byte> = [];
for (let i = 0; i < blocks[0].length; i++) {
blocks.forEach((block, j) => {
// Skip the padding byte in short blocks
if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]);
});
}
assert(result.length == rawCodewords);
return result;
}
// Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
// data area of this QR Code. Function modules need to be marked off before this is called.
private drawCodewords(data: Readonly<Array<byte>>): void {
if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
throw new RangeError("Invalid argument");
let i: int = 0; // Bit index into the data
// Do the funny zigzag scan
for (let right = this.size - 1; right >= 1; right -= 2) {
// Index of right column in each column pair
if (right == 6) right = 5;
for (let vert = 0; vert < this.size; vert++) {
// Vertical counter
for (let j = 0; j < 2; j++) {
const x: int = right - j; // Actual x coordinate
const upward: boolean = ((right + 1) & 2) == 0;
const y: int = upward ? this.size - 1 - vert : vert; // Actual y coordinate
if (!this.isFunction[y][x] && i < data.length * 8) {
this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
i++;
}
// If this QR Code has any remainder bits (0 to 7), they were assigned as
// 0/false/light by the constructor and are left unchanged by this method
}
}
}
assert(i == data.length * 8);
}
// XORs the codeword modules in this QR Code with the given mask pattern.
// The function modules must be marked and the codeword bits must be drawn
// before masking. Due to the arithmetic of XOR, calling applyMask() with
// the same mask value a second time will undo the mask. A final well-formed
// QR Code needs exactly one (not zero, two, etc.) mask applied.
private applyMask(mask: int): void {
if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");
for (let y = 0; y < this.size; y++) {
for (let x = 0; x < this.size; x++) {
let invert: boolean;
switch (mask) {
case 0:
invert = (x + y) % 2 == 0;
break;
case 1:
invert = y % 2 == 0;
break;
case 2:
invert = x % 3 == 0;
break;
case 3:
invert = (x + y) % 3 == 0;
break;
case 4:
invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
break;
case 5:
invert = ((x * y) % 2) + ((x * y) % 3) == 0;
break;
case 6:
invert = (((x * y) % 2) + ((x * y) % 3)) % 2 == 0;
break;
case 7:
invert = (((x + y) % 2) + ((x * y) % 3)) % 2 == 0;
break;
default:
throw new Error("Unreachable");
}
if (!this.isFunction[y][x] && invert) this.modules[y][x] = !this.modules[y][x];
}
}
}
// Calculates and returns the penalty score based on state of this QR Code's current modules.
// This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
private getPenaltyScore(): int {
let result: int = 0;
// Adjacent modules in row having same color, and finder-like patterns
for (let y = 0; y < this.size; y++) {
let runColor = false;
let runX = 0;
let runHistory = [0, 0, 0, 0, 0, 0, 0];
for (let x = 0; x < this.size; x++) {
if (this.modules[y][x] == runColor) {
runX++;
if (runX == 5) result += QrCode.PENALTY_N1;
else if (runX > 5) result++;
} else {
this.finderPenaltyAddHistory(runX, runHistory);
if (!runColor)
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
runColor = this.modules[y][x];
runX = 1;
}
}
result +=
this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
}
// Adjacent modules in column having same color, and finder-like patterns
for (let x = 0; x < this.size; x++) {
let runColor = false;
let runY = 0;
let runHistory = [0, 0, 0, 0, 0, 0, 0];
for (let y = 0; y < this.size; y++) {
if (this.modules[y][x] == runColor) {
runY++;
if (runY == 5) result += QrCode.PENALTY_N1;
else if (runY > 5) result++;
} else {
this.finderPenaltyAddHistory(runY, runHistory);
if (!runColor)
result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
runColor = this.modules[y][x];
runY = 1;
}
}
result +=
this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
}
// 2*2 blocks of modules having same color
for (let y = 0; y < this.size - 1; y++) {
for (let x = 0; x < this.size - 1; x++) {
const color: boolean = this.modules[y][x];
if (
color == this.modules[y][x + 1] &&
color == this.modules[y + 1][x] &&
color == this.modules[y + 1][x + 1]
)
result += QrCode.PENALTY_N2;
}
}
// Balance of dark and light modules
let dark: int = 0;
for (const row of this.modules)
dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
const total: int = this.size * this.size; // Note that size is odd, so dark/total != 1/2
// Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
const k: int = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
assert(0 <= k && k <= 9);
result += k * QrCode.PENALTY_N4;
assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
return result;
}
/*-- Private helper functions --*/
// Returns an ascending list of positions of alignment patterns for this version number.
// Each position is in the range [0,177), and are used on both the x and y axes.
// This could be implemented as lookup table of 40 variable-length lists of integers.
private getAlignmentPatternPositions(): Array<int> {
if (this.version == 1) return [];
else {
const numAlign: int = Math.floor(this.version / 7) + 2;
const step: int =
this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
let result: Array<int> = [6];
for (let pos = this.size - 7; result.length < numAlign; pos -= step)
result.splice(1, 0, pos);
return result;
}
}
// Returns the number of data bits that can be stored in a QR Code of the given version number, after
// all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
// The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
private static getNumRawDataModules(ver: int): int {
if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
throw new RangeError("Version number out of range");
let result: int = (16 * ver + 128) * ver + 64;
if (ver >= 2) {
const numAlign: int = Math.floor(ver / 7) + 2;
result -= (25 * numAlign - 10) * numAlign - 55;
if (ver >= 7) result -= 36;
}
assert(208 <= result && result <= 29648);
return result;
}
// Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
// QR Code of the given version number and error correction level, with remainder bits discarded.
// This stateless pure function could be implemented as a (40*4)-cell lookup table.
private static getNumDataCodewords(ver: int, ecl: QrCode.Ecc): int {
return (
Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver]
);
}
// Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
// implemented as a lookup table over all possible parameter values, instead of as an algorithm.
private static reedSolomonComputeDivisor(degree: int): Array<byte> {
if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");
// Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
// For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
let result: Array<byte> = [];
for (let i = 0; i < degree - 1; i++) result.push(0);
result.push(1); // Start off with the monomial x^0
// Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
// and drop the highest monomial term which is always 1x^degree.
// Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
let root = 1;
for (let i = 0; i < degree; i++) {
// Multiply the current product by (x - r^i)
for (let j = 0; j < result.length; j++) {
result[j] = QrCode.reedSolomonMultiply(result[j], root);
if (j + 1 < result.length) result[j] ^= result[j + 1];
}
root = QrCode.reedSolomonMultiply(root, 0x02);
}
return result;
}
// Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
private static reedSolomonComputeRemainder(
data: Readonly<Array<byte>>,
divisor: Readonly<Array<byte>>,
): Array<byte> {
let result: Array<byte> = divisor.map((_) => 0);
for (const b of data) {
// Polynomial division
const factor: byte = b ^ (result.shift() as byte);
result.push(0);
divisor.forEach((coef, i) => (result[i] ^= QrCode.reedSolomonMultiply(coef, factor)));
}
return result;
}
// Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
// are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
private static reedSolomonMultiply(x: byte, y: byte): byte {
if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");
// Russian peasant multiplication
let z: int = 0;
for (let i = 7; i >= 0; i--) {
z = (z << 1) ^ ((z >>> 7) * 0x11d);
z ^= ((y >>> i) & 1) * x;
}
assert(z >>> 8 == 0);
return z as byte;
}
// Can only be called immediately after a light run is added, and
// returns either 0, 1, or 2. A helper function for getPenaltyScore().
private finderPenaltyCountPatterns(runHistory: Readonly<Array<int>>): int {
const n: int = runHistory[1];
assert(n <= this.size * 3);
const core: boolean =
n > 0 &&
runHistory[2] == n &&
runHistory[3] == n * 3 &&
runHistory[4] == n &&
runHistory[5] == n;
return (
(core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +
(core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0)
);
}
// Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
private finderPenaltyTerminateAndCount(
currentRunColor: boolean,
currentRunLength: int,
runHistory: Array<int>,
): int {
if (currentRunColor) {
// Terminate dark run
this.finderPenaltyAddHistory(currentRunLength, runHistory);
currentRunLength = 0;
}
currentRunLength += this.size; // Add light border to final run
this.finderPenaltyAddHistory(currentRunLength, runHistory);
return this.finderPenaltyCountPatterns(runHistory);
}
// Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
private finderPenaltyAddHistory(currentRunLength: int, runHistory: Array<int>): void {
if (runHistory[0] == 0) currentRunLength += this.size; // Add light border to initial run
runHistory.pop();
runHistory.unshift(currentRunLength);
}
/*-- Constants and tables --*/
// The minimum version number supported in the QR Code Model 2 standard.
public static readonly MIN_VERSION: int = 1;
// The maximum version number supported in the QR Code Model 2 standard.
public static readonly MAX_VERSION: int = 40;
// For use in getPenaltyScore(), when evaluating which mask is best.
private static readonly PENALTY_N1: int = 3;
private static readonly PENALTY_N2: int = 3;
private static readonly PENALTY_N3: int = 40;
private static readonly PENALTY_N4: int = 10;
private static readonly ECC_CODEWORDS_PER_BLOCK: Array<Array<int>> = [
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
[
-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28,
30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
], // Low
[
-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
], // Medium
[
-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30,
30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
], // Quartile
[
-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24,
30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
], // High
];
private static readonly NUM_ERROR_CORRECTION_BLOCKS: Array<Array<int>> = [
// Version: (note that index 0 is for padding, and is set to an illegal value)
//0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
[
-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13,
14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25,
], // Low
[
-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21,
23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49,
], // Medium
[
-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29,
34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68,
], // Quartile
[
-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32,
35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81,
], // High
];
}
// Appends the given number of low-order bits of the given value
// to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
function appendBits(val: int, len: int, bb: Array<bit>): void {
if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");
for (
let i = len - 1;
i >= 0;
i-- // Append bit by bit
)
bb.push((val >>> i) & 1);
}
// Returns true iff the i'th bit of x is set to 1.
function getBit(x: int, i: int): boolean {
return ((x >>> i) & 1) != 0;
}
// Throws an exception if the given condition is false.
function assert(cond: boolean): void {
if (!cond) throw new Error("Assertion error");
}
/*---- Data segment class ----*/
/*
* A segment of character/binary/control data in a QR Code symbol.
* Instances of this class are immutable.
* The mid-level way to create a segment is to take the payload data
* and call a static factory function such as QrSegment.makeNumeric().
* The low-level way to create a segment is to custom-make the bit buffer
* and call the QrSegment() constructor with appropriate values.
* This segment class imposes no length restrictions, but QR Codes have restrictions.
* Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
* Any segment longer than this is meaningless for the purpose of generating QR Codes.
*/
export class QrSegment {
/*-- Static factory functions (mid level) --*/
// Returns a segment representing the given binary data encoded in
// byte mode. All input byte arrays are acceptable. Any text string
// can be converted to UTF-8 bytes and encoded as a byte mode segment.
public static makeBytes(data: Readonly<Array<byte>>): QrSegment {
let bb: Array<bit> = [];
for (const b of data) appendBits(b, 8, bb);
return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
}
// Returns a segment representing the given string of decimal digits encoded in numeric mode.
public static makeNumeric(digits: string): QrSegment {
if (!QrSegment.isNumeric(digits))
throw new RangeError("String contains non-numeric characters");
let bb: Array<bit> = [];
for (let i = 0; i < digits.length; ) {
// Consume up to 3 digits per iteration
const n: int = Math.min(digits.length - i, 3);
appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
i += n;
}
return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
}
// Returns a segment representing the given text string encoded in alphanumeric mode.
// The characters allowed are: 0 to 9, A to Z (uppercase only), space,
// dollar, percent, asterisk, plus, hyphen, period, slash, colon.
public static makeAlphanumeric(text: string): QrSegment {
if (!QrSegment.isAlphanumeric(text))
throw new RangeError("String contains unencodable characters in alphanumeric mode");
let bb: Array<bit> = [];
let i: int;
for (i = 0; i + 2 <= text.length; i += 2) {
// Process groups of 2
let temp: int = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
appendBits(temp, 11, bb);
}
if (i < text.length)
// 1 character remaining
appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
}
// Returns a new mutable list of zero or more segments to represent the given Unicode text string.
// The result may use various segment modes and switch modes to optimize the length of the bit stream.
public static makeSegments(text: string): Array<QrSegment> {
// Select the most efficient segment encoding automatically
if (text == "") return [];
else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];
else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];
else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
}
// Returns a segment representing an Extended Channel Interpretation
// (ECI) designator with the given assignment value.
public static makeEci(assignVal: int): QrSegment {
let bb: Array<bit> = [];
if (assignVal < 0) throw new RangeError("ECI assignment value out of range");
else if (assignVal < 1 << 7) appendBits(assignVal, 8, bb);
else if (assignVal < 1 << 14) {
appendBits(0b10, 2, bb);
appendBits(assignVal, 14, bb);
} else if (assignVal < 1000000) {
appendBits(0b110, 3, bb);
appendBits(assignVal, 21, bb);
} else throw new RangeError("ECI assignment value out of range");
return new QrSegment(QrSegment.Mode.ECI, 0, bb);
}
// Tests whether the given string can be encoded as a segment in numeric mode.
// A string is encodable iff each character is in the range 0 to 9.
public static isNumeric(text: string): boolean {
return QrSegment.NUMERIC_REGEX.test(text);
}
// Tests whether the given string can be encoded as a segment in alphanumeric mode.
// A string is encodable iff each character is in the following set: 0 to 9, A to Z
// (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
public static isAlphanumeric(text: string): boolean {
return QrSegment.ALPHANUMERIC_REGEX.test(text);
}
/*-- Constructor (low level) and fields --*/
// Creates a new QR Code segment with the given attributes and data.
// The character count (numChars) must agree with the mode and the bit buffer length,
// but the constraint isn't checked. The given bit buffer is cloned and stored.
public constructor(
// The mode indicator of this segment.
public readonly mode: QrSegment.Mode,
// The length of this segment's unencoded data. Measured in characters for
// numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
// Always zero or positive. Not the same as the data's bit length.
public readonly numChars: int,
// The data bits of this segment. Accessed through getData().
private readonly bitData: Array<bit>,
) {
if (numChars < 0) throw new RangeError("Invalid argument");
this.bitData = bitData.slice(); // Make defensive copy
}
/*-- Methods --*/
// Returns a new copy of the data bits of this segment.
public getData(): Array<bit> {
return this.bitData.slice(); // Make defensive copy
}
// (Package-private) Calculates and returns the number of bits needed to encode the given segments at
// the given version. The result is infinity if a segment has too many characters to fit its length field.
public static getTotalBits(segs: Readonly<Array<QrSegment>>, version: int): number {
let result: number = 0;
for (const seg of segs) {
const ccbits: int = seg.mode.numCharCountBits(version);
if (seg.numChars >= 1 << ccbits) return Infinity; // The segment's length doesn't fit the field's bit width
result += 4 + ccbits + seg.bitData.length;
}
return result;
}
// Returns a new array of bytes representing the given string encoded in UTF-8.
private static toUtf8ByteArray(str: string): Array<byte> {
str = encodeURI(str);
let result: Array<byte> = [];
for (let i = 0; i < str.length; i++) {
if (str.charAt(i) != "%") result.push(str.charCodeAt(i));
else {
result.push(parseInt(str.substring(i + 1, i + 3), 16));
i += 2;
}
}
return result;
}
/*-- Constants --*/
// Describes precisely all strings that are encodable in numeric mode.
private static readonly NUMERIC_REGEX: RegExp = /^[0-9]*$/;
// Describes precisely all strings that are encodable in alphanumeric mode.
private static readonly ALPHANUMERIC_REGEX: RegExp = /^[A-Z0-9 $%*+.\/:-]*$/;
// The set of all legal characters in alphanumeric mode,
// where each character value maps to the index in the string.
private static readonly ALPHANUMERIC_CHARSET: string =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
}
}
/*---- Public helper enumeration ----*/
namespace qrcodegen.QrCode {
type int = number;
/*
* The error correction level in a QR Code symbol. Immutable.
*/
export class Ecc {
/*-- Constants --*/
public static readonly LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
public static readonly MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
public static readonly QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
public static readonly HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
/*-- Constructor and fields --*/
private constructor(
// In the range 0 to 3 (unsigned 2-bit integer).
public readonly ordinal: int,
// (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
public readonly formatBits: int,
) {}
}
}
/*---- Public helper enumeration ----*/
namespace qrcodegen.QrSegment {
type int = number;
/*
* Describes how a segment's data bits are interpreted. Immutable.
*/
export class Mode {
/*-- Constants --*/
public static readonly NUMERIC = new Mode(0x1, [10, 12, 14]);
public static readonly ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
public static readonly BYTE = new Mode(0x4, [8, 16, 16]);
public static readonly KANJI = new Mode(0x8, [8, 10, 12]);
public static readonly ECI = new Mode(0x7, [0, 0, 0]);
/*-- Constructor and fields --*/
private constructor(
// The mode indicator bits, which is a uint4 value (range 0 to 15).
public readonly modeBits: int,
// Number of character count bits for three different version ranges.
private readonly numBitsCharCount: [int, int, int],
) {}
/*-- Method --*/
// (Package-private) Returns the bit width of the character count field for a segment in
// this mode in a QR Code at the given version number. The result is in the range [0, 16].
public numCharCountBits(ver: int): int {
return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
}
}
}
export const QrCode = qrcodegen.QrCode;
export const QrSegment = qrcodegen.QrSegment;
+16
View File
@@ -182,6 +182,7 @@ interface StagePackageJson {
readonly devDependencies: {
readonly electron: string;
};
readonly overrides: Record<string, unknown>;
}
const AzureTrustedSigningOptionsConfig = Config.all({
@@ -570,6 +571,20 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
});
}
const resolvedOverrides = yield* Effect.try({
try: () =>
resolveCatalogDependencies(
rootPackageJson.overrides,
rootPackageJson.workspaces.catalog,
"apps/desktop",
),
catch: (cause) =>
new BuildScriptError({
message: "Could not resolve overrides from package.json.",
cause,
}),
});
const resolvedServerDependencies = yield* Effect.try({
try: () =>
resolveCatalogDependencies(
@@ -677,6 +692,7 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* (
devDependencies: {
electron: electronVersion,
},
overrides: resolvedOverrides,
};
const stagePackageJsonString = yield* encodeJsonString(stagePackageJson);
+2
View File
@@ -84,6 +84,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.T3CODE_HOME, resolve("/tmp/custom-t3"));
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://localhost:4222");
assert.equal(env.VITE_WS_URL, "ws://localhost:4222");
assert.equal(env.T3CODE_NO_BROWSER, "1");
assert.equal(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD, "0");
@@ -183,6 +184,7 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
assert.equal(env.VITE_DEV_SERVER_URL, "http://127.0.0.1:5733");
assert.equal(env.HOST, "127.0.0.1");
assert.equal(env.T3CODE_PORT, "4222");
assert.equal(env.VITE_HTTP_URL, "http://127.0.0.1:4222");
assert.equal(env.T3CODE_MODE, undefined);
assert.equal(env.T3CODE_NO_BROWSER, undefined);
assert.equal(env.T3CODE_HOST, undefined);
+2
View File
@@ -159,9 +159,11 @@ export function createDevRunnerEnv({
if (!isDesktopMode) {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://localhost:${serverPort}`;
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
} else {
output.T3CODE_PORT = String(serverPort);
output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`;
delete output.T3CODE_MODE;
delete output.T3CODE_NO_BROWSER;