Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d169cfd54d | ||
|
|
e31fcbdf26 | ||
|
|
b033c60d41 | ||
|
|
2a5525a9e5 | ||
|
|
0e500fe025 | ||
|
|
442bab63e8 | ||
|
|
191883e599 | ||
|
|
dca0b9fb33 | ||
|
|
4437965135 | ||
|
|
5f94bfd5fe | ||
|
|
718a682782 | ||
|
|
b7cf04ba93 | ||
|
|
56bce5617a | ||
|
|
1327646d42 | ||
|
|
4f36062f9b |
No files matched your search
@@ -1,103 +0,0 @@
|
||||
# Plan: Remote Execution for T3 Server + Web/Desktop Frontends
|
||||
|
||||
## Goal
|
||||
Enable a remote `t3` backend to run on another machine while both frontend clients (browser web app and Electron desktop app) connect to it reliably.
|
||||
|
||||
## Constraints From Current Codebase
|
||||
- Transport is a single WebSocket RPC channel plus push events.
|
||||
- Desktop currently assumes local backend process ownership.
|
||||
- Browser clients cannot set arbitrary WebSocket headers.
|
||||
- Existing auth support was token-in-query only (`?token=...`).
|
||||
|
||||
## Core Design Choices Explored
|
||||
|
||||
### 1) Network Topology
|
||||
Option A: SSH tunnel to remote loopback (`ssh -L`)
|
||||
- Pros: no public WS exposure, strong default security model.
|
||||
- Cons: requires SSH session lifecycle and tunnel setup per user/session.
|
||||
|
||||
Option B: Direct authenticated WebSocket endpoint (typically behind TLS/reverse proxy)
|
||||
- Pros: simplest UX for multi-client access, no tunnel required.
|
||||
- Cons: needs auth hardening and TLS termination in deployment.
|
||||
|
||||
Decision: Support both operationally, but implement direct authenticated WS as the primary PoC path, with SSH as a first-class secure deployment mode.
|
||||
|
||||
### 2) WS Authentication Mechanism
|
||||
Option A: Query token (`wss://.../?token=...`)
|
||||
- Pros: works in browser and Electron renderer immediately.
|
||||
- Cons: token can leak via logs/history if mishandled.
|
||||
|
||||
Option B: `Authorization: Bearer ...` header
|
||||
- Pros: cleaner for non-browser clients and service integrations.
|
||||
- Cons: not settable by normal browser WebSocket API.
|
||||
|
||||
Option C: mTLS-only
|
||||
- Pros: strongest transport auth.
|
||||
- Cons: high setup complexity for a PoC.
|
||||
|
||||
Decision: Keep query token as browser-compatible baseline, add bearer-header support on server for non-browser clients.
|
||||
|
||||
### 3) Frontend Remote Endpoint Configuration
|
||||
Option A: Build-time env only (`VITE_WS_URL`)
|
||||
- Pros: simple in CI/deploy pipelines.
|
||||
- Cons: rigid for ad-hoc remote switching.
|
||||
|
||||
Option B: Runtime URL params (e.g. `?t3WsUrl=...&t3Token=...`)
|
||||
- Pros: no rebuild needed; easy operator workflow for PoC.
|
||||
- Cons: requires token hygiene.
|
||||
|
||||
Option C: In-app settings UI
|
||||
- Pros: best UX long-term.
|
||||
- Cons: more product and persistence work.
|
||||
|
||||
Decision: Implement A + B (env + runtime URL params) for web app PoC.
|
||||
|
||||
### 4) Desktop Backend Ownership Model
|
||||
Option A: Always spawn local backend (current)
|
||||
- Pros: existing stable behavior.
|
||||
- Cons: cannot target remote backend.
|
||||
|
||||
Option B: Configurable remote mode (skip local spawn; renderer connects remote WS)
|
||||
- Pros: minimal invasive change; preserves existing desktop UX shell.
|
||||
- Cons: some desktop-only assumptions may need future guardrails.
|
||||
|
||||
Decision: Implement B via env (`T3CODE_REMOTE_WS_URL`, optional `T3CODE_REMOTE_WS_TOKEN`).
|
||||
|
||||
### 5) Server Bind Strategy
|
||||
Option A: hardcoded mode-based bind (current desktop loopback / web default)
|
||||
- Pros: simple.
|
||||
- Cons: remote deployment lacks explicit operator control.
|
||||
|
||||
Option B: explicit `T3CODE_HOST` override
|
||||
- Pros: supports secure loopback-for-SSH and public bind use cases.
|
||||
|
||||
Decision: Implement B.
|
||||
|
||||
## Implemented PoC Changes
|
||||
- `apps/server/src/index.ts`
|
||||
- Added `T3CODE_HOST` support for explicit bind control.
|
||||
- `apps/server/src/wsServer.ts`
|
||||
- WS auth now accepts bearer token from `Authorization` header in addition to `?token=`.
|
||||
- `apps/server/src/wsServer.test.ts`
|
||||
- Added test coverage for bearer auth header path.
|
||||
- `apps/web/src/wsTransport.ts`
|
||||
- Added runtime remote config via URL params: `t3WsUrl`, `t3Token`.
|
||||
- Added protocol normalization (`http(s)` -> `ws(s)`) and token attachment logic.
|
||||
- Default same-origin fallback now respects page protocol (`wss` on https).
|
||||
- `apps/web/vite.config.ts`
|
||||
- Added `VITE_WS_TOKEN` injection for build/dev env usage.
|
||||
- `apps/desktop/src/main.ts`
|
||||
- Added remote backend mode (`T3CODE_REMOTE_WS_URL`, `T3CODE_REMOTE_WS_TOKEN`) that skips local backend spawn.
|
||||
|
||||
## Chosen Architecture (for this PoC)
|
||||
- Remote `t3` server is the single source of truth and execution node.
|
||||
- Web and desktop renderers are pure clients over authenticated WebSocket.
|
||||
- Deployment can be:
|
||||
- SSH tunnel + loopback bind (`T3CODE_HOST=127.0.0.1`), or
|
||||
- direct authenticated WS endpoint (prefer TLS/reverse proxy).
|
||||
|
||||
## Follow-ups After PoC
|
||||
- Move token auth from query param to short-lived session token bootstrap for browser UX/security.
|
||||
- Add explicit origin allowlist + rate limiting for internet-exposed deployments.
|
||||
- Add in-app connection settings UI for runtime endpoint switching.
|
||||
- Add reconnect telemetry and health/status endpoint for remote ops.
|
||||
@@ -27,8 +27,6 @@ T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JS
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
Remote deployment and frontend-to-remote connection details are documented in `REMOTE.md`.
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
# Remote T3 Architecture (PoC)
|
||||
|
||||
## Summary
|
||||
This PoC supports running `apps/server` on a remote machine and connecting both frontend clients to it:
|
||||
- Browser web app (via env or runtime URL params)
|
||||
- Electron desktop app (remote mode; no local backend spawn)
|
||||
|
||||
## Final Architecture
|
||||
```mermaid
|
||||
flowchart LR
|
||||
subgraph ClientMachine[Client Machine]
|
||||
Web[Web App\n(React/Vite)]
|
||||
Desktop[Desktop App\n(Electron Renderer)]
|
||||
end
|
||||
|
||||
subgraph RemoteMachine[Remote Machine]
|
||||
Server[T3 Server\n(HTTP + WS RPC)]
|
||||
Codex[Codex App Server\n(JSON-RPC over stdio)]
|
||||
end
|
||||
|
||||
Web -- "wss/ws + token auth" --> Server
|
||||
Desktop -- "wss/ws + token auth" --> Server
|
||||
Server -- "stdio JSON-RPC" --> Codex
|
||||
```
|
||||
|
||||
## Connection Modes
|
||||
|
||||
### 1) SSH Tunnel (recommended for operator security)
|
||||
Run remote server loopback-only:
|
||||
```bash
|
||||
T3CODE_HOST=127.0.0.1 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
|
||||
```
|
||||
|
||||
From client machine, forward port:
|
||||
```bash
|
||||
ssh -L 3773:127.0.0.1:3773 <user>@<remote-host>
|
||||
```
|
||||
|
||||
Then connect clients to `ws://127.0.0.1:3773` with the same token.
|
||||
|
||||
### 1b) Private Tunnel With Tailscale (no public exposure)
|
||||
This keeps your T3 server private to your tailnet and avoids opening router/firewall ports to the public internet.
|
||||
|
||||
1. Install and log in to Tailscale on both machines.
|
||||
2. Verify the two machines can reach each other over tailnet:
|
||||
```bash
|
||||
tailscale status
|
||||
```
|
||||
3. On the remote machine, run T3 loopback-only:
|
||||
```bash
|
||||
T3CODE_HOST=127.0.0.1 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
|
||||
```
|
||||
4. From your client machine, create an SSH local-forward over Tailscale:
|
||||
```bash
|
||||
ssh -N -L 3773:127.0.0.1:3773 <user>@<remote-tailnet-name-or-100.x.y.z>
|
||||
```
|
||||
|
||||
Now your local machine has a private tunnel at `127.0.0.1:3773` to the remote T3 server.
|
||||
|
||||
Use clients exactly like local:
|
||||
- Web: `http://localhost:<web-port>/?t3WsUrl=ws://127.0.0.1:3773&t3Token=<token>`
|
||||
- Desktop:
|
||||
```bash
|
||||
T3CODE_REMOTE_WS_URL=ws://127.0.0.1:3773 T3CODE_REMOTE_WS_TOKEN=<token> bun run start:desktop
|
||||
```
|
||||
|
||||
Notes:
|
||||
- If you use Tailscale SSH, the same `ssh -L` pattern works.
|
||||
- This model does not expose T3 to the public internet; access is limited by your tailnet + SSH auth + T3 token.
|
||||
|
||||
### 2) Direct Authenticated WS
|
||||
Run remote server network-bound:
|
||||
```bash
|
||||
T3CODE_HOST=0.0.0.0 T3CODE_PORT=3773 T3CODE_AUTH_TOKEN=<token> bun run start
|
||||
```
|
||||
|
||||
Use TLS termination/reverse proxy in front for production internet exposure.
|
||||
|
||||
## Client Configuration
|
||||
|
||||
### Web App
|
||||
Supported config sources:
|
||||
- Build/dev env: `VITE_WS_URL`, optional `VITE_WS_TOKEN`
|
||||
- Runtime URL params: `t3WsUrl`, `t3Token`
|
||||
|
||||
Examples:
|
||||
```text
|
||||
https://web-host/?t3WsUrl=wss://api.example.com&t3Token=secret
|
||||
https://api.example.com/?t3Token=secret
|
||||
```
|
||||
|
||||
Notes:
|
||||
- If `t3WsUrl` is `http://` or `https://`, it is normalized to `ws://` or `wss://`.
|
||||
- If no URL is provided, web falls back to same-origin WS using page protocol.
|
||||
- To avoid putting tokens in request logs/history, prefer fragment form (supported): `#t3WsUrl=...&t3Token=...`
|
||||
|
||||
### Desktop App
|
||||
Set remote mode env vars before launch:
|
||||
- `T3CODE_REMOTE_WS_URL` (required for remote mode)
|
||||
- `T3CODE_REMOTE_WS_TOKEN` (optional if URL already includes `?token=`)
|
||||
|
||||
Example:
|
||||
```bash
|
||||
T3CODE_REMOTE_WS_URL=ws://127.0.0.1:3773 T3CODE_REMOTE_WS_TOKEN=secret bun run start:desktop
|
||||
```
|
||||
|
||||
When `T3CODE_REMOTE_WS_URL` is set, desktop skips spawning the local server process.
|
||||
|
||||
## Auth Behavior
|
||||
Server WS auth now accepts either:
|
||||
- Query token: `?token=...` (browser-compatible)
|
||||
- `Authorization: Bearer <token>` header (non-browser clients)
|
||||
|
||||
## New/Relevant Env Vars
|
||||
- Server:
|
||||
- `T3CODE_HOST`
|
||||
- `T3CODE_PORT`
|
||||
- `T3CODE_AUTH_TOKEN`
|
||||
- Web:
|
||||
- `VITE_WS_URL`
|
||||
- `VITE_WS_TOKEN`
|
||||
- Desktop:
|
||||
- `T3CODE_REMOTE_WS_URL`
|
||||
- `T3CODE_REMOTE_WS_TOKEN`
|
||||
@@ -31,34 +31,6 @@ let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
|
||||
function trimToUndefined(value: string | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function resolveRemoteWsUrl(rawUrl: string, rawToken: string | undefined): string {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(rawUrl);
|
||||
} catch {
|
||||
throw new Error(`Invalid T3CODE_REMOTE_WS_URL: ${rawUrl}`);
|
||||
}
|
||||
|
||||
if (parsed.protocol === "http:") parsed.protocol = "ws:";
|
||||
if (parsed.protocol === "https:") parsed.protocol = "wss:";
|
||||
if (parsed.protocol !== "ws:" && parsed.protocol !== "wss:") {
|
||||
throw new Error(`Invalid T3CODE_REMOTE_WS_URL protocol: ${parsed.protocol}`);
|
||||
}
|
||||
|
||||
const token = trimToUndefined(rawToken);
|
||||
if (token && !parsed.searchParams.get("token")) {
|
||||
parsed.searchParams.set("token", token);
|
||||
}
|
||||
|
||||
return parsed.toString();
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
@@ -275,15 +247,6 @@ function createWindow(): BrowserWindow {
|
||||
}
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
const remoteWsUrl = trimToUndefined(process.env.T3CODE_REMOTE_WS_URL);
|
||||
if (remoteWsUrl) {
|
||||
backendWsUrl = resolveRemoteWsUrl(remoteWsUrl, process.env.T3CODE_REMOTE_WS_TOKEN);
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
registerIpcHandlers();
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
|
||||
@@ -34,15 +34,6 @@ function parsePort(value: string | undefined): number | undefined {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseHost(value: string | undefined): string | undefined {
|
||||
if (value === undefined) return undefined;
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
throw new Error("Invalid T3CODE_HOST: cannot be empty");
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
function expandHomePath(input: string): string {
|
||||
if (input === "~") return os.homedir();
|
||||
if (input.startsWith("~/")) {
|
||||
@@ -108,10 +99,8 @@ function resolveStaticDir(): string | undefined {
|
||||
async function main() {
|
||||
const mode: RuntimeMode = process.env.T3CODE_MODE === "desktop" ? "desktop" : "web";
|
||||
const requestedPort = parsePort(process.env.T3CODE_PORT);
|
||||
const requestedHost = parseHost(process.env.T3CODE_HOST);
|
||||
const port =
|
||||
requestedPort ?? (mode === "desktop" ? DEFAULT_PORT : await findAvailablePort(DEFAULT_PORT));
|
||||
const host = requestedHost ?? (mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
const stateDir = resolveStateDir(process.env.T3CODE_STATE_DIR);
|
||||
const projectRegistry = new ProjectRegistry(stateDir);
|
||||
const devUrl = process.env.VITE_DEV_SERVER_URL;
|
||||
@@ -127,7 +116,7 @@ async function main() {
|
||||
|
||||
const server = createServer({
|
||||
port,
|
||||
host,
|
||||
host: mode === "desktop" ? "127.0.0.1" : undefined,
|
||||
cwd,
|
||||
staticDir,
|
||||
devUrl,
|
||||
@@ -139,7 +128,6 @@ async function main() {
|
||||
const url = `http://localhost:${port}`;
|
||||
logger.info("T3 Code running", {
|
||||
url,
|
||||
host: host ?? "0.0.0.0",
|
||||
cwd,
|
||||
mode,
|
||||
stateDir,
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
type ProjectScript,
|
||||
type ProjectUpdateScriptsInput,
|
||||
type ProjectUpdateScriptsResult,
|
||||
normalizeProjectScripts,
|
||||
projectAddInputSchema,
|
||||
projectRecordSchema,
|
||||
projectRemoveInputSchema,
|
||||
@@ -131,7 +130,7 @@ export class ProjectRegistry {
|
||||
throw new Error(`Project not found: ${input.id}`);
|
||||
}
|
||||
|
||||
const nextScripts = normalizeProjectScripts(projectScriptsSchema.parse(input.scripts));
|
||||
const nextScripts = dedupeScriptsById(projectScriptsSchema.parse(input.scripts));
|
||||
const nextUpdatedAt = new Date().toISOString();
|
||||
const nextProject: ProjectRecord = {
|
||||
...this.projects[index]!,
|
||||
@@ -168,7 +167,7 @@ export class ProjectRegistry {
|
||||
cwd: normalizedCwd,
|
||||
name:
|
||||
project.name.trim().length > 0 ? project.name.trim() : inferProjectName(normalizedCwd),
|
||||
scripts: normalizeProjectScripts(project.scripts),
|
||||
scripts: dedupeScriptsById(project.scripts),
|
||||
};
|
||||
deduped.set(normalizedCwd, normalizedProject);
|
||||
normalizedProjects.push(normalizedProject);
|
||||
@@ -233,3 +232,35 @@ export class ProjectRegistry {
|
||||
fs.renameSync(tempFile, this.filePath);
|
||||
}
|
||||
}
|
||||
|
||||
function dedupeScriptsById(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const seenIds = new Set<string>();
|
||||
const deduped: ProjectScript[] = [];
|
||||
for (const script of scripts) {
|
||||
if (seenIds.has(script.id)) continue;
|
||||
seenIds.add(script.id);
|
||||
deduped.push({
|
||||
id: script.id,
|
||||
name: script.name,
|
||||
command: script.command,
|
||||
icon: script.icon,
|
||||
runOnWorktreeCreate: script.runOnWorktreeCreate,
|
||||
});
|
||||
}
|
||||
|
||||
let setupAssigned = false;
|
||||
const normalized: ProjectScript[] = [];
|
||||
for (const script of deduped) {
|
||||
if (!script.runOnWorktreeCreate) {
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
if (!setupAssigned) {
|
||||
setupAssigned = true;
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
normalized.push({ ...script, runOnWorktreeCreate: false });
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
@@ -143,14 +143,10 @@ class MockTerminalManager extends EventEmitter<{ event: [event: TerminalEvent] }
|
||||
dispose(): void {}
|
||||
}
|
||||
|
||||
function connectWs(
|
||||
port: number,
|
||||
token?: string,
|
||||
headers?: Record<string, string>,
|
||||
): Promise<WebSocket> {
|
||||
function connectWs(port: number, token?: string): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, { headers });
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const pending: PendingMessages = { queue: [], waiters: [] };
|
||||
pendingBySocket.set(ws, pending);
|
||||
|
||||
@@ -1061,20 +1057,4 @@ describe("WebSocket Server", () => {
|
||||
const welcome = (await waitForMessage(authorizedWs)) as WsPush;
|
||||
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
});
|
||||
|
||||
it("accepts bearer auth header for websocket authentication", async () => {
|
||||
server = createTestServer({ cwd: "/test", authToken: "secret-token" });
|
||||
await server.start();
|
||||
const addr = server.httpServer.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(
|
||||
connectWs(port, undefined, { Authorization: "Bearer wrong-token" }),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const ws = await connectWs(port, undefined, { Authorization: "Bearer secret-token" });
|
||||
connections.push(ws);
|
||||
const welcome = (await waitForMessage(ws)) as WsPush;
|
||||
expect(welcome.channel).toBe(WS_CHANNELS.serverWelcome);
|
||||
});
|
||||
});
|
||||
@@ -198,28 +198,6 @@ export function createServer(options: ServerOptions) {
|
||||
// WebSocket server — upgrades from the HTTP server
|
||||
const wss = new WebSocketServer({ noServer: true });
|
||||
|
||||
function parseBearerToken(authorizationHeader: string | string[] | undefined): string | null {
|
||||
const raw = Array.isArray(authorizationHeader)
|
||||
? authorizationHeader[0]
|
||||
: authorizationHeader;
|
||||
if (!raw) return null;
|
||||
const match = raw.match(/^Bearer\s+(.+)$/i);
|
||||
const token = match?.[1]?.trim();
|
||||
return token && token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
function parseTokenFromQuery(requestUrl: string | undefined): string | null {
|
||||
const url = new URL(requestUrl ?? "/", `http://localhost:${port}`);
|
||||
const queryToken = url.searchParams.get("token");
|
||||
return queryToken && queryToken.length > 0 ? queryToken : null;
|
||||
}
|
||||
|
||||
function parseUpgradeToken(request: http.IncomingMessage): string | null {
|
||||
const bearerToken = parseBearerToken(request.headers.authorization);
|
||||
if (bearerToken) return bearerToken;
|
||||
return parseTokenFromQuery(request.url);
|
||||
}
|
||||
|
||||
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
|
||||
socket.write(
|
||||
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
|
||||
@@ -234,16 +212,19 @@ export function createServer(options: ServerOptions) {
|
||||
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const providedToken = parseUpgradeToken(request);
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
|
||||
+32
-1
@@ -8,7 +8,7 @@ import {
|
||||
useReducer,
|
||||
} from "react";
|
||||
|
||||
import { type ProviderEvent, type ProviderSession, type TerminalEvent, normalizeProjectScripts } from "@t3tools/contracts";
|
||||
import type { ProviderEvent, ProviderSession, TerminalEvent } from "@t3tools/contracts";
|
||||
import { resolveModelSlug } from "./model-logic";
|
||||
import { hydratePersistedState, toPersistedState } from "./persistenceSchema";
|
||||
import { applyEventToMessages, asObject, asString, evolveSession } from "./session-logic";
|
||||
@@ -165,6 +165,37 @@ function normalizeRunningTerminalIds(
|
||||
.filter((id) => id.length > 0 && validTerminalIdSet.has(id));
|
||||
}
|
||||
|
||||
function normalizeProjectScripts(scripts: ProjectScript[]): ProjectScript[] {
|
||||
const deduped: ProjectScript[] = [];
|
||||
const seenIds = new Set<string>();
|
||||
for (const script of scripts) {
|
||||
const id = script.id.trim();
|
||||
if (id.length === 0 || seenIds.has(id)) continue;
|
||||
seenIds.add(id);
|
||||
deduped.push({
|
||||
...script,
|
||||
id,
|
||||
name: script.name.trim(),
|
||||
command: script.command.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
let setupAssigned = false;
|
||||
const normalized: ProjectScript[] = [];
|
||||
for (const script of deduped) {
|
||||
if (!script.runOnWorktreeCreate) {
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
if (!setupAssigned) {
|
||||
setupAssigned = true;
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
normalized.push({ ...script, runOnWorktreeCreate: false });
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function normalizeTerminalGroupIds(terminalIds: string[]): string[] {
|
||||
return [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))];
|
||||
|
||||
@@ -10,49 +10,6 @@ interface PendingRequest {
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 60_000;
|
||||
const RECONNECT_DELAYS_MS = [500, 1_000, 2_000, 4_000, 8_000];
|
||||
const RUNTIME_WS_URL_PARAM = "t3WsUrl";
|
||||
const RUNTIME_WS_TOKEN_PARAM = "t3Token";
|
||||
|
||||
function trimToUndefined(value: string | null | undefined): string | undefined {
|
||||
if (!value) return undefined;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
function readRuntimeParam(name: string): string | undefined {
|
||||
const fromSearch = trimToUndefined(new URLSearchParams(window.location.search).get(name));
|
||||
if (fromSearch) return fromSearch;
|
||||
|
||||
const hash = window.location.hash.startsWith("#")
|
||||
? window.location.hash.slice(1)
|
||||
: window.location.hash;
|
||||
return trimToUndefined(new URLSearchParams(hash).get(name));
|
||||
}
|
||||
|
||||
function normalizeWsUrl(raw: string): string {
|
||||
try {
|
||||
const parsed = new URL(raw, window.location.href);
|
||||
if (parsed.protocol === "http:") parsed.protocol = "ws:";
|
||||
if (parsed.protocol === "https:") parsed.protocol = "wss:";
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
function withAuthToken(url: string, token: string | undefined): string {
|
||||
if (!token) return url;
|
||||
try {
|
||||
const parsed = new URL(url, window.location.href);
|
||||
if (!parsed.searchParams.get("token")) {
|
||||
parsed.searchParams.set("token", token);
|
||||
}
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
const glue = url.includes("?") ? "&" : "?";
|
||||
return `${url}${glue}token=${encodeURIComponent(token)}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class WsTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
@@ -66,18 +23,16 @@ export class WsTransport {
|
||||
|
||||
constructor(url?: string) {
|
||||
const bridgeUrl = window.desktopBridge?.getWsUrl();
|
||||
const runtimeWsUrl = readRuntimeParam(RUNTIME_WS_URL_PARAM);
|
||||
const runtimeWsToken = readRuntimeParam(RUNTIME_WS_TOKEN_PARAM);
|
||||
// In dev mode, VITE_WS_URL points to the server's WebSocket endpoint.
|
||||
// In production, the page is served by the WS server on the same host:port.
|
||||
const envUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const envToken = trimToUndefined(import.meta.env.VITE_WS_TOKEN as string | undefined);
|
||||
const defaultProtocol = window.location.protocol === "https:" ? "wss" : "ws";
|
||||
const defaultUrl = `${defaultProtocol}://${window.location.host}`;
|
||||
const selectedUrl = trimToUndefined(
|
||||
url ?? bridgeUrl ?? runtimeWsUrl ?? trimToUndefined(envUrl) ?? defaultUrl,
|
||||
);
|
||||
this.url = withAuthToken(normalizeWsUrl(selectedUrl ?? defaultUrl), runtimeWsToken ?? envToken);
|
||||
this.url =
|
||||
url ??
|
||||
(bridgeUrl && bridgeUrl.length > 0
|
||||
? bridgeUrl
|
||||
: envUrl && envUrl.length > 0
|
||||
? envUrl
|
||||
: `ws://${window.location.hostname}:${window.location.port}`);
|
||||
this.connect();
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@ export default defineConfig({
|
||||
define: {
|
||||
// In dev mode, tell the web app where the WebSocket server lives
|
||||
"import.meta.env.VITE_WS_URL": JSON.stringify(process.env.VITE_WS_URL ?? ""),
|
||||
"import.meta.env.VITE_WS_TOKEN": JSON.stringify(process.env.VITE_WS_TOKEN ?? ""),
|
||||
},
|
||||
experimental: {
|
||||
enableNativePlugin: true,
|
||||
|
||||
@@ -84,43 +84,6 @@ export const projectUpdateScriptsResultSchema = z.object({
|
||||
|
||||
export type ProjectScriptIcon = z.infer<typeof projectScriptIconSchema>;
|
||||
export type ProjectScript = z.infer<typeof projectScriptSchema>;
|
||||
|
||||
/**
|
||||
* Deduplicate scripts by ID and enforce at most one `runOnWorktreeCreate: true`
|
||||
* flag (the first one wins). Fields are trimmed defensively so this is safe to
|
||||
* call on data that hasn't been through Zod parsing.
|
||||
*/
|
||||
export function normalizeProjectScripts(scripts: readonly ProjectScript[]): ProjectScript[] {
|
||||
const seenIds = new Set<string>();
|
||||
const deduped: ProjectScript[] = [];
|
||||
for (const script of scripts) {
|
||||
const id = script.id.trim();
|
||||
if (id.length === 0 || seenIds.has(id)) continue;
|
||||
seenIds.add(id);
|
||||
deduped.push({
|
||||
...script,
|
||||
id,
|
||||
name: script.name.trim(),
|
||||
command: script.command.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
let setupAssigned = false;
|
||||
const normalized: ProjectScript[] = [];
|
||||
for (const script of deduped) {
|
||||
if (!script.runOnWorktreeCreate) {
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
if (!setupAssigned) {
|
||||
setupAssigned = true;
|
||||
normalized.push(script);
|
||||
continue;
|
||||
}
|
||||
normalized.push({ ...script, runOnWorktreeCreate: false });
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
export type ProjectRecord = z.infer<typeof projectRecordSchema>;
|
||||
export type ProjectListResult = z.infer<typeof projectListResultSchema>;
|
||||
export type ProjectAddInput = z.input<typeof projectAddInputSchema>;
|
||||
|
||||
Reference in new issue
Block a user