Compare commits

...
Author SHA1 Message Date
Cursor AgentandJulius Marminge ba5fd8459e Fix typed port scanner assertions
Co-authored-by: Julius Marminge <[email protected]>
2026-06-14 16:09:05 +00:00
Cursor AgentandJulius Marminge 5ea7466bd5 Refactor preview port scanner Effect patterns
Co-authored-by: Julius Marminge <[email protected]>
2026-06-14 16:06:09 +00:00
Julius Marminge 3a0623f1cd rm test artifacts 2026-06-13 22:18:37 -07:00
Julius Marminge cd91ec75f3 Remove outdated plans for shared HTTP MCP server and visible preview browser automation via CDP. Consolidate and refine the architecture and process models for the new preview automation framework, including updated contracts, server-side broker, and desktop integration. Introduce new WS methods for client communication and enhance security measures for token management. Ensure comprehensive testing strategies are in place for all components. 2026-06-13 22:18:37 -07:00
Julius Marminge d4ba9e9618 Document browser preview phase 0.5 findings and plans
- Add phase 0 and 0.5 ADRs, findings, and spike notes
- Update browser preview docs and supporting UI/test files
- Record the chosen renderer, automation, recording, tunnel, and input decisions
2026-06-13 22:18:37 -07:00
Julius Marminge c1792bc9a6 Use real preview tooltips 2026-06-13 22:18:37 -07:00
Julius Marminge 1b4317ec35 Restore terminal drawer header toggle 2026-06-13 22:18:37 -07:00
Julius Marminge f452d63fef Fix terminal browser test mock 2026-06-13 22:18:37 -07:00
Julius Marminge 18a49abcec Fix preview CI test fixtures 2026-06-13 22:18:37 -07:00
Julius Marminge 85d5df6256 Unify browser asset preview routing
- Replace attachment and favicon routes with signed asset URLs
- Harden workspace and attachment asset resolution
- Update browser preview components and shared contracts
2026-06-13 22:18:37 -07:00
Julius Marminge b5b769dddf Prevent stale preview snapshots from resurrecting sessions
- Track preview store revisions per thread
- Ignore stale SWR results while revalidating
- Avoid restoring closed sessions from outdated data
2026-06-13 22:18:37 -07:00
Julius Marminge 3c7862edd7 Add SWR preview session state and resubscribe handling
- Fetch preview sessions through atom-backed SWR state
- Recover browser preview sessions after reconnects
- Ignore older streamed snapshots when SWR revalidates
2026-06-13 22:18:37 -07:00
Julius Marminge d8fe3d72c8 Scope preview listeners and control sessions
- Tie preview and debugger listeners to Effect scopes
- Factor shared automation helpers for snapshot and input handling
- Improve cleanup for browser preview sessions and port scanning
2026-06-13 22:18:37 -07:00
Julius Marminge 70ec39ae80 Port preview manager to Effect-based browser sessions
- derive preview partitions through `BrowserSession`
- serialize session state and async preview control flow
- update tests for screenshot, automation, and partition behavior
2026-06-13 22:18:37 -07:00
Julius Marminge 3d9e8dea7d Refactor desktop preview IPC onto shared manager
- Move preview session and IPC wiring into the new preview module
- Tighten IPC validation with schema-based handlers
- Update preview asset paths and tests for the browser preview port
2026-06-13 22:18:37 -07:00
Julius Marminge f7c422d581 Refactor MCP services into top-level modules
- Move MCP session registry and preview broker out of `Layers/` and `Services/`
- Update imports, tests, and server wiring to use the new module layout
2026-06-13 22:18:37 -07:00
Julius Marminge dd739c880d Port browser preview annotations to desktop
- Add IPC and runtime plumbing for preview annotation theming
- Generate and ship annotation CSS for the desktop overlay
- Add pointer and artifact handling for browser preview interactions
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 6c6740e381 Refine collaborative browser preview
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marminge 29150b5736 Add shared MCP preview automation 2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 07c6d70b91 Add preview annotation capture tooling
- Add structured annotation payload validation and tests
- Update preview preload to capture selected elements, regions, and strokes
- Wire new preview annotation UI into the web app

Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 50bc18b208 fix(preview): declare RPC authorization scopes
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 63d42a5e58 fix(preview): initialize and open browser reliably
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Julius Marmingeandcodex 9b43123ba2 fix(preview): port browser preview to current main
Co-authored-by: codex <[email protected]>
2026-06-13 22:18:37 -07:00
Aiden Bai 17fb0e4a9a feat(preview): element-pick attachments + sandboxed picker preload
Adds an in-page element picker to the preview browser. Clicking the
crosshair button in the chrome row activates a blue-highlight picker
inside the guest webview; clicking an element captures its component
name (via react-grab), source location, html/css preview, and selector,
then attaches it to the chat composer as a chip that serializes into an
`<element_context>` block in the outgoing message.

Architecture:
- Per-`<webview>` preload bundle (`preview-pick-preload.cjs`) renders
  the overlay, hosts the picker event loop, and bubbles the picked
  payload back to main via the per-WebContents `wc.ipc` channel (not
  `sendToHost`, which only fires on the host renderer's <webview>
  element and never reaches main).
- Main coordinates via `PreviewViewManager.pickElement(tabId)`, which
  cancels any in-flight session, force-focuses the guest (so the first
  click on a remote page actually reaches the preload), then awaits the
  payload. User-initiated cancels (Escape, beforeunload) echo `null`
  back to main; main-initiated cancels and supersession tear down
  silently to avoid the new-pick-resolves-with-stale-null race.
- Renderer fetches partition + webPreferences + preload URL in a single
  `getPreviewConfig()` IPC call, snapshots the previously-focused host
  element before triggering a pick, and restores focus when the pick
  resolves so the user's textarea cursor isn't lost.

Security posture for the guest webview:
- `webpreferences="contextIsolation=false,sandbox=true,nodeIntegration=false"`
  centralized in `preview-webview-preferences.ts`. contextIsolation off
  is required so react-grab's `getElementContext` can reach the page's
  React DevTools hook on `globalThis`. sandbox stays on so the page
  cannot reach Node APIs even with shared globals (without it, the
  preload's `require` would land on the page's `globalThis` and any
  third-party site could send arbitrary IPC to main).
- Defense in depth: a `will-attach-webview` handler in main, gated on
  the preview partition, force-pins `sandbox: true`, all
  `nodeIntegration*: false`, and the absolute preload PATH (not URL —
  that field rejects file:// URLs with "preload script must have
  absolute path" and silently disables the picker).

Composer + transcript integration:
- New `elementContexts` slice in `composerDraftStore` (mirrors the
  terminal-context slice: dedup by selector+tag+component+url, persist
  via partializer, restore on send-failure retry).
- `ComposerPendingElementContexts` chip row above the editor.
- `deriveDisplayedUserMessageState` now strips both `<element_context>`
  AND `<terminal_context>` blocks (element first, since it's appended
  last) and exposes element entries to `MessagesTimeline`, which renders
  them as compact chips beneath the message body.
- Pick button is disabled with explanatory tooltip when the page failed
  to load (the React `<PreviewUnreachable>` overlay covers the webview,
  so picks would silently dangle otherwise).

Tests added:
- `preview-webview-preferences.test.ts` locks down the security flags
  (contextIsolation=false, sandbox=true, nodeIntegration=false, no
  whitespace, only true/false literal values).
- `preview-pick-label-position.test.ts` covers the floating-label
  clamp/flip math (no off-screen overflow, flip-below when no room
  above, etc.).
- `picked-element-payload.test.ts` validator coverage.
- `elementContext.test.ts` for the serialization round-trip,
  normalization, dedup, and label formatting.
- `composerDraftStore.test.ts` element-contexts slice (add, dedup,
  remove, set, clear, persistence round-trip).
- `ChatView.logic.test.ts` sendable-content-with-element-only.

Build: new `tsdown` entry inlines react-grab + bippy into the picker
preload bundle (~59KB / 19KB gzipped).
2026-06-13 22:18:37 -07:00
Aiden Bai 43e8bbd7ae fix 2026-06-13 22:18:37 -07:00
Aiden Bai 52c77c1ec4 feat(preview): in-app browser preview panel
Adds a desktop-only browser preview that lives in the right panel slot
alongside plan/diff. Lets the user point an Electron <webview> at any
URL — typed into a chrome-style URL bar, clicked from the empty-state
list of detected localhost dev servers, or auto-opened by a project
script with `previewUrl` set. Single-tab per thread.

Server (Effect/Layers):
- PreviewManager: per-(thread, tab) session metadata via SynchronizedRef
  + PubSub<PreviewEvent>; survives WS reconnect via `list`/replay.
- PreviewPortScanner: lsof on macOS/Linux, TCP probe fallback on
  Windows; reference-counted polling so we only scan when subscribed.
- WS RPC + streams (`preview.open|navigate|refresh|close|list|reportStatus`,
  `subscribePreviewEvents`, `subscribeDiscoveredLocalServers`).

Desktop:
- PreviewViewManager owns Chromium WebContents per tab, mediates
  navigation/zoom/devtools/clear-storage. registerWebview gates by
  webContents.getType() === "webview" and host-window match.
- IPC channels for create/close/register/navigate/back/forward/refresh/
  zoom/hardReload/openDevTools/clearCookies/clearCache/getBrowserPartition.
- Forwards app-level shortcuts (mod+shift+J, mod+K, mod+,, mod+W) from
  the webview back to the main window.
- Persisted browser session partition (cookies, cache).

Web:
- PreviewPanel/PreviewView/PreviewWebview render the surface; chrome row
  with back/forward/refresh + URL input + Open-in-browser + 3-dot menu
  (Hard reload, DevTools, Zoom −/+/reset, Clear cookies/cache).
- usePreviewSession subscribes to server events; usePreviewBridge
  mirrors desktop state into the store and forwards Loading→Success/
  LoadFailed back to the server.
- previewStateStore: per-thread snapshot + desktopOverlay + recently-
  seen URLs (Zustand).
- rightPanelStore arbitrates plan vs. preview vs. diff; ChatView's
  toggles strip the `?diff=1` URL hint when switching to preview and
  vice versa so the panels are mutually exclusive.
- Top-nav Globe toggle in ChatHeader (desktop builds only) and a
  `mod+shift+J` keybinding routed via a typed previewActionBus.
- PreviewEmptyState lists detected localhost servers (scanner +
  configured project URLs + recently-seen) with live "listening" pulse.
- PreviewUnreachable: theme-aware port of Chromium's "site can't be
  reached" page.
- Resizable inline panel (RightPanelResizeHandle + useResizableWidth);
  width persists to localStorage on drag-end.
- Terminal link "Open in preview" context-menu integration for loopback
  URLs.

Contracts:
- preview.ts schemas (PreviewSessionSnapshot, PreviewNavStatus,
  PreviewEvent, RPC inputs/results, DiscoveredLocalServer).
- ProjectScript schema gains optional `previewUrl` + `autoOpenPreview`.
- New keybinding commands: preview.toggle/refresh/focusUrl/zoomIn/Out/
  resetZoom; new `when:` contexts `previewFocus` / `previewOpen`.

Shared:
- @t3tools/shared/preview: normalizePreviewUrl, isPreviewableUrl,
  isLoopbackHost, newPreviewTabId, LSOF_LOCAL_HOST_TOKENS.

Tests:
- contracts: schema decode tests for all preview events/snapshots/inputs.
- shared: URL normalization coverage.
- server: PreviewManager (open/navigate/reportStatus/refresh/close,
  multi-subscriber isolation, idempotency); PortScanner (lsof parsing
  including IPv6, TCP probe, reference-counted polling).
- web: previewStateStore (per-tab event application, dedupe,
  reconnect recovery); rightPanelStore arbitration.
2026-06-13 22:18:37 -07:00
Aiden Bai d6eb386e3d planning 2026-06-13 22:18:37 -07:00
HuakunandJulius Marminge d25090cf6d fix: avoid sending composer during IME enter (#2817)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:14:13 +00:00
Mika CohenandJulius Marminge ae39bacf0e Handle non-resumable pending user input (#2766)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 02:13:34 +00:00
Julius MarmingeandJulius Marminge 1ea17026ee [codex] fix slow websocket shutdown (#2869)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-12 01:39:25 +00:00
Julius Marmingeandcodex 649f4328ea [codex] Refine inline tool call timeline UI (#3052)
Co-authored-by: codex <[email protected]>
2026-06-11 18:18:27 -07:00
Magnus Alexander StrømsengandJulius Marminge 7db034905b fix(git): disable external diff for patch output (#2553)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-11 18:18:13 -07:00
Julius MarmingeandClaude Fable 5 57f6bf7edb Fix turn fold proejctions (#3041)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 23:51:43 -07:00
Julius Marmingeandcodex 0baf1986e8 [codex] Reduce Git status polling churn (#3037)
Co-authored-by: codex <[email protected]>
2026-06-10 17:10:19 -07:00
Julius Marmingeandcodex ae7e88b0e0 [codex] Sync app-server protocol, service tiers, and provider startup (#3036)
Co-authored-by: codex <[email protected]>
2026-06-10 16:24:19 -07:00
1916ac6d55 Rework message metadata, timestamps, and tool work log rows (#3022)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-06-10 14:38:42 -07:00
Julius Marmingeandcodex 343061a053 Misc chrome polish: header badges, plan sidebar, diff panel, empty state (#3027)
Co-authored-by: codex <[email protected]>
2026-06-10 12:25:03 -07:00
0b40ea62e1 Extract changed files card with compact aligned diff stats (#3023)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:27:32 +00:00
a4757c2656 Composer polish: focus ring, send/stop buttons, command menu, context meter, answer panel (#3018)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-10 08:02:32 +00:00
3efabdcd3a Polish web context menu fallback and sidebar icon actions (#3025)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 07:29:21 +00:00
c5f7cd40ba Polish branch picker trigger, scroll fade, and list layout (#3024)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-06-10 07:13:34 +00:00
e2db800f7c Provider env vars table and reworked accent color picker (#3026)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 23:27:59 -07:00
31533466b0 Model picker UI Improvements, Virtualize Model List (#3021)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-10 06:22:55 +00:00
7f741a56d1 Misc markdown styling improvements (#3017)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-06-09 21:21:58 -07:00
RuzbyteandJulius Marminge cc9e81ac93 fix(marketing) : marketing showing wrong icons on linux (#2696)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 20:04:36 -07:00
238715fd6f Polish dialog/alert surfaces and unauthenticated provider banner (#3016)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:52:16 -07:00
b03bc4b52d Mute icons in labeled controls and suppress popup focus rings (#3015)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 17:15:09 -07:00
aca14507f7 Bundle DM Sans and JetBrains Mono fonts instead of Google Fonts (#3014)
Co-authored-by: ss <[email protected]>
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-06-09 16:57:38 -07:00
t3-code[bot] 04f7f32ace chore(release): prepare v0.0.27 2026-06-09 21:14:36 +00:00
Julius Marmingeandcodex a3422a9bb5 Fix Clerk browser test mock (#3013)
Co-authored-by: codex <[email protected]>
2026-06-09 20:38:20 +00:00
Julius Marmingeandcodex 22f9f3058b [codex] Rebrand T3 Cloud as T3 Connect (#3011)
Co-authored-by: codex <[email protected]>
2026-06-09 12:25:02 -07:00
t3-code[bot] 983a8c7fa6 chore(release): prepare v0.0.26 2026-06-09 17:53:22 +00:00
Julius Marmingeandcodex de58ec8e24 Add Claude Fable 5 model (#3009)
Co-authored-by: codex <[email protected]>
2026-06-09 17:39:18 +00:00
Julius Marmingeandcodex 8e6f4229da [codex] Fix main CI Effect test runtimes (#3008)
Co-authored-by: codex <[email protected]>
2026-06-09 09:43:03 -07:00
Milosz JankiewiczandJulius Marminge 38ea6d483e feat(grok): add Grok CLI provider via ACP (#2809)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-09 09:28:40 -07:00
Julius Marmingeandcodex 0e4a43519f [codex] Extract infrastructure, telemetry, and test tooling (#2994)
Co-authored-by: codex <[email protected]>
2026-06-07 20:21:47 -07:00
416 changed files with 39860 additions and 6431 deletions

No files matched your search

+7 -2
View File
@@ -1,5 +1,5 @@
# Optional: T3 Cloud source builds
# Leave these unset to disable optional T3 Cloud features in local source builds.
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
@@ -10,3 +10,8 @@
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Public, ingest-only mobile OpenTelemetry configuration.
# T3CODE_MOBILE_OTLP_TRACES_URL=https://api.axiom.co/v1/traces
# T3CODE_MOBILE_OTLP_TRACES_DATASET=t3-code-mobile-traces-dev
# T3CODE_MOBILE_OTLP_TRACES_TOKEN=xaat-...
+1 -1
View File
@@ -1,4 +1,4 @@
name: Deploy T3 Cloud relay
name: Deploy T3 Connect relay
on:
push:
+1 -1
View File
@@ -167,7 +167,7 @@ jobs:
--github-output
relay_public_config:
name: Resolve T3 Cloud public config
name: Resolve T3 Connect public config
needs: preflight
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
+5 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.24",
"version": "0.0.27",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -20,13 +20,16 @@
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
"electron-updater": "^6.6.2",
"playwright-core": "1.60.0",
"react-grab": "^0.1.32"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"tailwindcss": "^4.0.0",
"vite-plus": "catalog:"
},
"productName": "T3 Code (Alpha)"
@@ -0,0 +1,40 @@
import { readFile, writeFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { compile } from "tailwindcss";
const directory = dirname(fileURLToPath(import.meta.url));
const appRoot = join(directory, "..");
const sourcePath = join(appRoot, "src", "preview", "Annotation.css");
const preloadPath = join(appRoot, "src", "preview", "PickPreload.ts");
const outputPath = join(appRoot, "src", "preview", "AnnotationStyles.generated.ts");
const require = createRequire(import.meta.url);
const tailwindRoot = dirname(require.resolve("tailwindcss/package.json"));
const [annotationSource, preloadSource, themeSource, preflightSource] = await Promise.all([
readFile(sourcePath, "utf8"),
readFile(preloadPath, "utf8"),
readFile(join(tailwindRoot, "theme.css"), "utf8"),
readFile(join(tailwindRoot, "preflight.css"), "utf8"),
]);
const candidates = new Set(
Array.from(preloadSource.matchAll(/!?-?[A-Za-z0-9_:@/.[\]()%,-]+/g), (match) => match[0]),
);
const compilerInput = [
themeSource,
preflightSource,
annotationSource.replace('@import "tailwindcss";', "@tailwind utilities;"),
].join("\n");
const compiler = await compile(compilerInput, { base: appRoot });
const css = compiler.build([...candidates]);
const encodedCss = `'${css
.replaceAll("\\", "\\\\")
.replaceAll("'", "\\'")
.replaceAll("\r", "\\r")
.replaceAll("\n", "\\n")}'`;
const moduleSource = `// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.\nexport const previewAnnotationStyles =\n ${encodedCss};\n`;
await writeFile(outputPath, moduleSource);
+7 -2
View File
@@ -2,7 +2,11 @@ import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import { desktopDir, resolveDevProtocolClient, resolveElectronPath } from "./electron-launcher.mjs";
import {
desktopDir,
resolveDevProtocolClient,
resolveElectronLaunchCommand,
} from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const devServerUrl = process.env.VITE_DEV_SERVER_URL?.trim();
@@ -79,7 +83,8 @@ function startApp() {
const launchArgs = devProtocolClient
? electronArgs
: [...electronArgs, `--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"];
const app = spawn(resolveElectronPath(), launchArgs, {
const electronCommand = resolveElectronLaunchCommand(launchArgs);
const app = spawn(electronCommand.electronPath, electronCommand.args, {
cwd: desktopDir,
env: childEnv,
stdio: "inherit",
@@ -307,6 +307,31 @@ function buildMacLauncher(electronBinaryPath) {
return targetBinaryPath;
}
function isLinuxSetuidSandboxConfigured(electronBinaryPath) {
if (process.platform !== "linux") {
return true;
}
const sandboxPath = join(dirname(electronBinaryPath), "chrome-sandbox");
try {
const sandboxStat = statSync(sandboxPath);
return sandboxStat.uid === 0 && (sandboxStat.mode & 0o4777) === 0o4755;
} catch {
return false;
}
}
function resolveLinuxSandboxArgs(electronBinaryPath) {
if (isLinuxSetuidSandboxConfigured(electronBinaryPath)) {
return [];
}
console.warn(
"[desktop-launcher] Electron chrome-sandbox is not root-owned with mode 4755; launching local Electron with --no-sandbox.",
);
return ["--no-sandbox"];
}
export function resolveElectronPath() {
ensureElectronRuntime();
@@ -320,6 +345,14 @@ export function resolveElectronPath() {
return buildMacLauncher(electronBinaryPath);
}
export function resolveElectronLaunchCommand(args = []) {
const electronPath = resolveElectronPath();
return {
electronPath,
args: [...resolveLinuxSandboxArgs(electronPath), ...args],
};
}
export function resolveDevProtocolClient() {
if (process.platform !== "darwin" || !isDevelopment) {
return null;
+3 -2
View File
@@ -1,15 +1,16 @@
import { spawn } from "node:child_process";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const __dirname = dirname(fileURLToPath(import.meta.url));
const desktopDir = resolve(__dirname, "..");
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
console.log("\nLaunching Electron smoke test...");
const child = spawn(electronBin, [mainJs], {
const electronCommand = resolveElectronLaunchCommand([mainJs]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: ["pipe", "pipe", "pipe"],
env: {
...process.env,
+3 -2
View File
@@ -1,11 +1,12 @@
import { spawn } from "node:child_process";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { desktopDir, resolveElectronLaunchCommand } from "./electron-launcher.mjs";
const childEnv = { ...process.env };
delete childEnv.ELECTRON_RUN_AS_NODE;
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
const electronCommand = resolveElectronLaunchCommand(["dist-electron/main.cjs"]);
const child = spawn(electronCommand.electronPath, electronCommand.args, {
stdio: "inherit",
cwd: desktopDir,
env: childEnv,
+1 -1
View File
@@ -176,7 +176,7 @@ const bootstrap = Effect.gen(function* () {
);
}
yield* installDesktopIpcHandlers;
yield* installDesktopIpcHandlers();
yield* logBootstrapInfo("bootstrap ipc handlers registered");
if (!(yield* Ref.get(state.quitting))) {
@@ -59,6 +59,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.savedEnvironmentRegistryPath, "/tmp/t3/dev/saved-environments.json");
assert.equal(environment.serverSettingsPath, "/tmp/t3/dev/settings.json");
assert.equal(environment.logDir, "/tmp/t3/dev/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/dev/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
@@ -89,6 +90,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.isDevelopment, false);
assert.equal(environment.stateDir, "/tmp/t3/userdata");
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
}),
);
@@ -49,6 +49,7 @@ export interface DesktopEnvironmentShape {
readonly savedEnvironmentRegistryPath: string;
readonly serverSettingsPath: string;
readonly logDir: string;
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
readonly backendEntryPath: string;
@@ -183,6 +184,7 @@ const makeDesktopEnvironment = Effect.fn("desktop.environment.make")(function* (
savedEnvironmentRegistryPath: path.join(stateDir, "saved-environments.json"),
serverSettingsPath: path.join(stateDir, "settings.json"),
logDir: path.join(stateDir, "logs"),
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.catch(() => Effect.succeed<string | null>(null)),
Effect.orElseSucceed(() => null),
);
const dnsName =
input.statusJson === undefined
@@ -44,6 +44,12 @@ function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextM
continue;
}
// Header items are decorative section labels for the web fallback only —
// Electron's native menu has no equivalent affordance, so we skip them.
if (sourceItem.header === true) {
continue;
}
const normalizedItem: ContextMenuItem = {
id: sourceItem.id,
label: sourceItem.label,
+7 -2
View File
@@ -48,9 +48,11 @@ import {
setTheme,
showContextMenu,
} from "./methods/window.ts";
import * as PreviewIpc from "./methods/preview.ts";
export const installDesktopIpcHandlers = Effect.gen(function* () {
export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
const ipc = yield* DesktopIpc.DesktopIpc;
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getLocalEnvironmentBootstrap);
@@ -92,4 +94,7 @@ export const installDesktopIpcHandlers = Effect.gen(function* () {
yield* ipc.handle(downloadUpdate);
yield* ipc.handle(installUpdate);
yield* ipc.handle(checkForUpdate);
}).pipe(Effect.withSpan("desktop.ipc.installHandlers"));
for (const previewMethod of PreviewIpc.methods) {
yield* ipc.handle(previewMethod);
}
});
+35
View File
@@ -39,3 +39,38 @@ export const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mod
export const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
export const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
export const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
export const PREVIEW_CREATE_TAB_CHANNEL = "desktop:preview-create-tab";
export const PREVIEW_CLOSE_TAB_CHANNEL = "desktop:preview-close-tab";
export const PREVIEW_REGISTER_WEBVIEW_CHANNEL = "desktop:preview-register-webview";
export const PREVIEW_NAVIGATE_CHANNEL = "desktop:preview-navigate";
export const PREVIEW_GO_BACK_CHANNEL = "desktop:preview-go-back";
export const PREVIEW_GO_FORWARD_CHANNEL = "desktop:preview-go-forward";
export const PREVIEW_REFRESH_CHANNEL = "desktop:preview-refresh";
export const PREVIEW_ZOOM_IN_CHANNEL = "desktop:preview-zoom-in";
export const PREVIEW_ZOOM_OUT_CHANNEL = "desktop:preview-zoom-out";
export const PREVIEW_RESET_ZOOM_CHANNEL = "desktop:preview-reset-zoom";
export const PREVIEW_HARD_RELOAD_CHANNEL = "desktop:preview-hard-reload";
export const PREVIEW_OPEN_DEVTOOLS_CHANNEL = "desktop:preview-open-devtools";
export const PREVIEW_CLEAR_COOKIES_CHANNEL = "desktop:preview-clear-cookies";
export const PREVIEW_CLEAR_CACHE_CHANNEL = "desktop:preview-clear-cache";
export const PREVIEW_GET_CONFIG_CHANNEL = "desktop:preview-get-config";
export const PREVIEW_SET_ANNOTATION_THEME_CHANNEL = "desktop:preview-set-annotation-theme";
export const PREVIEW_PICK_ELEMENT_CHANNEL = "desktop:preview-pick-element";
export const PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL = "desktop:preview-cancel-pick-element";
export const PREVIEW_CAPTURE_SCREENSHOT_CHANNEL = "desktop:preview-capture-screenshot";
export const PREVIEW_REVEAL_ARTIFACT_CHANNEL = "desktop:preview-reveal-artifact";
export const PREVIEW_COPY_ARTIFACT_CHANNEL = "desktop:preview-copy-artifact";
export const PREVIEW_AUTOMATION_STATUS_CHANNEL = "desktop:preview-automation-status";
export const PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL = "desktop:preview-automation-snapshot";
export const PREVIEW_AUTOMATION_CLICK_CHANNEL = "desktop:preview-automation-click";
export const PREVIEW_AUTOMATION_TYPE_CHANNEL = "desktop:preview-automation-type";
export const PREVIEW_AUTOMATION_PRESS_CHANNEL = "desktop:preview-automation-press";
export const PREVIEW_AUTOMATION_SCROLL_CHANNEL = "desktop:preview-automation-scroll";
export const PREVIEW_AUTOMATION_EVALUATE_CHANNEL = "desktop:preview-automation-evaluate";
export const PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL = "desktop:preview-automation-wait-for";
export const PREVIEW_RECORDING_START_CHANNEL = "desktop:preview-recording-start";
export const PREVIEW_RECORDING_STOP_CHANNEL = "desktop:preview-recording-stop";
export const PREVIEW_RECORDING_SAVE_CHANNEL = "desktop:preview-recording-save";
export const PREVIEW_RECORDING_FRAME_CHANNEL = "desktop:preview-recording-frame";
export const PREVIEW_STATE_CHANGE_CHANNEL = "desktop:preview-state-change";
export const PREVIEW_POINTER_EVENT_CHANNEL = "desktop:preview-pointer-event";
@@ -0,0 +1,54 @@
import { it as effectIt } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as PreviewManager from "../../preview/Manager.ts";
import * as PreviewIpc from "./preview.ts";
const { fromPartition } = vi.hoisted(() => ({
fromPartition: vi.fn(() => {
throw new Error("Session can only be received when app is ready");
}),
}));
vi.mock("electron", () => ({
BrowserWindow: {
getAllWindows: vi.fn(() => []),
},
session: {
fromPartition,
},
webContents: {
fromId: vi.fn(() => null),
},
}));
describe("preview IPC methods", () => {
beforeEach(() => {
fromPartition.mockClear();
});
it("does not access the Electron session while the module loads", async () => {
await expect(import("./preview.ts")).resolves.toBeDefined();
expect(fromPartition).not.toHaveBeenCalled();
});
effectIt.effect("rejects invalid webContents ids before resolving the preview service", () =>
Effect.map(
PreviewIpc.registerWebview
.handler({ tabId: "tab-1", webContentsId: 0 })
.pipe(Effect.provideService(PreviewManager.PreviewManager, null as never), Effect.exit),
(exit) => {
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Cause.findErrorOption(exit.cause);
expect(Option.isSome(error) && Schema.isSchemaError(error.value)).toBe(true);
expect(fromPartition).not.toHaveBeenCalled();
},
),
);
});
+377
View File
@@ -0,0 +1,377 @@
import {
DesktopPreviewAnnotationThemeInputSchema,
DesktopPreviewArtifactInputSchema,
DesktopPreviewAutomationClickInputSchema,
DesktopPreviewAutomationEvaluateInputSchema,
DesktopPreviewAutomationPressInputSchema,
DesktopPreviewAutomationScrollInputSchema,
DesktopPreviewAutomationTypeInputSchema,
DesktopPreviewAutomationWaitForInputSchema,
DesktopPreviewConfigInputSchema,
DesktopPreviewNavigateInputSchema,
DesktopPreviewRecordingArtifactSchema,
DesktopPreviewRecordingSaveInputSchema,
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { pathToFileURL } from "node:url";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import { makeIpcMethod } from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
});
export const createTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.createTab(tabId);
}),
});
export const closeTab = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.closeTab")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.closeTab(tabId);
}),
});
export const registerWebview = makeIpcMethod({
channel: IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL,
payload: DesktopPreviewRegisterWebviewInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.registerWebview")(function* ({ tabId, webContentsId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.registerWebview(tabId, webContentsId);
}),
});
export const navigate = makeIpcMethod({
channel: IpcChannels.PREVIEW_NAVIGATE_CHANNEL,
payload: DesktopPreviewNavigateInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.navigate")(function* ({ tabId, url }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.navigate(tabId, url);
}),
});
const tabMethod = (
channel: string,
name: string,
invoke: (
manager: PreviewManager.PreviewManagerShape,
tabId: string,
) => Effect.Effect<void, PreviewManager.PreviewManagerError>,
) =>
makeIpcMethod({
channel,
payload: DesktopPreviewTabInputSchema,
result: Schema.Void,
handler: Effect.fn(name)(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* invoke(manager, tabId);
}),
});
export const goBack = tabMethod(
IpcChannels.PREVIEW_GO_BACK_CHANNEL,
"desktop.ipc.preview.goBack",
(manager, tabId) => manager.goBack(tabId),
);
export const goForward = tabMethod(
IpcChannels.PREVIEW_GO_FORWARD_CHANNEL,
"desktop.ipc.preview.goForward",
(manager, tabId) => manager.goForward(tabId),
);
export const refresh = tabMethod(
IpcChannels.PREVIEW_REFRESH_CHANNEL,
"desktop.ipc.preview.refresh",
(manager, tabId) => manager.refresh(tabId),
);
export const zoomIn = tabMethod(
IpcChannels.PREVIEW_ZOOM_IN_CHANNEL,
"desktop.ipc.preview.zoomIn",
(manager, tabId) => manager.zoomIn(tabId),
);
export const zoomOut = tabMethod(
IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL,
"desktop.ipc.preview.zoomOut",
(manager, tabId) => manager.zoomOut(tabId),
);
export const resetZoom = tabMethod(
IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL,
"desktop.ipc.preview.resetZoom",
(manager, tabId) => manager.resetZoom(tabId),
);
export const hardReload = tabMethod(
IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL,
"desktop.ipc.preview.hardReload",
(manager, tabId) => manager.hardReload(tabId),
);
export const openDevTools = tabMethod(
IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL,
"desktop.ipc.preview.openDevTools",
(manager, tabId) => manager.openDevTools(tabId),
);
export const cancelPickElement = tabMethod(
IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL,
"desktop.ipc.preview.cancelPickElement",
(manager, tabId) => manager.cancelPickElement(tabId),
);
export const startRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_START_CHANNEL,
"desktop.ipc.preview.startRecording",
(manager, tabId) => manager.startRecording(tabId),
);
export const stopRecording = tabMethod(
IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL,
"desktop.ipc.preview.stopRecording",
(manager, tabId) => manager.stopRecording(tabId),
);
export const clearCookies = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCookies")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCookies();
}),
});
export const clearCache = makeIpcMethod({
channel: IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL,
payload: Schema.Void,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.clearCache")(function* () {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.clearCache();
}),
});
export const getPreviewConfig = makeIpcMethod({
channel: IpcChannels.PREVIEW_GET_CONFIG_CHANNEL,
payload: DesktopPreviewConfigInputSchema,
result: DesktopPreviewWebviewConfigSchema,
handler: Effect.fn("desktop.ipc.preview.getConfig")(function* ({ environmentId }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.getBrowserSession(environmentId);
return {
partition: yield* manager.getBrowserPartition(environmentId),
webPreferences: PREVIEW_WEBVIEW_PREFERENCES,
preloadUrl: pathToFileURL(`${__dirname}/preview-pick-preload.cjs`).href,
};
}),
});
export const setAnnotationTheme = makeIpcMethod({
channel: IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL,
payload: DesktopPreviewAnnotationThemeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.setAnnotationTheme")(function* ({ theme }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.setAnnotationTheme(theme);
}),
});
export const pickElement = makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
}),
});
export const captureScreenshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: DesktopPreviewScreenshotArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.captureScreenshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.captureScreenshot(tabId);
}),
});
export const revealArtifact = makeIpcMethod({
channel: IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.revealArtifact")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.revealArtifact(path);
}),
});
export const copyArtifactToClipboard = makeIpcMethod({
channel: IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL,
payload: DesktopPreviewArtifactInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.copyArtifactToClipboard")(function* ({ path }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.copyArtifactToClipboard(path);
}),
});
export const automationStatus = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationStatus,
handler: Effect.fn("desktop.ipc.preview.automationStatus")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationStatus(tabId);
}),
});
export const automationSnapshot = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: PreviewAutomationSnapshot,
handler: Effect.fn("desktop.ipc.preview.automationSnapshot")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationSnapshot(tabId);
}),
});
export const automationClick = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL,
payload: DesktopPreviewAutomationClickInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationClick")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationClick(tabId, input);
}),
});
export const automationType = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL,
payload: DesktopPreviewAutomationTypeInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationType")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationType(tabId, input);
}),
});
export const automationPress = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL,
payload: DesktopPreviewAutomationPressInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationPress")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationPress(tabId, input);
}),
});
export const automationScroll = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL,
payload: DesktopPreviewAutomationScrollInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationScroll")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationScroll(tabId, input);
}),
});
export const automationEvaluate = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL,
payload: DesktopPreviewAutomationEvaluateInputSchema,
result: Schema.Unknown,
handler: Effect.fn("desktop.ipc.preview.automationEvaluate")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.automationEvaluate(tabId, input);
}),
});
export const automationWaitFor = makeIpcMethod({
channel: IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL,
payload: DesktopPreviewAutomationWaitForInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.automationWaitFor")(function* ({ tabId, input }) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.automationWaitFor(tabId, input);
}),
});
export const saveRecording = makeIpcMethod({
channel: IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL,
payload: DesktopPreviewRecordingSaveInputSchema,
result: DesktopPreviewRecordingArtifactSchema,
handler: Effect.fn("desktop.ipc.preview.saveRecording")(function* ({ tabId, mimeType, data }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.saveRecording(tabId, mimeType, data);
}),
});
export const methods = [
createTab,
closeTab,
registerWebview,
navigate,
goBack,
goForward,
refresh,
zoomIn,
zoomOut,
resetZoom,
hardReload,
openDevTools,
clearCookies,
clearCache,
getPreviewConfig,
setAnnotationTheme,
pickElement,
cancelPickElement,
captureScreenshot,
revealArtifact,
copyArtifactToClipboard,
automationStatus,
automationSnapshot,
automationClick,
automationType,
automationPress,
automationScroll,
automationEvaluate,
automationWaitFor,
startRecording,
stopRecording,
saveRecording,
] as const;
+11 -1
View File
@@ -44,6 +44,8 @@ import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
import * as DesktopState from "./app/DesktopState.ts";
import * as DesktopUpdates from "./updates/DesktopUpdates.ts";
import * as PreviewBrowserSession from "./preview/BrowserSession.ts";
import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
const desktopEnvironmentLayer = Layer.unwrap(
@@ -127,7 +129,15 @@ const desktopServerExposureLayer = DesktopServerExposure.layer.pipe(
Layer.provideMerge(desktopFoundationLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(Layer.provideMerge(desktopServerExposureLayer));
const desktopPreviewLayer = PreviewManager.layer.pipe(
Layer.provideMerge(PreviewBrowserSession.layer),
Layer.provideMerge(desktopFoundationLayer),
);
const desktopWindowLayer = DesktopWindow.layer.pipe(
Layer.provideMerge(desktopServerExposureLayer),
Layer.provideMerge(desktopPreviewLayer),
);
const desktopBackendLayer = DesktopBackendManager.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
+99 -1
View File
@@ -1,4 +1,9 @@
import type { DesktopBridge } from "@t3tools/contracts";
import type {
DesktopBridge,
DesktopPreviewPointerEvent,
DesktopPreviewRecordingFrame,
DesktopPreviewTabState,
} from "@t3tools/contracts";
import { contextBridge, ipcRenderer } from "electron";
import * as IpcChannels from "./ipc/channels.ts";
@@ -141,4 +146,97 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.UPDATE_STATE_CHANNEL, wrappedListener);
};
},
preview: {
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
registerWebview: (tabId, webContentsId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
navigate: (tabId, url) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_NAVIGATE_CHANNEL, { tabId, url }),
goBack: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_BACK_CHANNEL, { tabId }),
goForward: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_GO_FORWARD_CHANNEL, { tabId }),
refresh: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_REFRESH_CHANNEL, { tabId }),
zoomIn: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_IN_CHANNEL, { tabId }),
zoomOut: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_ZOOM_OUT_CHANNEL, { tabId }),
resetZoom: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_RESET_ZOOM_CHANNEL, { tabId }),
hardReload: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_HARD_RELOAD_CHANNEL, { tabId }),
openDevTools: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_OPEN_DEVTOOLS_CHANNEL, { tabId }),
clearCookies: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_COOKIES_CHANNEL),
clearCache: () => ipcRenderer.invoke(IpcChannels.PREVIEW_CLEAR_CACHE_CHANNEL),
getPreviewConfig: (environmentId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_GET_CONFIG_CHANNEL, { environmentId }),
setAnnotationTheme: (theme) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_SET_ANNOTATION_THEME_CHANNEL, { theme }),
pickElement: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL, { tabId }),
cancelPickElement: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CANCEL_PICK_ELEMENT_CHANNEL, { tabId }),
captureScreenshot: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CAPTURE_SCREENSHOT_CHANNEL, { tabId }),
revealArtifact: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REVEAL_ARTIFACT_CHANNEL, { path }),
copyArtifactToClipboard: (path) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_COPY_ARTIFACT_CHANNEL, { path }),
recording: {
startScreencast: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_START_CHANNEL, { tabId }),
stopScreencast: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_STOP_CHANNEL, { tabId }),
save: (tabId, mimeType, data) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_RECORDING_SAVE_CHANNEL, {
tabId,
mimeType,
data,
}),
onFrame: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, frame: unknown) => {
if (typeof frame !== "object" || frame === null) return;
listener(frame as DesktopPreviewRecordingFrame);
};
ipcRenderer.on(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, wrappedListener);
},
},
automation: {
status: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_STATUS_CHANNEL, { tabId }),
snapshot: (tabId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SNAPSHOT_CHANNEL, { tabId }),
click: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_CLICK_CHANNEL, { tabId, input }),
type: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_TYPE_CHANNEL, { tabId, input }),
press: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_PRESS_CHANNEL, { tabId, input }),
scroll: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_SCROLL_CHANNEL, { tabId, input }),
evaluate: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_EVALUATE_CHANNEL, { tabId, input }),
waitFor: (tabId, input) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_AUTOMATION_WAIT_FOR_CHANNEL, { tabId, input }),
},
onStateChange: (listener) => {
const wrappedListener = (
_event: Electron.IpcRendererEvent,
tabId: unknown,
state: unknown,
) => {
if (typeof tabId !== "string" || typeof state !== "object" || state === null) return;
listener(tabId, state as DesktopPreviewTabState);
};
ipcRenderer.on(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, wrappedListener);
},
onPointerEvent: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, pointerEvent: unknown) => {
if (typeof pointerEvent !== "object" || pointerEvent === null) return;
listener(pointerEvent as DesktopPreviewPointerEvent);
};
ipcRenderer.on(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
return () =>
ipcRenderer.removeListener(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, wrappedListener);
},
},
} satisfies DesktopBridge);
+1
View File
@@ -0,0 +1 @@
import "./preview/PickPreload.ts";
+68
View File
@@ -0,0 +1,68 @@
@import "tailwindcss";
@theme inline {
--font-sans: var(--t3-font-sans);
--font-mono: var(--t3-font-mono);
--color-background: var(--t3-background);
--color-foreground: var(--t3-foreground);
--color-popover: var(--t3-popover);
--color-popover-foreground: var(--t3-popover-foreground);
--color-primary: var(--t3-primary);
--color-primary-foreground: var(--t3-primary-foreground);
--color-muted: var(--t3-muted);
--color-muted-foreground: var(--t3-muted-foreground);
--color-accent: var(--t3-accent);
--color-accent-foreground: var(--t3-accent-foreground);
--color-border: var(--t3-border);
--color-input: var(--t3-input);
--color-ring: var(--t3-ring);
--radius-sm: calc(var(--t3-radius) - 4px);
--radius-md: calc(var(--t3-radius) - 2px);
--radius-lg: var(--t3-radius);
--radius-xl: calc(var(--t3-radius) + 4px);
--radius-2xl: calc(var(--t3-radius) + 8px);
}
:host {
--t3-font-sans:
"DM Sans Variable", "DM Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui,
sans-serif;
--t3-font-mono:
"SF Mono", "SFMono-Regular", "JetBrains Mono", Consolas, "Liberation Mono", Menlo, monospace;
--t3-radius: 0.625rem;
--t3-background: white;
--t3-foreground: oklch(0.269 0 0);
--t3-popover: white;
--t3-popover-foreground: oklch(0.269 0 0);
--t3-primary: oklch(0.488 0.217 264);
--t3-primary-foreground: white;
--t3-muted: rgb(0 0 0 / 4%);
--t3-muted-foreground: oklch(0.556 0 0);
--t3-accent: rgb(0 0 0 / 4%);
--t3-accent-foreground: oklch(0.269 0 0);
--t3-border: rgb(0 0 0 / 8%);
--t3-input: rgb(0 0 0 / 10%);
--t3-ring: oklch(0.488 0.217 264);
color: var(--t3-foreground);
font-family: var(--t3-font-sans);
}
* {
box-sizing: border-box;
border-color: var(--t3-border);
}
button,
input,
select,
textarea {
font: inherit;
}
button:focus-visible,
input:focus-visible,
select:focus-visible,
textarea:focus-visible {
outline: 2px solid color-mix(in srgb, var(--t3-ring) 72%, transparent);
outline-offset: 1px;
}
@@ -0,0 +1,3 @@
// Generated by scripts/build-preview-annotation-css.mjs. Do not edit.
export const previewAnnotationStyles =
'/*! tailwindcss v4.3.0 | MIT License | https://tailwindcss.com */\n@layer properties;\n:root, :host {\n --spacing: 0.25rem;\n --text-xs: 0.75rem;\n --text-xs--line-height: calc(1 / 0.75);\n --text-sm: 0.875rem;\n --text-sm--line-height: calc(1.25 / 0.875);\n --text-lg: 1.125rem;\n --text-lg--line-height: calc(1.75 / 1.125);\n --font-weight-medium: 500;\n --font-weight-semibold: 600;\n --font-weight-bold: 700;\n --blur-xl: 24px;\n --default-font-family: var(--t3-font-sans);\n --default-mono-font-family: var(--t3-font-mono);\n}\n*, ::after, ::before, ::backdrop, ::file-selector-button {\n box-sizing: border-box;\n margin: 0;\n padding: 0;\n border: 0 solid;\n}\nhtml, :host {\n line-height: 1.5;\n -webkit-text-size-adjust: 100%;\n tab-size: 4;\n font-family: var(--default-font-family, ui-sans-serif, system-ui, sans-serif, \'Apple Color Emoji\', \'Segoe UI Emoji\', \'Segoe UI Symbol\', \'Noto Color Emoji\');\n font-feature-settings: var(--default-font-feature-settings, normal);\n font-variation-settings: var(--default-font-variation-settings, normal);\n -webkit-tap-highlight-color: transparent;\n}\nhr {\n height: 0;\n color: inherit;\n border-top-width: 1px;\n}\nabbr:where([title]) {\n -webkit-text-decoration: underline dotted;\n text-decoration: underline dotted;\n}\nh1, h2, h3, h4, h5, h6 {\n font-size: inherit;\n font-weight: inherit;\n}\na {\n color: inherit;\n -webkit-text-decoration: inherit;\n text-decoration: inherit;\n}\nb, strong {\n font-weight: bolder;\n}\ncode, kbd, samp, pre {\n font-family: var(--default-mono-font-family, ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \'Liberation Mono\', \'Courier New\', monospace);\n font-feature-settings: var(--default-mono-font-feature-settings, normal);\n font-variation-settings: var(--default-mono-font-variation-settings, normal);\n font-size: 1em;\n}\nsmall {\n font-size: 80%;\n}\nsub, sup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsub {\n bottom: -0.25em;\n}\nsup {\n top: -0.5em;\n}\ntable {\n text-indent: 0;\n border-color: inherit;\n border-collapse: collapse;\n}\n:-moz-focusring {\n outline: auto;\n}\nprogress {\n vertical-align: baseline;\n}\nsummary {\n display: list-item;\n}\nol, ul, menu {\n list-style: none;\n}\nimg, svg, video, canvas, audio, iframe, embed, object {\n display: block;\n vertical-align: middle;\n}\nimg, video {\n max-width: 100%;\n height: auto;\n}\nbutton, input, select, optgroup, textarea, ::file-selector-button {\n font: inherit;\n font-feature-settings: inherit;\n font-variation-settings: inherit;\n letter-spacing: inherit;\n color: inherit;\n border-radius: 0;\n background-color: transparent;\n opacity: 1;\n}\n:where(select:is([multiple], [size])) optgroup {\n font-weight: bolder;\n}\n:where(select:is([multiple], [size])) optgroup option {\n padding-inline-start: 20px;\n}\n::file-selector-button {\n margin-inline-end: 4px;\n}\n::placeholder {\n opacity: 1;\n}\n@supports (not (-webkit-appearance: -apple-pay-button)) or (contain-intrinsic-size: 1px) {\n ::placeholder {\n color: currentcolor;\n @supports (color: color-mix(in lab, red, red)) {\n color: color-mix(in oklab, currentcolor 50%, transparent);\n }\n }\n}\ntextarea {\n resize: vertical;\n}\n::-webkit-search-decoration {\n -webkit-appearance: none;\n}\n::-webkit-date-and-time-value {\n min-height: 1lh;\n text-align: inherit;\n}\n::-webkit-datetime-edit {\n display: inline-flex;\n}\n::-webkit-datetime-edit-fields-wrapper {\n padding: 0;\n}\n::-webkit-datetime-edit, ::-webkit-datetime-edit-year-field, ::-webkit-datetime-edit-month-field, ::-webkit-datetime-edit-day-field, ::-webkit-datetime-edit-hour-field, ::-webkit-datetime-edit-minute-field, ::-webkit-datetime-edit-second-field, ::-webkit-datetime-edit-millisecond-field, ::-webkit-datetime-edit-meridiem-field {\n padding-block: 0;\n}\n::-webkit-calendar-picker-indicator {\n line-height: 1;\n}\n:-moz-ui-invalid {\n box-shadow: none;\n}\nbutton, input:where([type=\'button\'], [type=\'reset\'], [type=\'submit\']), ::file-selector-button {\n appearance: button;\n}\n::-webkit-inner-spin-button, ::-webkit-outer-spin-button {\n height: auto;\n}\n[hidden]:where(:not([hidden=\'until-found\'])) {\n display: none !important;\n}\n.pointer-events-auto {\n pointer-events: auto;\n}\n.pointer-events-none {\n pointer-events: none;\n}\n.absolute {\n position: absolute;\n}\n.fixed {\n position: fixed;\n}\n.inset-0 {\n inset: calc(var(--spacing) * 0);\n}\n.top-1\\/2 {\n top: calc(1 / 2 * 100%);\n}\n.top-2\\.5 {\n top: calc(var(--spacing) * 2.5);\n}\n.right-2 {\n right: calc(var(--spacing) * 2);\n}\n.left-1\\/2 {\n left: calc(1 / 2 * 100%);\n}\n.z-1 {\n z-index: 1;\n}\n.block {\n display: block;\n}\n.flex {\n display: flex;\n}\n.grid {\n display: grid;\n}\n.hidden {\n display: none;\n}\n.inline-flex {\n display: inline-flex;\n}\n.h-7 {\n height: calc(var(--spacing) * 7);Line truncated
@@ -0,0 +1,83 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { fromPartition, sessions } = vi.hoisted(() => ({
fromPartition: vi.fn(),
sessions: new Map<
string,
{
readonly clearCache: ReturnType<typeof vi.fn>;
readonly clearStorageData: ReturnType<typeof vi.fn>;
readonly getUserAgent: ReturnType<typeof vi.fn>;
readonly setPermissionRequestHandler: ReturnType<typeof vi.fn>;
readonly setUserAgent: ReturnType<typeof vi.fn>;
}
>(),
}));
vi.mock("electron", () => ({
session: {
fromPartition,
},
}));
import * as BrowserSession from "./BrowserSession.ts";
const layer = BrowserSession.layer.pipe(Layer.provide(NodeServices.layer));
describe("BrowserSession", () => {
beforeEach(() => {
sessions.clear();
fromPartition.mockReset();
fromPartition.mockImplementation((partition: string) => {
const browserSession = {
clearCache: vi.fn(() => Promise.resolve()),
clearStorageData: vi.fn(() => Promise.resolve()),
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/0.0.27"),
setPermissionRequestHandler: vi.fn(),
setUserAgent: vi.fn(),
};
sessions.set(partition, browserSession);
return browserSession;
});
});
it.effect("derives deterministic partitions and memoizes sessions", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("scope-a");
const first = yield* browserSessions.getSession("scope-a");
const second = yield* browserSessions.getSession("scope-a");
assert.strictEqual(partition, "persist:t3code-preview-f051bb2c68cb7b2fe969");
assert.strictEqual(first, second);
assert.strictEqual(fromPartition.mock.calls.length, 1);
}).pipe(Effect.provide(layer)),
);
it.effect("clears storage and cache for every created session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
yield* browserSessions.getSession("scope-a");
yield* browserSessions.getSession("scope-b");
yield* browserSessions.clearCookies();
yield* browserSessions.clearCache();
assert.strictEqual(sessions.size, 2);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
assert.deepEqual(browserSession.clearStorageData.mock.calls[0], [
{
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
},
]);
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
}
}).pipe(Effect.provide(layer)),
);
});
+107
View File
@@ -0,0 +1,107 @@
import type { Session } from "electron";
import { session } from "electron";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionError extends Data.TaggedError("BrowserSessionError")<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Desktop preview browser session operation failed: ${this.operation}`;
}
}
export interface BrowserSessionShape {
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
}
export class BrowserSession extends Context.Service<BrowserSession, BrowserSessionShape>()(
"@t3tools/desktop/preview/BrowserSession",
) {}
const make = Effect.gen(function* BrowserSessionMake() {
const crypto = yield* Crypto.Crypto;
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(scope))
.pipe(
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
});
const getSession = Effect.fn("BrowserSession.getSession")(function* (scope = "shared") {
const partition = yield* getPartition(scope);
return yield* SynchronizedRef.modifyEffect(sessionsRef, (sessions) => {
const existing = sessions.get(partition);
if (existing) return Effect.succeed([existing, sessions] as const);
return Effect.try({
try: () => {
const browserSession = session.fromPartition(partition);
const userAgent = browserSession
.getUserAgent()
.replace(/Electron\/[\d.]+ /, "")
.replace(/\s*t3code\/[\d.]+/, "");
browserSession.setUserAgent(userAgent);
browserSession.setPermissionRequestHandler((_webContents, permission, callback) => {
const allowed = ["clipboard-read", "clipboard-write", "notifications", "geolocation"];
callback(allowed.includes(permission));
});
const next = new Map(sessions);
next.set(partition, browserSession);
return [browserSession, next] as const;
},
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
});
});
});
return BrowserSession.of({
getPartition,
isPartition: (partition) => partition.startsWith(PREVIEW_PARTITION_PREFIX),
getSession,
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.values()].map((browserSession) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
}),
),
{ concurrency: "unbounded", discard: true },
);
}),
});
}).pipe(Effect.withSpan("BrowserSession.make"));
export const layer = Layer.effect(BrowserSession, make);
@@ -0,0 +1,6 @@
export const START_PICK_CHANNEL = "preview:start-pick";
export const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
+374
View File
@@ -0,0 +1,374 @@
import { it as effectIt } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import type * as Scope from "effect/Scope";
import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn(() => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
writeImage,
},
nativeImage: {
createFromPath,
},
shell: {
showItemInFolder,
},
session: {
fromPartition: vi.fn(),
},
webContents: {
fromId,
},
}));
const browserSessionLayer = Layer.succeed(
BrowserSession.BrowserSession,
BrowserSession.BrowserSession.of({
getPartition: () => Effect.succeed("persist:t3code-preview-test"),
isPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getSession: () => Effect.die("unexpected getSession"),
clearCookies: () => Effect.void,
clearCache: () => Effect.void,
}),
);
const environmentLayer = Layer.succeed(
DesktopEnvironment.DesktopEnvironment,
DesktopEnvironment.DesktopEnvironment.of({
browserArtifactsDir: "/tmp/t3/dev/browser-artifacts",
} as DesktopEnvironment.DesktopEnvironmentShape),
);
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: (path) =>
Effect.sync(() => {
mkdir(path);
}),
writeFile: (path, data) =>
Effect.sync(() => {
writeFile(path, data);
}),
});
const layer = PreviewManager.layer.pipe(
Layer.provideMerge(browserSessionLayer),
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
);
const withManager = <A>(
use: (
manager: PreviewManager.PreviewManagerShape,
) => Effect.Effect<A, PreviewManager.PreviewManagerError, Scope.Scope>,
) =>
Effect.gen(function* () {
const manager = yield* PreviewManager.PreviewManager;
return yield* use(manager);
}).pipe(Effect.provide(layer), Effect.scoped);
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
writeImage.mockClear();
createFromPath.mockClear();
webviewSend.mockClear();
});
effectIt.effect("reports an unregistered webview as temporarily unavailable", () =>
withManager((manager) =>
Effect.gen(function* () {
expect(yield* manager.automationStatus("tab_1")).toEqual({
available: false,
visible: true,
tabId: "tab_1",
url: null,
title: null,
loading: false,
});
yield* manager.createTab("tab_1");
expect(yield* manager.automationStatus("tab_1")).toEqual({
available: false,
visible: true,
tabId: "tab_1",
url: null,
title: null,
loading: false,
});
expect(fromId).not.toHaveBeenCalled();
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
const png = Buffer.from("preview-png");
const capturePage = vi.fn(async () => ({ toPNG: () => png }));
const listeners = new Map<string, (...args: never[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com:8443/path?query=value",
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
capturePage,
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
expect(webviewSend).toHaveBeenCalledWith(
"preview:annotation-theme",
expect.objectContaining({
colorScheme: "light",
primary: "oklch(0.488 0.217 264)",
}),
);
const artifact = yield* manager.captureScreenshot("tab_1");
expect(capturePage).toHaveBeenCalledOnce();
expect(mkdir).toHaveBeenCalledWith("/tmp/t3/dev/browser-artifacts");
expect(writeFile).toHaveBeenCalledWith(artifact.path, png);
expect(artifact).toMatchObject({
tabId: "tab_1",
mimeType: "image/png",
sizeBytes: png.byteLength,
});
expect(artifact.path).toMatch(
/\/browser-artifacts\/browser-screenshot-example-com-[^.]+\.png$/,
);
}),
),
);
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
withManager((manager) =>
Effect.gen(function* () {
yield* manager.revealArtifact("/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png");
expect(showItemInFolder).toHaveBeenCalledWith(
"/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png",
);
const exit = yield* Effect.exit(manager.revealArtifact("/tmp/t3/dev/settings.json"));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
);
effectIt.effect("copies screenshot artifacts to the system clipboard", () =>
withManager((manager) =>
Effect.gen(function* () {
const artifactPath = "/tmp/t3/dev/browser-artifacts/browser-screenshot-test.png";
yield* manager.copyArtifactToClipboard(artifactPath);
expect(createFromPath).toHaveBeenCalledWith(artifactPath);
expect(writeImage).toHaveBeenCalledOnce();
const exit = yield* Effect.exit(
manager.copyArtifactToClipboard("/tmp/t3/dev/settings.json"),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
message: "Preview artifact path is outside the configured artifact directory.",
});
}),
),
);
effectIt.effect("emits the resolved pointer target before dispatching an automation click", () =>
withManager((manager) =>
Effect.gen(function* () {
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const activity: string[] = [];
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (method === "Runtime.evaluate") {
return {
result: {
value: { width: 800, height: 600 },
},
};
}
if (method === "Input.dispatchMouseEvent" && params?.type === "mousePressed") {
activity.push("mousePressed");
humanInput?.({}, { kind: "pointer", x: params.x, y: params.y, button: 0 });
}
return undefined;
});
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
.automationClick("tab_1", { x: 120, y: 80 })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust(200);
yield* Fiber.join(click);
expect(activity).toEqual(["move", "click", "mousePressed"]);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
type: "mousePressed",
x: 120,
y: 80,
button: "left",
clickCount: 1,
});
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
type: "mouseReleased",
x: 120,
y: 80,
button: "left",
clickCount: 1,
});
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string) => {
if (method === "Runtime.evaluate") {
return {
result: {
value: { width: 800, height: 600 },
},
};
}
if (method === "Input.dispatchMouseEvent") {
humanInput?.({}, { kind: "pointer", x: 400, y: 300, button: 0 });
}
return undefined;
});
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
.automationClick("tab_1", { x: 120, y: 80 })
.pipe(Effect.forkChild({ startImmediately: true }));
yield* TestClock.adjust(200);
const exit = yield* Fiber.await(click);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isSuccess(exit)) return;
const error = Option.getOrThrow(Cause.findErrorOption(exit.cause));
expect(error.cause).toMatchObject({
name: "PreviewAutomationControlInterruptedError",
});
}),
),
);
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,46 @@
/**
* Pure clamp/flip math for the floating label that follows the cursor while
* the user is picking an element in the in-app browser. Lives in its own
* electron-free module so the geometry can be unit-tested without spinning
* up an Electron preload context (`PickPreload.ts` itself imports
* `electron` and `react-grab/primitives`, which can't load under vitest).
*
* - Horizontally pins the label to `targetLeft`, clamped into
* `[VIEWPORT_MARGIN, viewportWidth - labelWidth - VIEWPORT_MARGIN]`.
* - Vertically prefers above the target. If the label would overflow the
* top, flips below; if THAT also overflows the bottom, pins to the
* bottom margin (better to overlap the highlight than disappear).
*/
/** Distance in CSS pixels between the highlight and the floating label. */
export const LABEL_GAP = 4;
/** Minimum padding the label keeps from any viewport edge. */
export const VIEWPORT_MARGIN = 4;
export function computeLabelPosition(input: {
targetLeft: number;
targetTop: number;
targetBottom: number;
labelWidth: number;
labelHeight: number;
viewportWidth: number;
viewportHeight: number;
}): { x: number; y: number } {
const { targetLeft, targetTop, targetBottom, labelWidth, labelHeight } = input;
const { viewportWidth, viewportHeight } = input;
let x = targetLeft;
const maxX = viewportWidth - labelWidth - VIEWPORT_MARGIN;
if (x > maxX) x = maxX;
if (x < VIEWPORT_MARGIN) x = VIEWPORT_MARGIN;
let y = targetTop - labelHeight - LABEL_GAP;
if (y < VIEWPORT_MARGIN) {
y = targetBottom + LABEL_GAP;
if (y + labelHeight > viewportHeight - VIEWPORT_MARGIN) {
y = Math.max(VIEWPORT_MARGIN, viewportHeight - labelHeight - VIEWPORT_MARGIN);
}
}
return { x, y };
}
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vite-plus/test";
import { computeLabelPosition } from "./PickLabelPosition.ts";
const VIEWPORT = { viewportWidth: 1280, viewportHeight: 800 };
describe("computeLabelPosition", () => {
it("anchors to the element's top-left when there's room above and to the right", () => {
const { x, y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 200,
targetBottom: 240,
labelWidth: 120,
labelHeight: 18,
});
expect(x).toBe(200);
// 200 (top) - 18 (height) - 4 (gap)
expect(y).toBe(200 - 18 - 4);
});
it("clamps left edge so the label stays inside the viewport", () => {
const { x } = computeLabelPosition({
...VIEWPORT,
targetLeft: -50,
targetTop: 200,
targetBottom: 240,
labelWidth: 120,
labelHeight: 18,
});
expect(x).toBe(4);
});
it("clamps right edge when the label would overflow the viewport (the bug we shipped)", () => {
const { x } = computeLabelPosition({
...VIEWPORT,
targetLeft: 1240,
targetTop: 200,
targetBottom: 240,
labelWidth: 200,
labelHeight: 18,
});
// viewportWidth (1280) - labelWidth (200) - margin (4) = 1076
expect(x).toBe(1076);
});
it("flips the label below the element when there's no room above", () => {
const { y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 4,
targetBottom: 44,
labelWidth: 120,
labelHeight: 18,
});
// labelY = 4 - 18 - 4 = -18 → flip → 44 + 4 = 48
expect(y).toBe(48);
});
it("pins to the bottom margin when the element fills the viewport (no room above OR below)", () => {
const { y } = computeLabelPosition({
...VIEWPORT,
targetLeft: 200,
targetTop: 0,
targetBottom: 800,
labelWidth: 120,
labelHeight: 18,
});
// Above overflows top → flip below = 800 + 4 = 804 → also overflows
// bottom → pin to viewportHeight - labelHeight - margin = 778.
expect(y).toBe(800 - 18 - 4);
});
it("never returns a negative coordinate", () => {
const { x, y } = computeLabelPosition({
...VIEWPORT,
targetLeft: -1000,
targetTop: -1000,
targetBottom: -900,
labelWidth: 5000,
labelHeight: 5000,
});
expect(x).toBeGreaterThanOrEqual(0);
expect(y).toBeGreaterThanOrEqual(0);
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,201 @@
import { describe, expect, it } from "vite-plus/test";
import { isPickedElementPayload, isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
function validPayload(overrides?: Record<string, unknown>): Record<string, unknown> {
return {
pageUrl: "https://example.com/",
pageTitle: "Example",
tagName: "button",
selector: "button.submit",
htmlPreview: "<button>Save</button>",
componentName: "SubmitButton",
source: {
functionName: "SubmitButton",
fileName: "/repo/src/Button.tsx",
lineNumber: 12,
columnNumber: 5,
},
stack: [
{
functionName: "SubmitButton",
fileName: "/repo/src/Button.tsx",
lineNumber: 12,
columnNumber: 5,
},
],
styles: ".submit { color: white; }",
pickedAt: "2026-05-03T18:00:00.000Z",
...overrides,
};
}
describe("isPickedElementPayload", () => {
it("accepts a complete, well-typed payload", () => {
expect(isPickedElementPayload(validPayload())).toBe(true);
});
it("accepts nullable string fields when null", () => {
expect(
isPickedElementPayload(
validPayload({ pageTitle: null, selector: null, componentName: null, source: null }),
),
).toBe(true);
});
it("accepts an empty stack array", () => {
expect(isPickedElementPayload(validPayload({ stack: [] }))).toBe(true);
});
it("accepts stack frames with null fields", () => {
expect(
isPickedElementPayload(
validPayload({
stack: [
{
functionName: null,
fileName: null,
lineNumber: null,
columnNumber: null,
},
],
}),
),
).toBe(true);
});
it("rejects null and primitive inputs", () => {
expect(isPickedElementPayload(null)).toBe(false);
expect(isPickedElementPayload(undefined)).toBe(false);
expect(isPickedElementPayload("string")).toBe(false);
expect(isPickedElementPayload(42)).toBe(false);
expect(isPickedElementPayload([])).toBe(false);
});
it.each<[string, Record<string, unknown>]>([
["missing pageUrl", validPayload({ pageUrl: undefined })],
["wrong-type pageUrl", validPayload({ pageUrl: 123 })],
["missing tagName", validPayload({ tagName: undefined })],
["missing htmlPreview", validPayload({ htmlPreview: undefined })],
["missing styles", validPayload({ styles: undefined })],
["missing pickedAt", validPayload({ pickedAt: undefined })],
["wrong-type pageTitle", validPayload({ pageTitle: 99 })],
["wrong-type selector", validPayload({ selector: 99 })],
["wrong-type componentName", validPayload({ componentName: 99 })],
])("rejects payloads with %s", (_label, value) => {
expect(isPickedElementPayload(value)).toBe(false);
});
it("rejects malformed source frames", () => {
expect(
isPickedElementPayload(
validPayload({
source: {
functionName: 0,
fileName: null,
lineNumber: null,
columnNumber: null,
},
}),
),
).toBe(false);
});
it("rejects non-finite numeric line/column numbers", () => {
expect(
isPickedElementPayload(
validPayload({
source: {
functionName: null,
fileName: null,
lineNumber: Number.POSITIVE_INFINITY,
columnNumber: null,
},
}),
),
).toBe(false);
expect(
isPickedElementPayload(
validPayload({
source: {
functionName: null,
fileName: null,
lineNumber: Number.NaN,
columnNumber: null,
},
}),
),
).toBe(false);
});
it("rejects malformed stack arrays", () => {
expect(isPickedElementPayload(validPayload({ stack: "not-an-array" }))).toBe(false);
expect(isPickedElementPayload(validPayload({ stack: [{ bogus: true }] }))).toBe(false);
});
});
function validAnnotation(overrides?: Record<string, unknown>): Record<string, unknown> {
return {
id: "annotation_1",
pageUrl: "https://example.com/",
pageTitle: "Example",
comment: "Make this clearer",
elements: [
{
id: "element_1",
element: validPayload(),
rect: { x: 10, y: 20, width: 100, height: 40 },
},
],
regions: [{ id: "region_1", rect: { x: 5, y: 6, width: 20, height: 30 } }],
strokes: [
{
id: "stroke_1",
color: "#7c3aed",
width: 4,
points: [
{ x: 10, y: 10 },
{ x: 20, y: 20 },
],
bounds: { x: 6, y: 6, width: 18, height: 18 },
},
],
styleChanges: [
{
targetId: "element_1",
selector: "button.submit",
property: "opacity",
previousValue: "1",
value: "0.5",
},
],
screenshot: null,
createdAt: "2026-06-11T00:00:00.000Z",
...overrides,
};
}
describe("isPreviewAnnotationPayload", () => {
it("accepts a structured annotation draft before screenshot capture", () => {
expect(isPreviewAnnotationPayload(validAnnotation())).toBe(true);
});
it("rejects screenshots supplied by the guest preload", () => {
expect(isPreviewAnnotationPayload(validAnnotation({ screenshot: { dataUrl: "bad" } }))).toBe(
false,
);
});
it("rejects malformed geometry and nested element payloads", () => {
expect(
isPreviewAnnotationPayload(
validAnnotation({ regions: [{ id: "region_1", rect: { x: 0, y: 0, width: "wide" } }] }),
),
).toBe(false);
expect(
isPreviewAnnotationPayload(
validAnnotation({ elements: [{ id: "element_1", element: {}, rect: {} }] }),
),
).toBe(false);
});
});
@@ -0,0 +1,146 @@
/**
* Strict structural validator for `PickedElementPayload` messages received
* from the in-page picker preload (`apps/desktop/src/preview/PickPreload.ts`)
* via `wc.ipc`. Lives in its own electron-free module so the validator is
* trivially unit-testable.
*
* Validation must be tight: downstream `normalizeElementContextSelection`
* calls `.trim()` on incoming strings, so a malformed payload (preload bug,
* future schema mismatch, malicious page that intercepts the preload's IPC
* channel via prototype pollution) would otherwise throw deep in the
* renderer and the chip silently never appears.
*/
import type { PickedElementPayload, PreviewAnnotationPayload } from "@t3tools/contracts";
function isStringOrNull(value: unknown): value is string | null {
return value === null || typeof value === "string";
}
function isFiniteNumberOrNull(value: unknown): value is number | null {
return value === null || (typeof value === "number" && Number.isFinite(value));
}
function isPickedStackFrame(value: unknown): boolean {
if (typeof value !== "object" || value === null) return false;
const frame = value as Record<string, unknown>;
return (
isStringOrNull(frame["functionName"]) &&
isStringOrNull(frame["fileName"]) &&
isFiniteNumberOrNull(frame["lineNumber"]) &&
isFiniteNumberOrNull(frame["columnNumber"])
);
}
export function isPickedElementPayload(value: unknown): value is PickedElementPayload {
if (typeof value !== "object" || value === null) return false;
const c = value as Record<string, unknown>;
if (typeof c["pageUrl"] !== "string") return false;
if (typeof c["tagName"] !== "string") return false;
if (typeof c["htmlPreview"] !== "string") return false;
if (typeof c["styles"] !== "string") return false;
if (typeof c["pickedAt"] !== "string") return false;
if (!isStringOrNull(c["pageTitle"])) return false;
if (!isStringOrNull(c["selector"])) return false;
if (!isStringOrNull(c["componentName"])) return false;
if (c["source"] !== null && !isPickedStackFrame(c["source"])) return false;
if (!Array.isArray(c["stack"])) return false;
if (!c["stack"].every(isPickedStackFrame)) return false;
return true;
}
function isRect(value: unknown): boolean {
if (typeof value !== "object" || value === null) return false;
const rect = value as Record<string, unknown>;
return ["x", "y", "width", "height"].every(
(key) => typeof rect[key] === "number" && Number.isFinite(rect[key]),
);
}
function isPoint(value: unknown): boolean {
if (typeof value !== "object" || value === null) return false;
const point = value as Record<string, unknown>;
return (
typeof point["x"] === "number" &&
Number.isFinite(point["x"]) &&
typeof point["y"] === "number" &&
Number.isFinite(point["y"])
);
}
export function isPreviewAnnotationPayload(value: unknown): value is PreviewAnnotationPayload {
if (typeof value !== "object" || value === null) return false;
const annotation = value as Record<string, unknown>;
if (typeof annotation["id"] !== "string") return false;
if (typeof annotation["pageUrl"] !== "string") return false;
if (!isStringOrNull(annotation["pageTitle"])) return false;
if (typeof annotation["comment"] !== "string") return false;
if (typeof annotation["createdAt"] !== "string") return false;
if (annotation["screenshot"] !== null) return false;
const elements = annotation["elements"];
if (!Array.isArray(elements)) return false;
if (
!elements.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return (
typeof target["id"] === "string" &&
isPickedElementPayload(target["element"]) &&
isRect(target["rect"])
);
})
) {
return false;
}
const regions = annotation["regions"];
if (!Array.isArray(regions)) return false;
if (
!regions.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return typeof target["id"] === "string" && isRect(target["rect"]);
})
) {
return false;
}
const strokes = annotation["strokes"];
if (!Array.isArray(strokes)) return false;
if (
!strokes.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const target = entry as Record<string, unknown>;
return (
typeof target["id"] === "string" &&
typeof target["color"] === "string" &&
typeof target["width"] === "number" &&
Number.isFinite(target["width"]) &&
Array.isArray(target["points"]) &&
target["points"].every(isPoint) &&
isRect(target["bounds"])
);
})
) {
return false;
}
const styleChanges = annotation["styleChanges"];
if (!Array.isArray(styleChanges)) return false;
if (
!styleChanges.every((entry) => {
if (typeof entry !== "object" || entry === null) return false;
const change = entry as Record<string, unknown>;
return (
typeof change["targetId"] === "string" &&
isStringOrNull(change["selector"]) &&
typeof change["property"] === "string" &&
typeof change["previousValue"] === "string" &&
typeof change["value"] === "string"
);
})
) {
return false;
}
return true;
}
@@ -0,0 +1,26 @@
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { describe, expect } from "vite-plus/test";
import {
playwrightInjectedRuntimeInstallExpression,
playwrightInjectedRuntimeSource,
} from "./PlaywrightInjectedRuntime.ts";
describe("playwright injected runtime", () => {
effectIt.effect("extracts the pinned runtime from playwright-core", () =>
Effect.gen(function* () {
const source = yield* playwrightInjectedRuntimeSource();
expect(source.length).toBeGreaterThan(100_000);
expect(source).toContain("InjectedScript");
}),
);
effectIt.effect("builds an idempotent install expression", () =>
Effect.gen(function* () {
const expression = yield* playwrightInjectedRuntimeInstallExpression();
expect(expression).toContain("__t3PlaywrightInjected");
expect(expression).toContain('testIdAttributeName":"data-testid');
}),
);
});
@@ -0,0 +1,90 @@
// @effect-diagnostics nodeBuiltinImport:off - Extracts Playwright's installed Node bundle for browser injection.
import { readFile } from "node:fs/promises";
import { createRequire } from "node:module";
import { dirname, join } from "node:path";
import { runInNewContext } from "node:vm";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
export class PlaywrightInjectedRuntimeError extends Data.TaggedError(
"PlaywrightInjectedRuntimeError",
)<{
readonly operation: string;
readonly cause: unknown;
}> {
override get message() {
return `Playwright injected runtime operation failed: ${this.operation}`;
}
}
const fail = (operation: string, cause: unknown) =>
new PlaywrightInjectedRuntimeError({ operation, cause });
export const playwrightInjectedRuntimeSource = Effect.fn("PlaywrightInjectedRuntime.source")(
function* () {
const packageJsonPath = yield* Effect.try({
try: () => require.resolve("playwright-core/package.json"),
catch: (cause) => fail("resolvePackage", cause),
});
const coreBundle = yield* Effect.tryPromise({
try: () => readFile(join(dirname(packageJsonPath), "lib/coreBundle.js"), "utf8"),
catch: (cause) => fail("readCoreBundle", cause),
});
const marker = "source3 = ";
const start = coreBundle.indexOf(marker);
if (start < 0) {
return yield* fail(
"findSourceMarker",
new Error("Playwright injected runtime marker was not found."),
);
}
const literalStart = start + marker.length;
const literalEnd = coreBundle.indexOf(";\n }\n});", literalStart);
if (literalEnd < 0) {
return yield* fail(
"findSourceTerminator",
new Error("Playwright injected runtime terminator was not found."),
);
}
const literal = coreBundle.slice(literalStart, literalEnd);
const source = yield* Effect.try({
try: () => runInNewContext(literal, Object.create(null), { timeout: 1_000 }),
catch: (cause) => fail("evaluateSourceLiteral", cause),
});
if (typeof source !== "string" || source.length < 100_000) {
return yield* fail(
"validateSource",
new Error("Playwright injected runtime extraction returned invalid source."),
);
}
return source;
},
);
export const playwrightInjectedRuntimeInstallExpression = Effect.fn(
"PlaywrightInjectedRuntime.installExpression",
)(function* () {
const source = yield* playwrightInjectedRuntimeSource();
const options = yield* encodeUnknownJson({
isUnderTest: false,
sdkLanguage: "javascript",
testIdAttributeName: "data-testid",
stableRafCount: 1,
browserName: "chromium",
shouldPrependErrorPrefix: false,
isUtilityWorld: false,
customEngines: [],
}).pipe(Effect.mapError((cause) => fail("encodeOptions", cause)));
return `(() => {
if (globalThis.__t3PlaywrightInjected) return true;
const module = { exports: {} };
${source}
globalThis.__t3PlaywrightInjected = new (module.exports.InjectedScript())(globalThis, ${options});
return true;
})()`;
});
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vite-plus/test";
import { PREVIEW_WEBVIEW_PREFERENCES } from "./WebviewPreferences.ts";
/**
* Mirrors Electron's webview attribute parser closely enough to catch the
* regressions we've already hit:
*
* - whitespace inside the comma-separated list silently drops keys (so
* `" sandbox=true"` becomes an unknown key and Electron falls back to
* defaults — re-opening the Node-leak window we closed),
* - non-`true`/`false` values (`"yes"`, `"no"`, etc.) are kept as truthy
* strings and assigned to a boolean preference, which silently flips
* `contextIsolation=no` to ENABLED (then react-grab can't see the React
* DevTools hook and componentName resolution always returns null).
*
* The actual Electron parser does roughly:
*
* for (const pair of webpreferences.split(',')) {
* const [key, value] = pair.split('=');
* prefs[key] = value; // value left as a string
* }
*
* then later coerces booleans via `Boolean(value)`. Replicating that here
* keeps the test independent of Electron internals while still failing if
* we accidentally ship `"contextIsolation=no"` again.
*/
function parseWebPreferences(input: string): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const pair of input.split(",")) {
if (pair !== pair.trim()) {
// Electron's parser doesn't trim; surface the bug as undefined-key.
out[pair] = pair.split("=")[1];
continue;
}
const [key, value] = pair.split("=");
if (!key) continue;
out[key] = value;
}
return out;
}
describe("PREVIEW_WEBVIEW_PREFERENCES", () => {
const parsed = parseWebPreferences(PREVIEW_WEBVIEW_PREFERENCES);
it("contains exactly the three security-critical keys", () => {
expect(Object.keys(parsed).toSorted()).toEqual(
["contextIsolation", "nodeIntegration", "sandbox"].toSorted(),
);
});
it("uses canonical JS-boolean string literals (not yes/no, on/off, 1/0)", () => {
// `value="no"` is a TRUTHY string when assigned to webPreferences.X — so
// `contextIsolation="no"` would silently leave isolation ENABLED. Lock
// the values to `"true"` / `"false"` so the parser does the right thing.
for (const value of Object.values(parsed)) {
expect(value).toMatch(/^(true|false)$/);
}
});
it("disables context isolation (so react-grab can see the page's React DevTools hook)", () => {
expect(parsed["contextIsolation"]).toBe("false");
});
it("keeps the renderer sandbox enabled (so the page cannot reach Node APIs)", () => {
expect(parsed["sandbox"]).toBe("true");
});
it("disables nodeIntegration (defense in depth — page never gets Node)", () => {
expect(parsed["nodeIntegration"]).toBe("false");
});
it("contains no whitespace (Electron's parser does not trim)", () => {
// Electron splits on `,` without trimming, so any whitespace would turn
// a key into an unknown one and silently drop the security flag.
expect(PREVIEW_WEBVIEW_PREFERENCES).not.toMatch(/\s/);
});
});
@@ -0,0 +1,42 @@
/**
* webPreferences override applied to every preview `<webview>` element via
* its `webpreferences="..."` attribute. Single source of truth so all guest
* surfaces inherit the same security posture.
*
* Lives in its own electron-free module so the value is unit-testable
* without importing `Manager.ts` (which transitively imports
* `electron` and blows up under vitest).
*
* - `contextIsolation=false`: the picker preload needs to share `globalThis`
* with the page so react-grab/bippy can read the React DevTools hook
* (`__REACT_DEVTOOLS_GLOBAL_HOOK__`) and resolve component names. Without
* this every pick comes back with `componentName: null` even on dev React
* apps.
* - `sandbox=true`: keeps the OS-level renderer sandbox enabled. Critical
* when paired with `contextIsolation=false` — without sandbox, the preload
* has full Node access (`require`, `fs`, `child_process`, ...) and that
* `require` would land on the page's shared `globalThis`, giving any
* third-party page in the preview full Node + IPC access to the host.
* In sandboxed mode Electron still synthesizes the `electron` module for
* the preload's `import { ipcRenderer }` line, but no Node globals leak.
* - `nodeIntegration=false`: pinned for clarity (the page itself never gets
* Node access).
*
* Format notes (locked down by `WebviewPreferences.test.ts`):
* - Whitespace-free. Electron's webpreferences parser splits on `,` and
* does not trim, so a leading space would turn a key into an unknown one
* and silently drop it.
* - Values are JS-boolean strings (`true`/`false`) — `yes`/`no` are not
* special-cased by the parser; `value="no"` becomes the truthy STRING
* `"no"` when assigned to a boolean webPreferences key. Most critically,
* `contextIsolation="no"` is truthy → contextIsolation stays ENABLED →
* react-grab can't see the React DevTools hook.
*
* Defense in depth: `apps/desktop/src/main.ts` also runs a
* `will-attach-webview` handler that force-sets `sandbox: true` and
* `nodeIntegration*: false` on the actual webPreferences object, gated on
* the preview partition, so even if this string is ever wrong, the
* security-critical flags can't regress on preview tabs.
*/
export const PREVIEW_WEBVIEW_PREFERENCES =
"contextIsolation=false,sandbox=true,nodeIntegration=false";
+19 -1
View File
@@ -8,6 +8,17 @@ import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
vi.mock("electron", async (importOriginal) => ({
...(await importOriginal<typeof import("electron")>()),
session: {
fromPartition: vi.fn(() => ({
getUserAgent: vi.fn(() => "Mozilla/5.0 Electron/41.5.0 t3code/1.2.3"),
setPermissionRequestHandler: vi.fn(),
setUserAgent: vi.fn(),
})),
},
}));
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
@@ -18,6 +29,7 @@ import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopWindow from "./DesktopWindow.ts";
import * as PreviewManager from "../preview/Manager.ts";
const environmentInput = {
dirname: "/repo/apps/desktop/dist-electron",
@@ -155,6 +167,12 @@ function makeTestLayer(input: {
} satisfies ElectronShell.ElectronShellShape),
electronThemeLayer,
electronWindowLayer,
Layer.mock(PreviewManager.PreviewManager)({
getBrowserSession: () => Effect.succeed({} as Electron.Session),
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
}),
),
),
);
@@ -165,7 +183,7 @@ describe("DesktopWindow", () => {
assert.isTrue(
DesktopWindow.isSameOriginRendererNavigation({
applicationUrl: "http://127.0.0.1:3773/",
navigationUrl: "http://127.0.0.1:3773/settings/cloud",
navigationUrl: "http://127.0.0.1:3773/settings/connections",
}),
);
assert.isFalse(
+23 -2
View File
@@ -11,6 +11,7 @@ import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -36,7 +37,8 @@ type DesktopWindowRuntimeServices =
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
| ElectronWindow.ElectronWindow;
| ElectronWindow.ElectronWindow
| PreviewManager.PreviewManager;
export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
"DesktopWindowDevServerUrlMissingError",
@@ -48,7 +50,8 @@ export class DesktopWindowDevServerUrlMissingError extends Data.TaggedError(
export type DesktopWindowError =
| DesktopWindowDevServerUrlMissingError
| ElectronWindow.ElectronWindowCreateError;
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export interface DesktopWindowShape {
readonly createMain: Effect.Effect<Electron.BrowserWindow, DesktopWindowError>;
@@ -162,6 +165,7 @@ const make = Effect.gen(function* () {
const electronShell = yield* ElectronShell.ElectronShell;
const electronTheme = yield* ElectronTheme.ElectronTheme;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
@@ -170,6 +174,7 @@ const make = Effect.gen(function* () {
const createWindow = Effect.fn("desktop.window.createWindow")(function* (
backendHttpUrl: URL,
): Effect.fn.Return<Electron.BrowserWindow, DesktopWindowError> {
yield* previewManager.getBrowserSession();
const applicationUrl = environment.isDevelopment
? yield* resolveDesktopDevServerUrl(environment)
: backendHttpUrl.href;
@@ -192,9 +197,25 @@ const make = Effect.gen(function* () {
contextIsolation: true,
nodeIntegration: false,
sandbox: true,
webviewTag: true,
},
});
yield* previewManager.setMainWindow(window);
window.webContents.on("will-attach-webview", (event, webPreferences, params) => {
if (
typeof params.partition !== "string" ||
!previewManager.isBrowserPartition(params.partition)
) {
event.preventDefault();
return;
}
webPreferences.sandbox = true;
webPreferences.nodeIntegration = false;
webPreferences.nodeIntegrationInSubFrames = false;
webPreferences.contextIsolation = false;
});
window.webContents.on("context-menu", (event, params) => {
event.preventDefault();
+14 -3
View File
@@ -14,17 +14,18 @@ export default defineConfig({
run: {
tasks: {
build: {
command: "vp pack",
command: "node scripts/build-preview-annotation-css.mjs && vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
command:
"node scripts/build-preview-annotation-css.mjs && cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "vp pack --watch",
command: "node scripts/build-preview-annotation-css.mjs && vp pack --watch",
cache: false,
},
"dev:electron": {
@@ -56,5 +57,15 @@ export default defineConfig({
define: publicConfigDefine,
entry: ["src/preload.ts"],
},
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/preview-pick-preload.ts"],
deps: {
alwaysBundle: (id) => id === "react-grab" || id.startsWith("react-grab/"),
},
},
],
});
@@ -1,53 +0,0 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+1 -1
View File
@@ -47,7 +47,7 @@ import { RELEASES_URL } from "../lib/releases";
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.36.333.292.2Line truncated
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
+4 -4
View File
@@ -1,6 +1,5 @@
---
import Layout from "../layouts/Layout.astro";
import TuxIcon from "../components/TuxIcon.astro";
import { tweets } from "../lib/tweets";
const desktopEndorsementRows = [
@@ -53,7 +52,7 @@ const mobileEndorsementRows = [
>
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="hero-linux-" />
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="download-label">Download for macOS</span>
</a>
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer" class="btn btn-ghost btn-lg">
@@ -360,7 +359,8 @@ const mobileEndorsementRows = [
<a id="cta-download-btn" class="btn btn-primary btn-lg" href="https://github.com/pingdotgg/t3code/releases">
<svg class="dl-icon dl-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="dl-icon dl-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<TuxIcon class="dl-icon dl-icon--linux" idPrefix="cta-linux-" />
<svg class="dl-icon dl-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M12.504 0c-.155 0-.315.008-.48.021-4.226.333-3.105 4.807-3.17 6.298-.076 1.092-.3 1.953-1.05 3.02-.885 1.051-2.127 2.75-2.716 4.521-.278.832-.41 1.684-.287 2.489a.424.424 0 00-.11.135c-.26.268-.45.6-.663.839-.199.199-.485.267-.797.4-.313.136-.658.269-.864.68-.09.189-.136.394-.132.602 0 .199.027.4.055.536.058.399.116.728.04.97-.249.68-.28 1.145-.106 1.484.174.334.535.47.94.601.81.2 1.91.135 2.774.6.926.466 1.866.67 2.616.47.526-.116.97-.464 1.208-.946.587-.003 1.23-.269 2.26-.334.699-.058 1.574.267 2.577.2.025.134.063.198.114.333l.003.003c.391.778 1.113 1.132 1.884 1.071.771-.06 1.592-.536 2.257-1.306.631-.765 1.683-1.084 2.378-1.503.348-.199.629-.469.649-.853.023-.4-.2-.811-.714-1.376v-.097l-.003-.003c-.17-.2-.25-.535-.338-.926-.085-.401-.182-.786-.492-1.046h-.003c-.059-.054-.123-.067-.188-.135a.357.357 0 00-.19-.064c.431-1.278.264-2.55-.173-3.694-.533-1.41-1.465-2.638-2.175-3.483-.796-1.005-1.576-1.957-1.56-3.368.026-2.152.236-6.133-3.544-6.139zm.529 3.405h.013c.213 0 .396.062.584.198.19.135.33.332.438.533.105.259.158.459.166.724 0-.02.006-.04.006-.06v.105a.086.086 0 01-.004-.021l-.004-.024a1.807 1.807 0 01-.15.706.953.953 0 01-.213.335.71.71 0 00-.088-.042c-.104-.045-.198-.064-.284-.133a1.312 1.312 0 00-.22-.066c.05-.06.146-.133.183-.198.053-.128.082-.264.088-.402v-.02a1.21 1.21 0 00-.061-.4c-.045-.134-.101-.2-.183-.333-.084-.066-.167-.132-.267-.132h-.016c-.093 0-.176.03-.262.132a.8.8 0 00-.205.334 1.18 1.18 0 00-.09.4v.019c.002.089.008.179.02.267-.193-.067-.438-.135-.607-.202a1.635 1.635 0 01-.018-.2v-.02a1.772 1.772 0 01.15-.768c.082-.22.232-.406.43-.533a.985.985 0 01.594-.2zm-2.962.059h.036c.142 0 .27.048.399.135.146.129.264.288.344.465.09.199.14.4.153.667v.004c.007.134.006.2-.002.266v.08c-.03.007-.056.018-.083.024-.152.055-.274.135-.393.2.012-.09.013-.18.003-.267v-.015c-.012-.133-.04-.2-.082-.333a.613.613 0 00-.166-.267.248.248 0 00-.183-.064h-.021c-.071.006-.13.04-.186.132a.552.552 0 00-.12.27.944.944 0 00-.023.33v.015c.012.135.037.2.08.334.046.134.098.2.166.268.01.009.02.018.034.024-.07.057-.117.07-.176.136a.304.304 0 01-.131.068 2.62 2.62 0 01-.275-.402 1.772 1.772 0 01-.155-.667 1.759 1.759 0 01.08-.668 1.43 1.43 0 01.283-.535c.128-.133.26-.2.418-.2zm1.37 1.706c.332 0 .733.065 1.216.399.293.2.523.269 1.052.468h.003c.255.136.405.266.478.399v-.131a.571.571 0 01.016.47c-.123.31-.516.643-1.063.842v.002c-.268.135-.501.333-.775.465-.276.135-.588.292-1.012.267a1.139 1.139 0 01-.448-.067 3.566 3.566 0 01-.322-.198c-.195-.135-.363-.332-.612-.465v-.005h-.005c-.4-.246-.616-.512-.686-.71-.07-.268-.005-.47.193-.6.224-.135.38-.271.483-.336.104-.074.143-.102.176-.131h.002v-.003c.169-.202.436-.47.839-.601.139-.036.294-.065.466-.065zm2.8 2.142c.358 1.417 1.196 3.475 1.735 4.473.286.534.855 1.659 1.102 3.024.156-.005.33.018.513.064.646-1.671-.546-3.467-1.089-3.966-.22-.2-.232-.335-.123-.335.59.534 1.365 1.572 1.646 2.757.13.535.16 1.104.021 1.67.067.028.135.06.205.067 1.032.534 1.413.938 1.23 1.537v-.043c-.06-.003-.12 0-.18 0h-.016c.151-.467-.182-.825-1.065-1.224-.915-.4-1.646-.336-1.77.465-.008.043-.013.066-.018.135-.068.023-.139.053-.209.064-.43.268-.662.669-.793 1.187-.13.533-.17 1.156-.205 1.869v.003c-.02.334-.17.838-.319 1.35-1.5 1.072-3.58 1.538-5.348.334a2.645 2.645 0 00-.402-.533 1.45 1.45 0 00-.275-.333c.182 0 .338-.03.465-.067a.615.615 0 00.314-.334c.108-.267 0-.697-.345-1.163-.345-.467-.931-.995-1.788-1.521-.63-.4-.986-.87-1.15-1.396-.165-.534-.143-1.085-.015-1.645.245-1.07.873-2.11 1.274-2.763.107-.065.037.135-.408.974-.396.751-1.14 2.497-.122 3.854a8.123 8.123 0 01.647-2.876c.564-1.278 1.743-3.504 1.836-5.268.048.036.217.135.289.202.218.133.38.333.59.465.21.201.477.335.876.335.039.003.075.006.11.006.412 0 .73-.134.997-.268.29-.134.52-.334.74-.4h.005c.467-.135.835-.402 1.044-.7zm2.185 8.958c.037.6.343 1.245.882 1.377.588.134 1.434-.333 1.791-.765l.211-.01c.315-.007.577.01.847.268l.003.003c.208.199.305.53.391.876.085.4.154.78.409 1.066.486.527.645.906.636 1.14l.003-.007v.018l-.003-.012c-.015.262-.185.396-.498.595-.63.401-1.746.712-2.457 1.57-.618.737-1.37 1.14-2.036 1.191-.664.053-1.237-.2-1.574-.898l-.005-.003c-.21-.4-.12-1.025.056-1.69.176-.668.428-1.344.463-1.897.037-.714.076-1.335.195-1.814.12-.465.308-.797.641-.984l.045-.022zm-10.814.049h.01c.053 0 .105.005.157.014.376.055.706.333 1.023.752l.91 1.664.003.003c.243.533.754 1.064 1.189 1.637.434.598.77 1.131.729 1.57v.006c-.057.744-.48 1.148-1.125 1.294-.645.135-1.52.002-2.395-.464-.968-.536-2.118-.469-2.857-.602-.369-.066-.61-.2-.723-.4-.11-.2-.113-.602.123-1.23v-.004l.002-.003c.117-.334.03-.752-.027-1.118-.055-.401-.083-.71.043-.94.16-.334.396-.4.69-.533.294-.135.64-.202.915-.47h.002v-.002c.256-.268.445-.601.668-.838.19-.201.38-.336.663-.336zm7.159-9.074c-.435.201-.945.535-1.488.535-.542 0-.97-.267-1.28-.466-.154-.134-.28-.268-.373-.335-.164-.134-.144-.333-.074-.333.109.016.129.134.199.2.096.066.215.2.3Line truncated
<span id="cta-download-label">Download for macOS</span>
</a>
<a class="btn btn-ghost btn-lg" href="/download">Windows · Linux · other</a>
@@ -548,7 +548,7 @@ const mobileEndorsementRows = [
:global([data-platform="mac"]) .dl-icon--apple { display: block; }
:global([data-platform="win"]) .dl-icon--windows { display: block; }
:global([data-platform="linux"]) .dl-icon--linux { display: block; }
:global(:not([data-platform])) .dl-icon--apple { display: block; }
:global(html:not([data-platform])) .dl-icon--apple { display: block; }
/* Floating harness marks */
.hero-float {
+1 -1
View File
@@ -16,7 +16,7 @@ This app has three variants:
Run commands from `apps/mobile`.
T3 Cloud is optional and disabled in a fresh clone. Public configuration belongs in the
T3 Connect is optional and disabled in a fresh clone. Public configuration belongs in the
repository-root `.env` or `.env.local`, not an `apps/mobile/.env` file. See
[`../../.env.example`](../../.env.example).
+5
View File
@@ -161,6 +161,11 @@ const config: ExpoConfig = {
publishableKey: repoEnv.EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY ?? null,
jwtTemplate: repoEnv.EXPO_PUBLIC_CLERK_JWT_TEMPLATE ?? null,
},
observability: {
tracesUrl: repoEnv.EXPO_PUBLIC_OTLP_TRACES_URL ?? "https://api.axiom.co/v1/traces",
tracesDataset: repoEnv.EXPO_PUBLIC_OTLP_TRACES_DATASET ?? null,
tracesToken: repoEnv.EXPO_PUBLIC_OTLP_TRACES_TOKEN ?? null,
},
eas: {
projectId: "d763fcb8-d37c-41ea-a773-b54a0ab4a454",
},
+2 -7
View File
@@ -1,4 +1,4 @@
import { useAuth, useUser, useUserProfileModal } from "@clerk/expo";
import { useAuth, useUser } from "@clerk/expo";
import * as Notifications from "expo-notifications";
import { Link, Stack, useRouter } from "expo-router";
import { SymbolView } from "expo-symbols";
@@ -68,7 +68,6 @@ function ConfiguredSettingsRouteScreen() {
const { push } = useRouter();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
const { savedConnectionsById } = useRemoteEnvironmentState();
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
@@ -266,15 +265,11 @@ function ConfiguredSettingsRouteScreen() {
push("/settings/waitlist");
return;
}
if (isUserProfileModalAvailable) {
void presentUserProfile();
return;
}
Alert.alert(
"T3 Cloud unavailable",
"Native T3 Cloud account management is not available in this build.",
);
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]);
}, [isLoaded, isSignedIn, push]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -41,7 +41,7 @@ export function normalizeAgentAwarenessRelayBaseUrl(
}
function readRelayConfig(): { readonly url: string } | null {
const relayUrl = resolveCloudPublicConfig().relayUrl;
const relayUrl = resolveCloudPublicConfig().relay.url;
if (!relayUrl) {
logRegistrationDebug("relay registration skipped; relay config missing");
return null;
@@ -66,7 +66,9 @@ function CloudAuthBridge(props: { readonly children: ReactNode }) {
}
export function CloudAuthProvider(props: { readonly children: ReactNode }) {
const { clerkPublishableKey: publishableKey, relayUrl } = resolveCloudPublicConfig();
const config = resolveCloudPublicConfig();
const publishableKey = config.clerk.publishableKey;
const relayUrl = config.relay.url;
useEffect(() => {
if (!publishableKey || !relayUrl) {
@@ -572,7 +572,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(Response.json(validLinkResponse("env-other")));
@@ -631,7 +631,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -669,7 +669,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
return Promise.resolve(
@@ -713,7 +713,7 @@ describe("mobile cloud link environment client", () => {
if (String(url).endsWith("/v1/client/environment-link-challenges")) {
return Promise.resolve(Response.json(validLinkChallengeResponse()));
}
if (String(url).endsWith("/api/cloud/link-proof")) {
if (String(url).endsWith("/api/connect/link-proof")) {
return Promise.resolve(Response.json(validLinkProof()));
}
if (String(url).endsWith("/v1/client/environment-links")) {
@@ -50,7 +50,7 @@ export function normalizeRelayBaseUrl(value: string | null | undefined): string
}
function readRelayUrl(): string | null {
return resolveCloudPublicConfig().relayUrl;
return resolveCloudPublicConfig().relay.url;
}
export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
@@ -301,7 +301,7 @@ export function linkEnvironmentToCloud(input: {
),
);
const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
const proof = yield* environmentClient.cloud
const proof = yield* environmentClient.connect
.linkProof({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -336,7 +336,7 @@ export function linkEnvironmentToCloud(input: {
link,
});
yield* environmentClient.cloud
yield* environmentClient.connect
.relayConfig({
headers: { authorization: `Bearer ${localBearerToken}` },
payload: {
@@ -1,7 +1,6 @@
import { useAtomValue } from "@effect/atom-react";
import {
createManagedRelayQueryManager,
ManagedRelayClient,
managedRelaySessionAtom,
readManagedRelaySnapshotState,
} from "@t3tools/client-runtime";
@@ -9,23 +8,13 @@ import type {
RelayClientEnvironmentRecord,
RelayEnvironmentStatusResponse,
} from "@t3tools/contracts/relay";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback } from "react";
import { mobileRuntime } from "../../lib/runtime";
import { mobileRuntimeContextLayer } from "../../lib/runtime";
import { appAtomRegistry } from "../../state/atom-registry";
const managedRelayAtomRuntime = Atom.runtime(
Layer.effect(
ManagedRelayClient,
mobileRuntime.contextEffect.pipe(
Effect.map((context) => Context.get(context, ManagedRelayClient)),
),
),
);
const managedRelayAtomRuntime = Atom.runtime(mobileRuntimeContextLayer);
export const managedRelayQueryManager = createManagedRelayQueryManager(managedRelayAtomRuntime);
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { resolveCloudPublicConfig } from "./publicConfig";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "./publicConfig";
vi.mock("expo-constants", () => ({
default: {
@@ -13,9 +13,18 @@ vi.mock("expo-constants", () => ({
describe("resolveCloudPublicConfig", () => {
it("returns no cloud configuration for an unconfigured build", () => {
expect(resolveCloudPublicConfig({})).toEqual({
clerkPublishableKey: null,
clerkJwtTemplate: null,
relayUrl: null,
clerk: {
publishableKey: null,
jwtTemplate: null,
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
});
});
@@ -24,11 +33,25 @@ describe("resolveCloudPublicConfig", () => {
resolveCloudPublicConfig({
clerk: { publishableKey: " pk_test_example ", jwtTemplate: " t3-relay " },
relay: { url: " https://relay.example.test/// " },
observability: {
tracesUrl: " https://api.axiom.co/v1/traces ",
tracesDataset: " mobile-traces ",
tracesToken: " public-ingest-token ",
},
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: "https://relay.example.test",
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: "https://relay.example.test",
},
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
});
});
@@ -39,9 +62,59 @@ describe("resolveCloudPublicConfig", () => {
relay: { url: "http://relay.example.test" },
}),
).toEqual({
clerkPublishableKey: "pk_test_example",
clerkJwtTemplate: "t3-relay",
relayUrl: null,
clerk: {
publishableKey: "pk_test_example",
jwtTemplate: "t3-relay",
},
relay: {
url: null,
},
observability: {
tracesUrl: null,
tracesDataset: null,
tracesToken: null,
},
});
});
it("rejects an insecure traces URL", () => {
expect(
resolveCloudPublicConfig({
observability: {
tracesUrl: "http://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}).observability,
).toEqual({
tracesUrl: null,
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
});
});
it("keeps tracing disabled unless every public tracing value is configured", () => {
expect(hasMobileTracingPublicConfig(resolveCloudPublicConfig({}))).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
},
}),
),
).toBe(false);
expect(
hasMobileTracingPublicConfig(
resolveCloudPublicConfig({
observability: {
tracesUrl: "https://api.axiom.co/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
}),
),
).toBe(true);
});
});
+69 -17
View File
@@ -2,40 +2,92 @@ import Constants from "expo-constants";
import { relayClerkTokenOptions } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
type ExpoExtra = Readonly<Record<string, unknown>> | undefined;
export interface CloudPublicConfig {
readonly clerkPublishableKey: string | null;
readonly clerkJwtTemplate: string | null;
readonly relayUrl: string | null;
readonly clerk: {
readonly publishableKey: string | null;
readonly jwtTemplate: string | null;
};
readonly relay: {
readonly url: string | null;
};
readonly observability: {
readonly tracesUrl: string | null;
readonly tracesDataset: string | null;
readonly tracesToken: string | null;
};
}
type UntrustedSection<T> = {
readonly [Key in keyof T]?: unknown;
};
type ExpoExtra =
| {
readonly [Section in keyof CloudPublicConfig]?: UntrustedSection<CloudPublicConfig[Section]>;
}
| undefined;
function trimNonEmpty(value: unknown): string | null {
return typeof value === "string" && value.trim() ? value.trim() : null;
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
const clerk = extra?.clerk as
| { readonly publishableKey?: unknown; readonly jwtTemplate?: unknown }
| undefined;
const relay = extra?.relay as { readonly url?: unknown } | undefined;
function normalizeSecureUrl(value: unknown): string | null {
const raw = trimNonEmpty(value);
if (raw === null) {
return null;
}
try {
const url = new URL(raw);
return url.protocol === "https:" ? url.toString() : null;
} catch {
return null;
}
}
export function resolveCloudPublicConfig(extra: ExpoExtra = Constants.expoConfig?.extra) {
return {
clerkPublishableKey: trimNonEmpty(clerk?.publishableKey),
clerkJwtTemplate: trimNonEmpty(clerk?.jwtTemplate),
relayUrl: normalizeSecureRelayUrl(trimNonEmpty(relay?.url) ?? ""),
clerk: {
publishableKey: trimNonEmpty(extra?.clerk?.publishableKey),
jwtTemplate: trimNonEmpty(extra?.clerk?.jwtTemplate),
},
relay: {
url: normalizeSecureRelayUrl(trimNonEmpty(extra?.relay?.url) ?? ""),
},
observability: {
tracesUrl: normalizeSecureUrl(extra?.observability?.tracesUrl),
tracesDataset: trimNonEmpty(extra?.observability?.tracesDataset),
tracesToken: trimNonEmpty(extra?.observability?.tracesToken),
},
} satisfies CloudPublicConfig;
}
export function hasCloudPublicConfig(): boolean {
const config = resolveCloudPublicConfig();
return Boolean(config.clerkPublishableKey && config.clerkJwtTemplate && config.relayUrl);
return Boolean(config.clerk.publishableKey && config.clerk.jwtTemplate && config.relay.url);
}
type Configured<T> = {
readonly [Key in keyof T]: NonNullable<T[Key]>;
};
type MobileTracingPublicConfig = Omit<CloudPublicConfig, "observability"> & {
readonly observability: Configured<CloudPublicConfig["observability"]>;
};
export function hasMobileTracingPublicConfig(
config: CloudPublicConfig = resolveCloudPublicConfig(),
): config is MobileTracingPublicConfig {
return Boolean(
config.observability.tracesUrl &&
config.observability.tracesDataset &&
config.observability.tracesToken,
);
}
export function resolveRelayClerkTokenOptions() {
const { clerkJwtTemplate } = resolveCloudPublicConfig();
if (!clerkJwtTemplate) {
const { jwtTemplate } = resolveCloudPublicConfig().clerk;
if (!jwtTemplate) {
throw new Error("T3CODE_CLERK_JWT_TEMPLATE is not configured.");
}
return relayClerkTokenOptions(clerkJwtTemplate);
return relayClerkTokenOptions(jwtTemplate);
}
@@ -0,0 +1,52 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { makeMobileTracingLayer } from "./mobileTracing";
vi.mock("expo-constants", () => ({
default: {
expoConfig: {
extra: {},
},
},
}));
it.effect("exports spans through the scoped mobile OTLP layer", () => {
const fetchFn = vi.fn<typeof fetch>(async () => new Response(null, { status: 202 }));
const tracingLayer = makeMobileTracingLayer(
{
tracesUrl: "https://api.axiom.test/v1/traces",
tracesDataset: "mobile-traces",
tracesToken: "public-ingest-token",
},
{
appVariant: "test",
serviceVersion: "1.2.3",
},
).pipe(Layer.provide(remoteHttpClientLayer(fetchFn)));
const tracedApplication = Layer.effectDiscard(
Effect.void.pipe(Effect.withSpan("mobile.test.span")),
).pipe(Layer.provide(tracingLayer));
return Effect.gen(function* () {
yield* Layer.build(tracedApplication);
expect(fetchFn).not.toHaveBeenCalled();
}).pipe(
Effect.scoped,
Effect.andThen(
Effect.sync(() => {
expect(fetchFn).toHaveBeenCalledOnce();
const [url, init] = fetchFn.mock.calls[0]!;
expect(String(url)).toBe("https://api.axiom.test/v1/traces");
expect(new Headers(init?.headers).get("authorization")).toBe("Bearer public-ingest-token");
expect(new Headers(init?.headers).get("x-axiom-dataset")).toBe("mobile-traces");
expect(new TextDecoder().decode(init?.body as Uint8Array)).toContain("mobile.test.span");
}),
),
);
});
@@ -0,0 +1,60 @@
import Constants from "expo-constants";
import * as Layer from "effect/Layer";
import type { HttpClient } from "effect/unstable/http";
import { OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { hasMobileTracingPublicConfig, resolveCloudPublicConfig } from "../cloud/publicConfig";
export interface MobileTracingConfig {
readonly tracesUrl: string;
readonly tracesDataset: string;
readonly tracesToken: string;
}
export interface MobileTracingResource {
readonly serviceVersion?: string;
readonly appVariant: string;
}
export function resolveMobileTracingConfig(): MobileTracingConfig | null {
const config = resolveCloudPublicConfig();
if (!hasMobileTracingPublicConfig(config)) {
return null;
}
const { tracesUrl, tracesDataset, tracesToken } = config.observability;
return { tracesUrl, tracesDataset, tracesToken };
}
export function makeMobileTracingLayer(
config: MobileTracingConfig | null,
resource: MobileTracingResource,
): Layer.Layer<never, never, HttpClient.HttpClient> {
if (config === null) {
return Layer.empty;
}
return OtlpTracer.layer({
url: config.tracesUrl,
headers: {
Authorization: `Bearer ${config.tracesToken}`,
"X-Axiom-Dataset": config.tracesDataset,
},
resource: {
serviceName: "t3-mobile",
serviceVersion: resource.serviceVersion,
attributes: {
"service.runtime": "react-native",
"service.component": "mobile",
"deployment.environment.name": resource.appVariant,
},
},
}).pipe(Layer.provide(OtlpSerialization.layerJson));
}
export const mobileTracingLayer = makeMobileTracingLayer(resolveMobileTracingConfig(), {
serviceVersion: Constants.expoConfig?.version,
appVariant:
typeof Constants.expoConfig?.extra?.appVariant === "string"
? Constants.expoConfig.extra.appVariant
: "unknown",
});
@@ -10,7 +10,7 @@ import type {
import {
detectComposerTrigger,
replaceTextRange,
serializeComposerMentionPath,
serializeComposerFileLink,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import { TextInputWrapper } from "expo-paste-input";
@@ -419,7 +419,7 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
let replacement = "";
if (item.type === "path") {
replacement = `@${serializeComposerMentionPath(item.path)} `;
replacement = `${serializeComposerFileLink(item.path)} `;
} else if (item.type === "skill") {
replacement = `$${item.skill.name} `;
} else if (item.type === "slash-command") {
+8 -7
View File
@@ -6,19 +6,20 @@ import { remoteHttpClientLayer } from "@t3tools/client-runtime";
import { mobileCryptoLayer } from "../features/cloud/dpop";
import { mobileManagedRelayClientLayer } from "../features/cloud/managedRelayLayer";
import { resolveCloudPublicConfig } from "../features/cloud/publicConfig";
import { mobileTracingLayer } from "../features/observability/mobileTracing";
function configuredRelayUrl(): string {
return resolveCloudPublicConfig().relayUrl ?? "http://relay.invalid";
return resolveCloudPublicConfig().relay.url ?? "http://relay.invalid";
}
const mobileHttpClientLayer = remoteHttpClientLayer(fetch);
export const mobileRuntime = ManagedRuntime.make(
Layer.mergeAll(
mobileHttpClientLayer,
mobileCryptoLayer,
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provide(Layer.mergeAll(mobileHttpClientLayer, mobileCryptoLayer)),
),
mobileManagedRelayClientLayer(configuredRelayUrl()).pipe(
Layer.provideMerge(mobileCryptoLayer),
Layer.provideMerge(mobileHttpClientLayer),
Layer.provideMerge(mobileTracingLayer.pipe(Layer.provide(mobileHttpClientLayer))),
),
);
export const mobileRuntimeContextLayer = Layer.effectContext(mobileRuntime.contextEffect);
@@ -35,6 +35,7 @@ import { ProjectionCheckpointRepository } from "../src/persistence/Services/Proj
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeProviderRegistryLayer } from "../src/provider/testUtils/providerRegistryMock.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
@@ -293,6 +294,7 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
Layer.provide(providerEventLoggersLayer),
);
const providerRegistryLayer = makeProviderRegistryLayer();
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
@@ -375,6 +377,7 @@ export const makeOrchestrationIntegrationHarness = (
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provide(persistenceLayer),
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(ServerSettingsService.layerTest()),
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.24",
"version": "0.0.27",
"license": "MIT",
"repository": {
"type": "git",
@@ -22,7 +22,7 @@
"test": "vp test run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
+88 -3
View File
@@ -18,9 +18,16 @@ const emitInterleavedAssistantToolCalls =
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION === "1";
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
const permissionOptionIds = {
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
rejectOnce: process.env.T3_ACP_REJECT_ONCE_OPTION_ID ?? "reject-once",
};
const sessionId = "mock-session-1";
let currentModeId = "ask";
@@ -237,6 +244,21 @@ function modeState(): AcpSchema.SessionModeState {
};
}
const grokAcpModels: ReadonlyArray<AcpSchema.ModelInfo> = [
{ modelId: "grok-build", name: "Grok Build" },
{ modelId: "grok-mock-alt", name: "Grok Mock Alt" },
];
function modelState(): AcpSchema.SessionModelState {
const modelId = grokAcpModels.some((model) => model.modelId === currentModelId)
? currentModelId
: "grok-build";
return {
currentModelId: modelId,
availableModels: grokAcpModels,
};
}
const program = Effect.gen(function* () {
const agent = yield* EffectAcpAgent.AcpAgent;
@@ -257,6 +279,7 @@ const program = Effect.gen(function* () {
Effect.succeed({
sessionId,
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
);
@@ -273,11 +296,28 @@ const program = Effect.gen(function* () {
.pipe(
Effect.as({
modes: modeState(),
models: modelState(),
configOptions: configOptions(),
}),
),
);
yield* agent.handleSetSessionModel((request) =>
Effect.gen(function* () {
if (!grokAcpModels.some((model) => model.modelId === request.modelId)) {
return yield* AcpError.AcpRequestError.invalidParams(
`Unknown mock model id: ${request.modelId}`,
{
method: "session/set_model",
params: request,
},
);
}
currentModelId = request.modelId;
return {};
}),
);
yield* agent.handleSetSessionConfigOption((request) =>
Effect.gen(function* () {
if (exitOnSetConfigOption) {
@@ -325,6 +365,10 @@ const program = Effect.gen(function* () {
Effect.gen(function* () {
const requestedSessionId = String(request.sessionId ?? sessionId);
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
yield* Effect.sleep(`${promptDelayMs} millis`);
}
if (emitInterleavedAssistantToolCalls) {
const toolCallId = "tool-call-1";
@@ -419,9 +463,13 @@ const program = Effect.gen(function* () {
],
},
options: [
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
{ optionId: permissionOptionIds.allowOnce, name: "Allow once", kind: "allow_once" },
{
optionId: permissionOptionIds.allowAlways,
name: "Allow always",
kind: "allow_always",
},
{ optionId: permissionOptionIds.rejectOnce, name: "Reject", kind: "reject_once" },
],
});
@@ -514,6 +562,43 @@ const program = Effect.gen(function* () {
return { stopReason: "end_turn" };
}
if (emitXAiAskUserQuestion) {
const result = yield* agent.client.extRequest("_x.ai/ask_user_question", {
method: "x.ai/ask_user_question",
params: {
sessionId: requestedSessionId,
toolCallId: "ask-user-question-tool-call-1",
questions: [
{
question: "Which scope should Grok use?",
multiSelect: null,
options: [
{ label: "Workspace", description: "Use the current workspace" },
{ label: "Session", description: "Only use this session" },
],
},
],
mode: "default",
},
});
if (typeof result !== "object" || result === null || !("outcome" in result)) {
throw new Error("Expected _x.ai/ask_user_question response outcome.");
}
if (result.outcome === "cancelled") {
return { stopReason: "end_turn" };
}
if (
result.outcome !== "accepted" ||
!("answers" in result) ||
typeof result.answers !== "object" ||
result.answers === null
) {
throw new Error("Expected accepted _x.ai/ask_user_question response answers.");
}
return { stopReason: "end_turn" };
}
yield* agent.client.sessionUpdate({
sessionId: requestedSessionId,
update: {
+150
View File
@@ -0,0 +1,150 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { ServerConfig } from "../config.ts";
import { ProjectFaviconResolverLive } from "../project/Layers/ProjectFaviconResolver.ts";
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
import { ASSET_ROUTE_PREFIX, issueAssetUrl, resolveAsset } from "./AssetAccess.ts";
const configLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-asset-access-test-",
});
const testLayer = Layer.mergeAll(
configLayer,
WorkspacePathsLive,
ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive)),
ServerSecretStore.layer.pipe(Layer.provide(configLayer)),
).pipe(Layer.provideMerge(NodeServices.layer));
describe("AssetAccess", () => {
it.effect("issues workspace URLs that resolve the entry file and sibling assets", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-workspace-",
});
const htmlPath = path.join(root, "report.html");
const cssPath = path.join(root, "report.css");
yield* fileSystem.writeFileString(htmlPath, '<link rel="stylesheet" href="report.css">');
yield* fileSystem.writeFileString(cssPath, "body { color: red; }");
yield* fileSystem.writeFileString(path.join(root, ".env"), "SECRET=value");
const result = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: htmlPath,
},
workspaceRoot: root,
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "report.html")).toEqual({
kind: "file",
path: htmlPath,
});
expect(yield* resolveAsset(token, "report.css")).toEqual({
kind: "file",
path: cssPath,
});
expect(yield* resolveAsset(token, "../secret.txt")).toBeNull();
expect(yield* resolveAsset(token, ".env")).toBeNull();
expect(yield* resolveAsset(`${token}tampered`, "report.html")).toBeNull();
}).pipe(Effect.provide(testLayer)),
);
it.effect("rejects workspace files outside the authorized root", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-root-",
});
const outside = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-outside-",
});
const htmlPath = path.join(outside, "report.html");
yield* fileSystem.writeFileString(htmlPath, "<p>outside</p>");
const error = yield* issueAssetUrl({
resource: {
_tag: "workspace-file",
threadId: ThreadId.make("thread-1"),
path: htmlPath,
},
workspaceRoot: root,
}).pipe(Effect.flip);
expect(error.message).toContain("relative to the project root");
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues exact attachment capabilities by attachment id", () =>
Effect.gen(function* () {
const config = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001";
const attachmentPath = path.join(config.attachmentsDir, `${attachmentId}.png`);
yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true });
yield* fileSystem.writeFile(attachmentPath, new Uint8Array([1, 2, 3]));
const result = yield* issueAssetUrl({
resource: { _tag: "attachment", attachmentId },
});
const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
const token = suffix.slice(0, separatorIndex);
expect(yield* resolveAsset(token, "ignored.png")).toEqual({
kind: "file",
path: attachmentPath,
});
}).pipe(Effect.provide(testLayer)),
);
it.effect("issues project favicon capabilities with a signed fallback", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-asset-favicon-",
});
const faviconPath = path.join(root, "favicon.svg");
yield* fileSystem.writeFileString(faviconPath, "<svg />");
const faviconResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
const faviconSuffix = faviconResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const faviconSeparatorIndex = faviconSuffix.indexOf("/");
expect(
yield* resolveAsset(
faviconSuffix.slice(0, faviconSeparatorIndex),
faviconSuffix.slice(faviconSeparatorIndex + 1),
),
).toEqual({ kind: "file", path: faviconPath });
yield* fileSystem.remove(faviconPath);
const fallbackResult = yield* issueAssetUrl({
resource: { _tag: "project-favicon", cwd: root },
});
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
expect(
yield* resolveAsset(
fallbackSuffix.slice(0, fallbackSeparatorIndex),
fallbackSuffix.slice(fallbackSeparatorIndex + 1),
),
).toEqual({ kind: "project-favicon-fallback" });
}).pipe(Effect.provide(testLayer)),
);
});
+287
View File
@@ -0,0 +1,287 @@
import type { AssetResource } from "@t3tools/contracts";
import { AssetAccessError } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
base64UrlDecodeUtf8,
base64UrlEncode,
signPayload,
timingSafeEqualBase64Url,
} from "../auth/utils.ts";
import { ServerSecretStore } from "../auth/ServerSecretStore.ts";
import { resolveAttachmentPathById } from "../attachmentStore.ts";
import { ServerConfig } from "../config.ts";
import { ProjectFaviconResolver } from "../project/Services/ProjectFaviconResolver.ts";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
export const ASSET_ROUTE_PREFIX = "/api/assets";
export const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const SIGNING_SECRET_NAME = "asset-access-signing-key";
const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000;
const PREVIEWABLE_EXTENSIONS = new Set([".htm", ".html", ".pdf"]);
const PREVIEW_ASSET_EXTENSIONS = new Set([
...PREVIEWABLE_EXTENSIONS,
".avif",
".css",
".gif",
".ico",
".jpeg",
".jpg",
".js",
".mjs",
".otf",
".png",
".svg",
".ttf",
".webp",
".woff",
".woff2",
]);
const AssetClaimsSchema = Schema.Union([
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("workspace-file"),
workspaceRoot: Schema.String,
baseRelativePath: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("attachment"),
attachmentId: Schema.String,
expiresAt: Schema.Number,
}),
Schema.Struct({
version: Schema.Literal(1),
kind: Schema.Literal("project-favicon"),
workspaceRoot: Schema.String,
relativePath: Schema.NullOr(Schema.String),
expiresAt: Schema.Number,
}),
]);
type AssetClaims = typeof AssetClaimsSchema.Type;
const AssetClaimsJson = Schema.fromJsonString(AssetClaimsSchema);
const decodeAssetClaims = Schema.decodeUnknownOption(AssetClaimsJson);
const encodeAssetClaims = Schema.encodeSync(AssetClaimsJson);
export type ResolvedAsset =
| { readonly kind: "file"; readonly path: string }
| { readonly kind: "project-favicon-fallback" };
function decodeClaims(encodedPayload: string): AssetClaims | null {
try {
return Option.getOrNull(decodeAssetClaims(base64UrlDecodeUtf8(encodedPayload)));
} catch {
return null;
}
}
function decodeRelativePath(value: string): string | null {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
const failAccess = (message: string, cause?: unknown) =>
new AssetAccessError({ message, ...(cause === undefined ? {} : { cause }) });
const resolveCanonicalWorkspaceFile = Effect.fn("AssetAccess.resolveCanonicalWorkspaceFile")(
function* (input: { readonly workspaceRoot: string; readonly relativePath: string }) {
const fileSystem = yield* FileSystem.FileSystem;
const workspacePaths = yield* WorkspacePaths;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot(input)
.pipe(Effect.orElseSucceed(() => null));
if (!resolved) return null;
const [canonicalRoot, canonicalFile] = yield* Effect.all([
fileSystem.realPath(input.workspaceRoot).pipe(Effect.orElseSucceed(() => null)),
fileSystem.realPath(resolved.absolutePath).pipe(Effect.orElseSucceed(() => null)),
]);
if (!canonicalRoot || !canonicalFile) return null;
const path = yield* Path.Path;
const relative = path.relative(canonicalRoot, canonicalFile);
if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative)) return null;
const info = yield* fileSystem.stat(canonicalFile).pipe(Effect.orElseSucceed(() => null));
return info?.type === "File" ? canonicalFile : null;
},
);
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
readonly resource: AssetResource;
readonly workspaceRoot?: string;
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const workspacePaths = yield* WorkspacePaths;
const expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
let claims: AssetClaims;
let fileName: string;
switch (input.resource._tag) {
case "workspace-file": {
if (!input.workspaceRoot) {
return yield* failAccess("Workspace context was not found.");
}
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const relativePath = path.isAbsolute(input.resource.path)
? path.relative(workspaceRoot, input.resource.path)
: input.resource.path;
const resolved = yield* workspacePaths
.resolveRelativePathWithinRoot({ workspaceRoot, relativePath })
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
if (!PREVIEWABLE_EXTENSIONS.has(path.extname(resolved.relativePath).toLowerCase())) {
return yield* failAccess("Only HTML and PDF files can open in the browser.");
}
const canonicalFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot,
relativePath: resolved.relativePath,
});
if (!canonicalFile) {
return yield* failAccess("Workspace asset was not found.");
}
claims = {
version: 1,
kind: "workspace-file",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
baseRelativePath: path.dirname(resolved.relativePath),
expiresAt,
};
fileName = path.basename(resolved.relativePath);
break;
}
case "attachment": {
const config = yield* ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: input.resource.attachmentId,
});
if (!attachmentPath) {
return yield* failAccess("Attachment was not found.");
}
claims = {
version: 1,
kind: "attachment",
attachmentId: input.resource.attachmentId,
expiresAt,
};
fileName = path.basename(attachmentPath);
break;
}
case "project-favicon": {
const workspaceRoot = yield* workspacePaths
.normalizeWorkspaceRoot(input.resource.cwd)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const faviconResolver = yield* ProjectFaviconResolver;
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot);
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
if (
relativePath &&
!(yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }))
) {
return yield* failAccess("Project favicon was not found.");
}
claims = {
version: 1,
kind: "project-favicon",
workspaceRoot: yield* fileSystem
.realPath(workspaceRoot)
.pipe(Effect.mapError((cause) => failAccess("Failed to resolve workspace.", cause))),
relativePath,
expiresAt,
};
fileName = relativePath ? path.basename(relativePath) : "favicon.svg";
break;
}
}
const secretStore = yield* ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.mapError((cause) => failAccess(cause.message, cause)));
const encodedPayload = base64UrlEncode(encodeAssetClaims(claims));
const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`;
return {
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
expiresAt,
};
});
export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
token: string,
relativePath: string,
) {
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
const secretStore = yield* ServerSecretStore;
const signingSecret = yield* secretStore
.getOrCreateRandom(SIGNING_SECRET_NAME, 32)
.pipe(Effect.orElseSucceed(() => null));
if (!signingSecret) return null;
if (!timingSafeEqualBase64Url(signature, signPayload(encodedPayload, signingSecret))) return null;
const claims = decodeClaims(encodedPayload);
if (!claims || claims.expiresAt <= (yield* Clock.currentTimeMillis)) return null;
if (claims.kind === "attachment") {
const config = yield* ServerConfig;
const attachmentPath = resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: claims.attachmentId,
});
if (!attachmentPath) return null;
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* fileSystem.stat(attachmentPath).pipe(Effect.orElseSucceed(() => null));
return info?.type === "File"
? ({ kind: "file", path: attachmentPath } satisfies ResolvedAsset)
: null;
}
if (claims.kind === "project-favicon") {
if (claims.relativePath === null) {
return { kind: "project-favicon-fallback" } satisfies ResolvedAsset;
}
const faviconPath = yield* resolveCanonicalWorkspaceFile({
workspaceRoot: claims.workspaceRoot,
relativePath: claims.relativePath,
});
return faviconPath ? ({ kind: "file", path: faviconPath } satisfies ResolvedAsset) : null;
}
const decodedPath = decodeRelativePath(relativePath);
if (decodedPath === null) return null;
const path = yield* Path.Path;
const segments = decodedPath.split(/[\\/]/);
if (
decodedPath.length === 0 ||
decodedPath.includes("\0") ||
segments.some((segment) => segment === "." || segment === ".." || segment.startsWith(".")) ||
!PREVIEW_ASSET_EXTENSIONS.has(path.extname(decodedPath).toLowerCase())
) {
return null;
}
const joinedRelativePath =
claims.baseRelativePath === "." ? decodedPath : path.join(claims.baseRelativePath, decodedPath);
const workspaceFile = yield* resolveCanonicalWorkspaceFile({
workspaceRoot: claims.workspaceRoot,
relativePath: joinedRelativePath,
});
return workspaceFile ? ({ kind: "file", path: workspaceFile } satisfies ResolvedAsset) : null;
});
-2
View File
@@ -1,8 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off
import NodePath from "node:path";
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\]+/, "");
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
+26 -24
View File
@@ -38,11 +38,11 @@ import { environmentAuthenticatedAuthLayer } from "./auth/http.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
class ProjectCliHttpApi extends HttpApi.make("environment").add(EnvironmentOrchestrationHttpApi) {}
const cloudCli = makeCli({ cloudEnabled: true });
const noCloudCli = makeCli({ cloudEnabled: false });
const connectCli = makeCli({ cloudEnabled: true });
const noConnectCli = makeCli({ cloudEnabled: false });
const runCli = (args: ReadonlyArray<string>, command = cli) =>
Command.runWith(command, { version: "0.0.0" })(args);
const runCloudCli = (args: ReadonlyArray<string>) => runCli(args, cloudCli);
const runConnectCli = (args: ReadonlyArray<string>) => runCli(args, connectCli);
const runCliWithRuntime = (args: ReadonlyArray<string>) =>
runCli(args).pipe(Effect.provide(CliRuntimeLayer));
@@ -179,9 +179,9 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("rejects cloud commands when public cloud configuration is missing", () =>
it.effect("rejects connect commands when public configuration is missing", () =>
Effect.gen(function* () {
const error = yield* runCli(["cloud", "status"], noCloudCli).pipe(Effect.flip);
const error = yield* runCli(["connect", "status"], noConnectCli).pipe(Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
@@ -189,20 +189,20 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
if (error._tag !== "ShowHelp") {
assert.fail(`Expected ShowHelp, got ${error._tag}`);
}
assert.deepEqual(error.commandPath, ["t3", "cloud"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Cloud public configuration");
assert.deepEqual(error.commandPath, ["t3", "connect"]);
assert.include(error.errors[0]?.message ?? "", "missing T3 Connect public configuration");
const output = (yield* TestConsole.errorLines).join("\n");
assert.include(output, "ERROR");
assert.include(output, "missing T3 Cloud public configuration");
assert.include(output, "missing T3 Connect public configuration");
}).pipe(Effect.provide(Layer.mergeAll(CliRuntimeLayer, TestConsole.layer))),
);
it.effect("reports fresh headless cloud state without requiring local configuration", () =>
it.effect("reports fresh headless connect state without requiring local configuration", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const status = JSON.parse(output) as {
@@ -221,21 +221,21 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
it.effect("reports actionable human-readable headless cloud state", () =>
it.effect("reports actionable human-readable headless connect state", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-status-human-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir]),
runConnectCli(["connect", "status", "--base-dir", baseDir]),
);
assert.include(output, "T3 Cloud\n Exposure: disabled");
assert.include(output, "T3 Connect\n Exposure: disabled");
assert.include(output, " Authorization: missing");
assert.include(output, " Environment link: not provisioned");
assert.include(output, "Next: Run `t3 cloud link` to authorize and enable cloud exposure.");
assert.include(output, "Next: Run `t3 connect link` to authorize and enable T3 Connect.");
}),
);
it.effect("logs in to headless cloud without enabling exposure", () =>
it.effect("logs in to headless connect without enabling access", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-login-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -250,9 +250,11 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
}),
);
const login = yield* captureStdout(runCloudCli(["cloud", "login", "--base-dir", baseDir]));
const login = yield* captureStdout(
runConnectCli(["connect", "login", "--base-dir", baseDir]),
);
const status = yield* captureStdout(
runCloudCli(["cloud", "status", "--base-dir", baseDir, "--json"]),
runConnectCli(["connect", "status", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off - CLI JSON output is decoded as a presentation DTO.
const decoded = JSON.parse(status.output) as {
@@ -260,24 +262,24 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
readonly authenticated: boolean;
};
assert.equal(login.output, "Signed in to T3 Cloud.");
assert.equal(login.output, "Signed in to T3 Connect.");
assert.isFalse(decoded.desired);
assert.isTrue(decoded.authenticated);
}),
);
it.effect("disables headless cloud exposure without a running server", () =>
it.effect("disables headless connect without a running server", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-unlink-test-"));
const { output } = yield* captureStdout(
runCloudCli(["cloud", "unlink", "--base-dir", baseDir]),
runConnectCli(["connect", "unlink", "--base-dir", baseDir]),
);
assert.equal(output, "T3 Cloud exposure is disabled locally.");
assert.equal(output, "T3 Connect is disabled locally.");
}),
);
it.effect("logs out of headless cloud and removes the stored CLI authorization", () =>
it.effect("logs out of headless connect and removes the stored CLI authorization", () =>
Effect.gen(function* () {
const baseDir = mkdtempSync(join(tmpdir(), "t3-cli-cloud-logout-test-"));
const { secretsDir } = yield* deriveServerPaths(baseDir, undefined);
@@ -286,10 +288,10 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
writeFileSync(tokenPath, "invalid persisted token");
const { output } = yield* captureStdout(
runCloudCli(["cloud", "logout", "--base-dir", baseDir]),
runConnectCli(["connect", "logout", "--base-dir", baseDir]),
);
assert.equal(output, "Signed out of T3 Cloud locally.");
assert.equal(output, "Signed out of T3 Connect locally.");
assert.isFalse(existsSync(tokenPath));
}),
);
+10 -10
View File
@@ -8,7 +8,7 @@ import * as CliError from "effect/unstable/cli/CliError";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { cloudCommand } from "./cli/cloud.ts";
import { connectCommand } from "./cli/connect.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
import { projectCommand } from "./cli/project.ts";
@@ -16,23 +16,23 @@ import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
const cloudPublicConfigMissingMessage =
"T3 Cloud commands are unavailable: this build is missing T3 Cloud public configuration.";
const connectPublicConfigMissingMessage =
"T3 Connect commands are unavailable: this build is missing T3 Connect public configuration.";
class CloudPublicConfigMissingError extends CliError.UserError {
class ConnectPublicConfigMissingError extends CliError.UserError {
override get message() {
return cloudPublicConfigMissingMessage;
return connectPublicConfigMissingMessage;
}
}
const cloudUnavailableCommand = Command.make("cloud").pipe(
Command.withDescription("T3 Cloud is unavailable in builds without public cloud configuration."),
const connectUnavailableCommand = Command.make("connect").pipe(
Command.withDescription("T3 Connect is unavailable in builds without public configuration."),
Command.withHidden,
Command.withHandler(() =>
Effect.fail(
new CliError.ShowHelp({
commandPath: ["t3", "cloud"],
errors: [new CloudPublicConfigMissingError({ cause: cloudPublicConfigMissingMessage })],
commandPath: ["t3", "connect"],
errors: [new ConnectPublicConfigMissingError({ cause: connectPublicConfigMissingMessage })],
}),
),
),
@@ -47,7 +47,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
serveCommand,
authCommand,
projectCommand,
cloudEnabled ? cloudCommand : cloudUnavailableCommand,
cloudEnabled ? connectCommand : connectUnavailableCommand,
]),
);
@@ -3,7 +3,7 @@ import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import { acquireRelayClientForLink } from "./cloud.ts";
import { acquireRelayClientForLink } from "./connect.ts";
const managedExecutable = {
status: "available",
@@ -89,15 +89,15 @@ function formatCloudStatus(status: CloudCliStatus, options?: { readonly json?: b
? "pending server startup"
: "not provisioned";
const nextStep = !status.authenticated
? "Run `t3 cloud link` to authorize and enable cloud exposure."
? "Run `t3 connect link` to authorize and enable T3 Connect."
: !status.desired
? "Run `t3 cloud link` to enable cloud exposure."
? "Run `t3 connect link` to enable T3 Connect."
: !status.linked
? "Start T3 to provision the environment link and launch its managed tunnel."
: undefined;
return [
"T3 Cloud",
"T3 Connect",
` Exposure: ${status.desired ? "enabled" : "disabled"}`,
` Authorization: ${status.authenticated ? "stored credential" : "missing"}`,
` Environment link: ${provisioned}`,
@@ -112,7 +112,7 @@ const CLOUD_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(5);
const confirmRelayClientInstall = (version: string) =>
Prompt.run(
Prompt.confirm({
message: `The T3 relay client is required for T3 Cloud exposure. Download and install version ${version}?`,
message: `The T3 relay client is required for T3 Connect. Download and install version ${version}?`,
initial: false,
}),
);
@@ -169,7 +169,7 @@ const withCloudCliSessionToken = <A, E, R>(
environmentAuth.issueSession({
scopes: [AuthRelayWriteScope],
subject: "cloud-cli",
label: "t3 cloud cli",
label: "t3 connect cli",
}),
(issued) => run(issued.token),
(issued) => environmentAuth.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
@@ -194,7 +194,7 @@ const runLiveCloudUnlink = Effect.fn("cloud.cli.run_live_unlink")(function* () {
baseUrl: runtimeState.value.origin,
}).pipe(
Effect.flatMap((client) =>
client.cloud.unlink({ headers: { authorization: `Bearer ${token}` } }),
client.connect.unlink({ headers: { authorization: `Bearer ${token}` } }),
),
Effect.timeout(CLOUD_CLI_LIVE_SERVER_TIMEOUT),
),
@@ -249,24 +249,24 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
if (liveResult.status === "failed") {
yield* Console.warn(
`T3 Cloud exposure is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
`T3 Connect is disabled, but the running server could not stop its tunnel: ${String(liveResult.cause)}\nRestart that server to stop the connector.`,
);
} else {
yield* Console.log("T3 Cloud exposure is disabled locally.");
yield* Console.log("T3 Connect is disabled locally.");
}
if (Exit.isFailure(relayResult)) {
yield* Console.warn(
options.clearAuthorization
? `Could not revoke the relay-side environment record before signing out: ${String(relayResult.cause)}\nThe stored CLI authorization was still removed locally.`
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 cloud unlink\` again when the relay is reachable.`,
: `Could not revoke the relay-side environment record yet: ${String(relayResult.cause)}\nRun \`t3 connect unlink\` again when the relay is reachable.`,
);
} else if (relayResult.value.status === "revoked") {
yield* Console.log("Revoked the relay-side environment record.");
}
if (options.clearAuthorization) {
yield* Console.log("Signed out of T3 Cloud locally.");
yield* Console.log("Signed out of T3 Connect locally.");
}
});
@@ -307,26 +307,26 @@ const runCloudCommand = <A, E>(
return yield* run.pipe(Effect.provide(runtimeLayer));
});
const cloudLoginCommand = Command.make("login", {
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize the T3 Cloud CLI without enabling cloud exposure."),
Command.withDescription("Authorize the T3 Connect CLI without enabling remote access."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
Effect.gen(function* () {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
yield* tokens.get;
yield* Console.log("Signed in to T3 Cloud.");
yield* Console.log("Signed in to T3 Connect.");
}),
),
),
);
const cloudLinkCommand = Command.make("link", {
const connectLinkCommand = Command.make("link", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Authorize this environment for T3 Cloud and expose it on next start."),
Command.withDescription("Authorize this environment for T3 Connect on next start."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -338,7 +338,7 @@ const cloudLinkCommand = Command.make("link", {
reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Cloud link cancelled. The relay client was not installed.");
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return;
}
yield* Console.log(
@@ -349,18 +349,18 @@ const cloudLinkCommand = Command.make("link", {
yield* tokens.get;
yield* CliState.setCliDesiredCloudLink(true);
yield* Console.log(
"This T3 environment will be available over T3 Cloud the next time T3 starts.",
"This T3 environment will be available through T3 Connect the next time T3 starts.",
);
}),
),
),
);
const cloudStatusCommand = Command.make("status", {
const connectStatusCommand = Command.make("status", {
...projectLocationFlags,
json: jsonFlag,
}).pipe(
Command.withDescription("Show persisted T3 Cloud and relay client state."),
Command.withDescription("Show persisted T3 Connect and relay client state."),
Command.withHandler((flags) =>
runCloudCommand(
flags,
@@ -395,31 +395,31 @@ const cloudStatusCommand = Command.make("status", {
),
);
const cloudUnlinkCommand = Command.make("unlink", {
const connectUnlinkCommand = Command.make("unlink", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure while retaining the stored authorization."),
Command.withDescription("Disable T3 Connect while retaining the stored authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: false })),
),
);
const cloudLogoutCommand = Command.make("logout", {
const connectLogoutCommand = Command.make("logout", {
...projectLocationFlags,
}).pipe(
Command.withDescription("Disable T3 Cloud exposure and clear the stored CLI authorization."),
Command.withDescription("Disable T3 Connect and clear the stored CLI authorization."),
Command.withHandler((flags) =>
runCloudCommand(flags, disconnectCloud({ clearAuthorization: true })),
),
);
export const cloudCommand = Command.make("cloud").pipe(
Command.withDescription("Manage headless T3 Cloud exposure."),
export const connectCommand = Command.make("connect").pipe(
Command.withDescription("Manage headless T3 Connect access."),
Command.withSubcommands([
cloudLoginCommand,
cloudLinkCommand,
cloudStatusCommand,
cloudUnlinkCommand,
cloudLogoutCommand,
connectLoginCommand,
connectLinkCommand,
connectStatusCommand,
connectUnlinkCommand,
connectLogoutCommand,
]),
);
+8 -8
View File
@@ -96,7 +96,7 @@ const make = Effect.gen(function* () {
const clear = secrets
.remove(CLOUD_CLI_OAUTH_TOKEN_SECRET)
.pipe(wrapError("Could not remove the stored T3 Cloud CLI credential."));
.pipe(wrapError("Could not remove the stored T3 Connect CLI credential."));
const read = Effect.fn("cloud.cli_token.read")(function* () {
const encoded = yield* secrets.get(CLOUD_CLI_OAUTH_TOKEN_SECRET);
@@ -146,7 +146,7 @@ const make = Effect.gen(function* () {
const url = new URL(request.originalUrl, metadata.redirectUri);
const code = url.searchParams.get("code");
if (url.searchParams.get("state") !== state || !code) {
return HttpServerResponse.text("Invalid T3 Cloud authorization callback.", {
return HttpServerResponse.text("Invalid T3 Connect authorization callback.", {
status: 400,
});
}
@@ -154,7 +154,7 @@ const make = Effect.gen(function* () {
return yield* HttpServerResponse.html`
<html>
<body style="font-family: sans-serif; text-align: center; margin-top: 50px;">
<h1>T3 Cloud authorization complete</h1>
<h1>T3 Connect authorization complete</h1>
<p>You can close this window and return to your terminal.</p>
</body>
</html>
@@ -182,13 +182,13 @@ const make = Effect.gen(function* () {
authorizationUrl.searchParams.set("state", state);
authorizationUrl.searchParams.set("code_challenge", challenge);
authorizationUrl.searchParams.set("code_challenge_method", "S256");
yield* Console.log(`Open this URL to authorize T3 Cloud:\n${authorizationUrl.toString()}\n`);
yield* Console.log(`Open this URL to authorize T3 Connect:\n${authorizationUrl.toString()}\n`);
const code = yield* Deferred.await(callback).pipe(
Effect.timeout(CLOUD_CLI_OAUTH_CALLBACK_TIMEOUT),
Effect.catchTag("TimeoutError", () =>
Effect.fail(
new CloudCliTokenManagerError({
message: "Timed out waiting for T3 Cloud authorization.",
message: "Timed out waiting for T3 Connect authorization.",
}),
),
),
@@ -213,12 +213,12 @@ const make = Effect.gen(function* () {
});
const getExisting = semaphore.withPermits(1)(
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Cloud CLI credential.")),
getExistingNoLock().pipe(wrapError("Could not refresh the T3 Connect CLI credential.")),
);
const hasCredential = semaphore.withPermits(1)(
read().pipe(
Effect.map(Option.isSome),
wrapError("Could not read the stored T3 Cloud CLI credential."),
wrapError("Could not read the stored T3 Connect CLI credential."),
),
);
const get = semaphore.withPermits(1)(
@@ -227,7 +227,7 @@ const make = Effect.gen(function* () {
return Option.isSome(token)
? token.value
: yield* Effect.scoped(login()).pipe(Effect.flatMap(persist));
}).pipe(wrapError("Could not authorize the T3 Cloud CLI.")),
}).pipe(wrapError("Could not authorize the T3 Connect CLI.")),
);
return CloudCliTokenManager.of({ get, getExisting, hasCredential, clear });
+1 -1
View File
@@ -76,7 +76,7 @@ describe("reconcileDesiredCloudLink", () => {
expect(error).toMatchObject({
_tag: "EnvironmentHttpUnauthorizedError",
message: "Run `t3 cloud link` to authorize this environment.",
message: "Run `t3 connect link` to authorize this environment.",
});
}).pipe(
Effect.provideService(
+6 -6
View File
@@ -509,7 +509,7 @@ const relayClientRequest = <A>(
Effect.mapError(
(cause) =>
new EnvironmentHttpInternalServerError({
message: `T3 Cloud relay request failed: ${String(cause)}`,
message: `T3 Connect relay request failed: ${String(cause)}`,
}),
),
);
@@ -535,7 +535,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
onNone: () =>
Effect.fail(
new EnvironmentHttpUnauthorizedError({
message: "Run `t3 cloud link` to authorize this environment.",
message: "Run `t3 connect link` to authorize this environment.",
}),
),
onSome: Effect.succeed,
@@ -595,7 +595,7 @@ const reconcileDesiredCloudLinkWith = Effect.fn("environment.cloud.reconcileDesi
CloudCliTokenManagerError: (error) =>
failEnvironmentCloudInternalError(error.message)(error.cause),
SecretStoreError: failEnvironmentCloudInternalError(
"Could not persist desired T3 Cloud link state.",
"Could not persist desired T3 Connect link state.",
),
}),
);
@@ -874,7 +874,7 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
scopes: AuthStandardClientScopes,
subject: "cloud-connect",
ttl: Duration.minutes(2),
label: "T3 Cloud connect",
label: "T3 Connect connect",
proofKeyThumbprint: proof.clientProofKeyThumbprint,
});
const responsePayload = {
@@ -924,9 +924,9 @@ const cloudMintCredentialHandler = Effect.fn("environment.cloud.mintCredential")
}),
);
export const cloudHttpApiLayer = HttpApiBuilder.group(
export const connectHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"cloud",
"connect",
Effect.fnUntraced(function* (handlers) {
const dependencies = yield* cloudHttpDependencies;
return handlers
+22
View File
@@ -0,0 +1,22 @@
import { assert, it } from "@effect/vitest";
import { ProviderInstanceId } from "@t3tools/contracts";
import { createModelSelection } from "@t3tools/shared/model";
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
it("returns the selected Codex service tier id", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
{ id: "serviceTier", value: "flex" },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
});
it("keeps legacy persisted fast mode selections working", () => {
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
{ id: "fastMode", value: true },
]);
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
});
+14
View File
@@ -0,0 +1,14 @@
import type { ModelSelection } from "@t3tools/contracts";
import {
getModelSelectionBooleanOptionValue,
getModelSelectionStringOptionValue,
} from "@t3tools/shared/model";
export function getCodexServiceTierOptionValue(
modelSelection: ModelSelection | null | undefined,
): string | undefined {
return (
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
);
}
+1 -1
View File
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
);
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
const details = yield* gitCore
.statusDetails(cwd)
.statusDetailsRemote(cwd)
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
if (details === null || !details.isRepo) {
return null;
+22 -83
View File
@@ -24,15 +24,13 @@ import {
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import { OtlpTracer } from "effect/unstable/observability";
import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths.ts";
import { resolveAttachmentPathById } from "./attachmentStore.ts";
import { resolveStaticDir, ServerConfig } from "./config.ts";
import {
ASSET_ROUTE_PREFIX,
FALLBACK_PROJECT_FAVICON_SVG,
resolveAsset,
} from "./assets/AssetAccess.ts";
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
annotateEnvironmentRequest,
@@ -43,8 +41,6 @@ import {
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import { browserApiCorsAllowedHeaders, browserApiCorsAllowedMethods } from "./httpCors.ts";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
@@ -169,107 +165,50 @@ export const otlpTracesProxyRouteLayer = HttpRouter.add(
),
);
export const attachmentsRouteLayer = HttpRouter.add(
export const assetRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
`${ASSET_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const config = yield* ServerConfig;
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
}
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
status: isIdLookup ? 404 : 400,
});
}
const fileSystem = yield* FileSystem.FileSystem;
const fileInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));
if (!fileInfo || fileInfo.type !== "File") {
const suffix = url.value.pathname.slice(`${ASSET_ROUTE_PREFIX}/`.length);
const separatorIndex = suffix.indexOf("/");
if (separatorIndex <= 0) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
return yield* HttpServerResponse.file(filePath, {
status: 200,
headers: {
"Cache-Control": "public, max-age=31536000, immutable",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
const asset = yield* resolveAsset(
suffix.slice(0, separatorIndex),
suffix.slice(separatorIndex + 1),
);
}).pipe(
Effect.catchTags({
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
EnvironmentInternalError: HttpServerRespondable.toResponse,
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
}),
),
);
export const projectFaviconRouteLayer = HttpRouter.add(
"GET",
"/api/project-favicon",
Effect.gen(function* () {
yield* authenticateRawRouteWithScope(AuthOrchestrationReadScope);
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
if (!asset) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const projectCwd = url.value.searchParams.get("cwd");
if (!projectCwd) {
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
}
const faviconResolver = yield* ProjectFaviconResolver;
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
if (!faviconFilePath) {
if (asset.kind === "project-favicon-fallback") {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
});
}
return yield* HttpServerResponse.file(faviconFilePath, {
return yield* HttpServerResponse.file(asset.path, {
status: 200,
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
"Cache-Control": "private, max-age=3600",
"X-Content-Type-Options": "nosniff",
},
}).pipe(
Effect.orElseSucceed(() => HttpServerResponse.text("Internal Server Error", { status: 500 })),
);
}).pipe(
Effect.catchTags({
EnvironmentAuthInvalidError: HttpServerRespondable.toResponse,
EnvironmentInternalError: HttpServerRespondable.toResponse,
EnvironmentScopeRequiredError: HttpServerRespondable.toResponse,
}),
),
}),
);
export const staticAndDevRouteLayer = HttpRouter.add(
+2
View File
@@ -205,6 +205,8 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("rightPanel.toggle"), "mod+alt+b");
assert.equal(defaultsByCommand.get("terminal.splitVertical"), "mod+shift+d");
assert.equal(defaultsByCommand.get("modelPicker.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("modelPicker.jump.9"), "mod+9");
}),
+165
View File
@@ -0,0 +1,165 @@
import { expect, it } from "@effect/vitest";
import { EnvironmentId, PreviewTabId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Stream from "effect/Stream";
import { McpSchema, McpServer } from "effect/unstable/ai";
import { HttpServerResponse } from "effect/unstable/http";
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const environmentId = EnvironmentId.make("environment-mcp-test");
const threadId = ThreadId.make("thread-mcp-test");
const tabId = PreviewTabId.make("tab-mcp-test");
const invocation = {
environmentId,
threadId,
providerSessionId: "provider-session-mcp-test",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: Number.MAX_SAFE_INTEGER,
};
const client = McpSchema.McpServerClient.of({
clientId: 1,
initializePayload: {
protocolVersion: "2025-03-26",
capabilities: {},
clientInfo: { name: "mcp-test", version: "1.0.0" },
},
getClient: Effect.die("unused"),
});
const TestLayer = McpHttpServer.PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpServer.McpServer.layer),
Layer.provideMerge(PreviewAutomationBroker.layer),
);
it("normalizes empty successful notification responses to accepted", () => {
const notificationResponse = McpHttpServer.normalizeMcpHttpResponse(
HttpServerResponse.text("", { status: 200, contentType: "application/json" }),
);
expect(notificationResponse.status).toBe(202);
const resultResponse = McpHttpServer.normalizeMcpHttpResponse(
HttpServerResponse.jsonUnsafe({ jsonrpc: "2.0", id: 1, result: {} }),
);
expect(resultResponse.status).toBe(200);
});
it.effect("registers annotated tools and preserves authenticated request context", () =>
Effect.scoped(
Effect.gen(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const requests = yield* broker.connect("mcp-test-client");
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: true,
result:
request.operation === "snapshot"
? {
url: "http://example.test/",
title: "Example",
loading: false,
visibleText: "Example",
interactiveElements: [],
accessibilityTree: {},
consoleEntries: [],
networkEntries: [],
actionTimeline: [],
screenshot: {
mimeType: "image/png",
data: Buffer.from("png").toString("base64"),
width: 10,
height: 5,
},
}
: request.operation === "press"
? undefined
: {
available: true,
visible: true,
tabId,
url: "http://example.test/",
title: "Example",
loading: false,
},
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "mcp-test-client",
environmentId,
threadId,
tabId,
visible: true,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const statusTool = server.tools.find(({ tool }) => tool.name === "preview_status");
expect(statusTool?.tool.annotations?.readOnlyHint).toBe(true);
expect(statusTool?.tool.annotations?.idempotentHint).toBe(true);
expect(statusTool?.tool.annotations?.destructiveHint).toBe(false);
const snapshotTool = server.tools.find(({ tool }) => tool.name === "preview_snapshot");
expect(snapshotTool?.tool.annotations?.readOnlyHint).toBe(true);
expect(snapshotTool?.tool.annotations?.idempotentHint).toBe(true);
expect(snapshotTool?.tool.annotations?.openWorldHint).toBe(true);
const clickTool = server.tools.find(({ tool }) => tool.name === "preview_click");
expect(clickTool?.tool.annotations?.readOnlyHint).toBe(false);
expect(clickTool?.tool.annotations?.destructiveHint).toBe(true);
expect(clickTool?.tool.annotations?.openWorldHint).toBe(true);
const navigateTool = server.tools.find(({ tool }) => tool.name === "preview_navigate");
expect(navigateTool?.tool.annotations?.destructiveHint).toBe(false);
expect(navigateTool?.tool.annotations?.openWorldHint).toBe(true);
const status = yield* server
.callTool({ name: "preview_status", arguments: {} })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(status.isError).toBe(false);
expect(status.structuredContent).toMatchObject({
available: true,
tabId,
});
const malformed = yield* server
.callTool({ name: "preview_click", arguments: { selector: "" } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(malformed.isError).toBe(true);
const snapshot = yield* server
.callTool({ name: "preview_snapshot", arguments: {} })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(snapshot.isError).toBe(false);
expect(snapshot.content.some((content) => content.type === "image")).toBe(true);
expect(snapshot.structuredContent).toMatchObject({
screenshot: { mimeType: "image/png", width: 10, height: 5 },
});
const press = yield* server
.callTool({ name: "preview_press", arguments: { key: "Enter" } })
.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.provideService(McpSchema.McpServerClient, client),
);
expect(press.isError).toBe(false);
expect(press.structuredContent).toBeNull();
expect(press.content).toEqual([{ type: "text", text: "null" }]);
}),
).pipe(Effect.provide(TestLayer)),
);
+191
View File
@@ -0,0 +1,191 @@
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import type * as Types from "effect/Types";
import { McpSchema, McpServer, Tool } from "effect/unstable/ai";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import packageJson from "../../package.json" with { type: "json" };
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
import {
PreviewSnapshotToolkitHandlersLive,
PreviewStandardToolkitHandlersLive,
} from "./toolkits/preview/handlers.ts";
import {
PreviewSnapshotTool,
PreviewSnapshotToolkit,
PreviewStandardToolkit,
} from "./toolkits/preview/tools.ts";
const unauthorized = HttpServerResponse.jsonUnsafe(
{
error: "invalid_mcp_credential",
message: "A valid provider-scoped MCP bearer credential is required.",
},
{
status: 401,
headers: {
"cache-control": "no-store",
"www-authenticate": "Bearer",
},
},
);
type AuthenticatedHttpEffect = Effect.Effect<
HttpServerResponse.HttpServerResponse,
Types.unhandled,
McpInvocationContext.McpInvocationContext
>;
type McpAuthMiddleware = (
httpEffect: AuthenticatedHttpEffect,
) => Effect.Effect<
HttpServerResponse.HttpServerResponse,
Types.unhandled,
HttpServerRequest.HttpServerRequest
>;
export const normalizeMcpHttpResponse = (
response: HttpServerResponse.HttpServerResponse,
): HttpServerResponse.HttpServerResponse => {
const bodyIsEmpty =
response.body._tag === "Empty" ||
(response.body._tag === "Uint8Array" && response.body.contentLength === 0) ||
(response.body._tag === "Raw" && response.body.contentLength === 0);
return response.status === 200 && bodyIsEmpty
? HttpServerResponse.setStatus(response, 202)
: response;
};
const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
Effect.map(
(registry): McpAuthMiddleware =>
Effect.fn("McpHttpServer.authenticateRequest")(function* (httpEffect) {
const request = yield* HttpServerRequest.HttpServerRequest;
const authorization = request.headers.authorization;
const token =
authorization?.startsWith("Bearer ") === true
? authorization.slice("Bearer ".length).trim()
: "";
const invocation = yield* registry.resolve(token);
if (!invocation) return unauthorized;
return yield* httpEffect.pipe(
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.map(normalizeMcpHttpResponse),
);
}),
),
Effect.withSpan("McpHttpServer.makeAuthMiddleware"),
);
const McpAuthMiddlewareLive = HttpRouter.middleware<{
provides: McpInvocationContext.McpInvocationContext;
}>()(makeMcpAuthMiddleware).layer;
const registerPreviewSnapshot = Effect.fn("McpHttpServer.registerPreviewSnapshot")(function* () {
const server = yield* McpServer.McpServer;
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const built = yield* PreviewSnapshotToolkit;
const tool = PreviewSnapshotTool;
yield* server.addTool({
tool: new McpSchema.Tool({
name: tool.name,
description: Tool.getDescription(tool),
inputSchema: Tool.getJsonSchema(tool),
annotations: {
...Context.getOption(tool.annotations, Tool.Title).pipe(
Option.map((title) => ({ title })),
Option.getOrUndefined,
),
readOnlyHint: Context.get(tool.annotations, Tool.Readonly),
destructiveHint: Context.get(tool.annotations, Tool.Destructive),
idempotentHint: Context.get(tool.annotations, Tool.Idempotent),
openWorldHint: Context.get(tool.annotations, Tool.OpenWorld),
},
}),
annotations: tool.annotations,
handle: (payload) =>
Effect.withFiber((fiber) => {
const invocation = Context.getUnsafe(
fiber.context,
McpInvocationContext.McpInvocationContext,
);
return built.handle("preview_snapshot", payload).pipe(
Stream.unwrap,
Stream.run(Sink.last()),
Effect.flatMap(Effect.fromOption),
Effect.provideService(PreviewAutomationBroker.PreviewAutomationBroker, broker),
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
Effect.matchCause({
onFailure: (cause) =>
new McpSchema.CallToolResult({
isError: true,
content: [{ type: "text", text: Cause.pretty(cause) }],
}),
onSuccess: ({ encodedResult }) => {
const snapshot = encodedResult as {
readonly screenshot: {
readonly mimeType: "image/png";
readonly data: string;
readonly width: number;
readonly height: number;
};
readonly [key: string]: unknown;
};
const { screenshot, ...page } = snapshot;
const metadata = {
...page,
screenshot: {
mimeType: screenshot.mimeType,
width: screenshot.width,
height: screenshot.height,
},
};
return new McpSchema.CallToolResult({
isError: false,
structuredContent: metadata,
content: [
{ type: "text", text: JSON.stringify(metadata) },
{
type: "image",
data: new Uint8Array(Buffer.from(screenshot.data, "base64")),
mimeType: screenshot.mimeType,
},
],
});
},
}),
);
}),
});
});
const PreviewStandardToolkitRegistrationLive = McpServer.toolkit(PreviewStandardToolkit).pipe(
Layer.provide(PreviewStandardToolkitHandlersLive),
);
const PreviewSnapshotRegistrationLive = Layer.effectDiscard(registerPreviewSnapshot()).pipe(
Layer.provide(PreviewSnapshotToolkitHandlersLive),
);
export const PreviewToolkitRegistrationLive = Layer.mergeAll(
PreviewStandardToolkitRegistrationLive,
PreviewSnapshotRegistrationLive,
);
const McpTransportLive = McpServer.layerHttp({
name: "T3 Code",
version: packageJson.version,
path: "/mcp",
}).pipe(Layer.provide(McpAuthMiddlewareLive));
export const layer = PreviewToolkitRegistrationLive.pipe(
Layer.provideMerge(McpTransportLive),
Layer.provide(PreviewAutomationBroker.layer),
);
@@ -0,0 +1,33 @@
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { PreviewAutomationUnavailableError } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
export type McpCapability = "preview";
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly providerSessionId: string;
readonly providerInstanceId: ProviderInstanceId;
readonly capabilities: ReadonlySet<McpCapability>;
readonly issuedAt: number;
readonly expiresAt: number;
}
export class McpInvocationContext extends Context.Service<
McpInvocationContext,
McpInvocationScope
>()("t3/mcp/McpInvocationContext") {}
export const requireMcpCapability = Effect.fn("mcp.requireCapability")(function* (
capability: McpCapability,
) {
const invocation = yield* McpInvocationContext;
if (!invocation.capabilities.has(capability)) {
return yield* new PreviewAutomationUnavailableError({
message: `MCP credential does not grant the ${capability} capability.`,
});
}
return invocation;
});
+28
View File
@@ -0,0 +1,28 @@
import type { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
export interface McpProviderSessionConfig {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly providerSessionId: string;
readonly providerInstanceId: ProviderInstanceId;
readonly endpoint: string;
readonly authorizationHeader: string;
}
const sessionsByThread = new Map<ThreadId, McpProviderSessionConfig>();
export function setMcpProviderSession(config: McpProviderSessionConfig): void {
sessionsByThread.set(config.threadId, config);
}
export function readMcpProviderSession(threadId: ThreadId): McpProviderSessionConfig | undefined {
return sessionsByThread.get(threadId);
}
export function clearMcpProviderSession(threadId: ThreadId): void {
sessionsByThread.delete(threadId);
}
export function clearAllMcpProviderSessions(): void {
sessionsByThread.clear();
}
@@ -0,0 +1,68 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { HttpServer } from "effect/unstable/http";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as McpSessionRegistry from "./McpSessionRegistry.ts";
const environmentId = EnvironmentId.make("environment-1");
const fakeHttpServer = HttpServer.HttpServer.of({
address: { _tag: "TcpAddress", hostname: "127.0.0.1", port: 43123 },
serve: (() => Effect.void) as HttpServer.HttpServer["Service"]["serve"],
});
const fakeEnvironment = ServerEnvironment.of({
getEnvironmentId: Effect.succeed(environmentId),
getDescriptor: Effect.die("unused"),
});
const makeRegistry = (now: () => number) =>
McpSessionRegistry.__testing
.make({
now,
idleTimeoutMs: 100,
maximumLifetimeMs: 1_000,
})
.pipe(
Effect.provideService(HttpServer.HttpServer, fakeHttpServer),
Effect.provideService(ServerEnvironment, fakeEnvironment),
Effect.provide(NodeServices.layer),
);
it.effect("stores only a token hash, resolves the bearer token, and revokes by thread", () =>
Effect.gen(function* () {
let timestamp = 1_000;
const registry = yield* makeRegistry(() => timestamp);
const threadId = ThreadId.make("thread-1");
const issued = yield* registry.issue({
threadId,
providerInstanceId: ProviderInstanceId.make("codex"),
});
expect(issued.config.endpoint).toBe("http://127.0.0.1:43123/mcp");
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
expect(token.length).toBeGreaterThan(20);
const resolved = yield* registry.resolve(token);
expect(resolved?.threadId).toBe(threadId);
yield* registry.revokeThread(threadId);
expect(yield* registry.resolve(token)).toBeUndefined();
timestamp += 2_000;
}),
);
it.effect("expires credentials after inactivity", () =>
Effect.gen(function* () {
let timestamp = 1_000;
const registry = yield* makeRegistry(() => timestamp);
const issued = yield* registry.issue({
threadId: ThreadId.make("thread-2"),
providerInstanceId: ProviderInstanceId.make("claude"),
});
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
timestamp += 101;
expect(yield* registry.resolve(token)).toBeUndefined();
}),
);
+207
View File
@@ -0,0 +1,207 @@
import { ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SynchronizedRef from "effect/SynchronizedRef";
import { HttpServer } from "effect/unstable/http";
import { ServerEnvironment } from "../environment/Services/ServerEnvironment.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpProviderSession from "./McpProviderSession.ts";
export interface McpCredentialRequest {
readonly threadId: ThreadId;
readonly providerInstanceId: ProviderInstanceId;
}
export interface McpIssuedCredential {
readonly config: McpProviderSession.McpProviderSessionConfig;
readonly expiresAt: number;
}
export interface McpSessionRegistryShape {
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
readonly resolve: (
rawToken: string,
) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
readonly revokeAll: Effect.Effect<void>;
}
export class McpSessionRegistry extends Context.Service<
McpSessionRegistry,
McpSessionRegistryShape
>()("t3/mcp/McpSessionRegistry") {}
interface CredentialRecord {
readonly tokenHash: string;
readonly scope: McpInvocationContext.McpInvocationScope;
readonly lastUsedAt: number;
}
interface RegistryState {
readonly records: ReadonlyMap<string, CredentialRecord>;
}
export interface McpSessionRegistryOptions {
readonly idleTimeoutMs?: number;
readonly maximumLifetimeMs?: number;
readonly now?: () => number;
}
const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1_000;
const DEFAULT_MAXIMUM_LIFETIME_MS = 8 * 60 * 60 * 1_000;
const bytesToHex = (bytes: Uint8Array): string =>
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
const tokenFromBytes = (bytes: Uint8Array): string => Buffer.from(bytes).toString("base64url");
const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
options: McpSessionRegistryOptions = {},
) {
const crypto = yield* Crypto.Crypto;
const environment = yield* ServerEnvironment;
const environmentId = yield* environment.getEnvironmentId;
const httpServer = yield* HttpServer.HttpServer;
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
const idleTimeoutMs = options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS;
const maximumLifetimeMs = options.maximumLifetimeMs ?? DEFAULT_MAXIMUM_LIFETIME_MS;
const endpoint =
httpServer.address._tag === "TcpAddress"
? `http://127.0.0.1:${httpServer.address.port}/mcp`
: "http://127.0.0.1/mcp";
const hashToken = (token: string) =>
crypto
.digest("SHA-256", new TextEncoder().encode(token))
.pipe(Effect.map(bytesToHex), Effect.orDie);
const pruneExpired = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
const next = new Map(
Array.from(records).filter(
([, record]) =>
timestamp <= record.scope.expiresAt && timestamp - record.lastUsedAt <= idleTimeoutMs,
),
);
return next.size === records.size ? records : next;
};
const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
function* (request) {
const issuedAt = yield* currentTimeMillis;
const providerSessionId = yield* crypto.randomUUIDv4.pipe(Effect.orDie);
const rawToken = yield* crypto.randomBytes(32).pipe(Effect.map(tokenFromBytes), Effect.orDie);
const tokenHash = yield* hashToken(rawToken);
const expiresAt = issuedAt + maximumLifetimeMs;
const scope: McpInvocationContext.McpInvocationScope = {
environmentId,
threadId: ThreadId.make(request.threadId),
providerSessionId,
providerInstanceId: ProviderInstanceId.make(request.providerInstanceId),
capabilities: new Set(["preview"]),
issuedAt,
expiresAt,
};
yield* SynchronizedRef.update(state, ({ records }) => {
const next = new Map(pruneExpired(records, issuedAt));
next.set(tokenHash, { tokenHash, scope, lastUsedAt: issuedAt });
return { records: next };
});
return {
config: {
environmentId,
threadId: scope.threadId,
providerSessionId,
providerInstanceId: scope.providerInstanceId,
endpoint,
authorizationHeader: `Bearer ${rawToken}`,
},
expiresAt,
};
},
);
const resolve: McpSessionRegistryShape["resolve"] = Effect.fn("McpSessionRegistry.resolve")(
function* (rawToken) {
if (rawToken.length === 0) return undefined;
const tokenHash = yield* hashToken(rawToken);
const timestamp = yield* currentTimeMillis;
return yield* SynchronizedRef.modify(state, ({ records }) => {
const current = pruneExpired(records, timestamp);
const record = current.get(tokenHash);
if (!record) return [undefined, { records: current }] as const;
const next = new Map(current);
next.set(tokenHash, { ...record, lastUsedAt: timestamp });
return [record.scope, { records: next }] as const;
});
},
);
const revokeWhere = (predicate: (record: CredentialRecord) => boolean) =>
SynchronizedRef.update(state, ({ records }) => ({
records: new Map(Array.from(records).filter(([, record]) => !predicate(record))),
}));
return McpSessionRegistry.of({
issue,
resolve,
revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
function* (providerSessionId) {
yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
},
),
revokeThread: Effect.fn("McpSessionRegistry.revokeThread")(function* (threadId) {
yield* revokeWhere((record) => record.scope.threadId === threadId);
}),
revokeAll: SynchronizedRef.set(state, { records: new Map() }),
});
});
let activeMcpSessionRegistry: McpSessionRegistryShape | undefined;
const make = Effect.acquireRelease(
makeWithOptions().pipe(
Effect.tap((registry) =>
Effect.sync(() => {
activeMcpSessionRegistry = registry;
}),
),
),
(registry) =>
Effect.sync(() => {
if (activeMcpSessionRegistry === registry) {
activeMcpSessionRegistry = undefined;
}
}),
);
export const layer: Layer.Layer<
McpSessionRegistry,
never,
Crypto.Crypto | ServerEnvironment | HttpServer.HttpServer
> = Layer.effect(McpSessionRegistry, make);
export const issueActiveMcpCredential = (
request: McpCredentialRequest,
): Effect.Effect<McpIssuedCredential | undefined> =>
activeMcpSessionRegistry
? activeMcpSessionRegistry
.revokeThread(request.threadId)
.pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
: Effect.sync((): McpIssuedCredential | undefined => undefined);
export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
export const revokeAllActiveMcpCredentials = (): Effect.Effect<void> =>
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeAll : Effect.void;
/** Exposed for tests. */
export const __testing = {
make: makeWithOptions,
};
@@ -0,0 +1,89 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
PreviewAutomationNoFocusedOwnerError,
ProviderInstanceId,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Stream from "effect/Stream";
import * as PreviewAutomationBroker from "./PreviewAutomationBroker.ts";
const scope = {
environmentId: EnvironmentId.make("environment-1"),
threadId: ThreadId.make("thread-1"),
providerSessionId: "provider-session-1",
providerInstanceId: ProviderInstanceId.make("codex"),
capabilities: new Set(["preview"] as const),
issuedAt: 1,
expiresAt: 2,
};
it.effect("routes a request to the focused owner and correlates its response", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect("client-1");
yield* Stream.runForEach(requests, (request) =>
broker.respond({
requestId: request.requestId,
ok: true,
result: { available: true },
}),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "client-1",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: null,
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
const result = yield* broker.invoke<{ available: boolean }>({
scope,
operation: "open",
input: {},
});
expect(result).toEqual({ available: true });
}),
),
);
it.effect("rejects calls when no focused owner exists", () =>
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const error = yield* broker
.invoke<void>({ scope, operation: "status", input: {} })
.pipe(Effect.flip);
expect(error).toBeInstanceOf(PreviewAutomationNoFocusedOwnerError);
}),
);
it.effect("routes interactive commands to a hidden durable browser host", () =>
Effect.scoped(
Effect.gen(function* () {
const broker = yield* PreviewAutomationBroker.__testing.make;
const requests = yield* broker.connect("client-hidden");
yield* Stream.runForEach(requests, (request) =>
broker.respond({ requestId: request.requestId, ok: true }),
).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* broker.reportOwner({
clientId: "client-hidden",
environmentId: scope.environmentId,
threadId: scope.threadId,
tabId: "tab-hidden",
visible: false,
supportsAutomation: true,
focusedAt: "2026-06-11T00:00:00.000Z",
});
yield* broker.invoke<void>({ scope, operation: "click", input: { x: 10, y: 10 } });
}),
),
);
@@ -0,0 +1,309 @@
import {
PreviewAutomationControlInterruptedError,
PreviewAutomationExecutionError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationNoFocusedOwnerError,
PreviewAutomationResultTooLargeError,
PreviewAutomationTabNotFoundError,
PreviewAutomationTimeoutError,
PreviewAutomationUnavailableError,
PreviewAutomationUnsupportedClientError,
type PreviewAutomationError,
type PreviewAutomationOperation,
type PreviewAutomationOwner,
type PreviewAutomationRequest,
type PreviewAutomationResponse,
type PreviewTabId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as McpInvocationContext from "./McpInvocationContext.ts";
export interface PreviewAutomationInvokeInput {
readonly scope: McpInvocationContext.McpInvocationScope;
readonly operation: PreviewAutomationOperation;
readonly input: unknown;
readonly tabId?: PreviewTabId;
readonly timeoutMs?: number;
}
export interface PreviewAutomationBrokerShape {
readonly connect: (clientId: string) => Effect.Effect<Stream.Stream<PreviewAutomationRequest>>;
readonly reportOwner: (
owner: PreviewAutomationOwner,
) => Effect.Effect<void, PreviewAutomationError>;
readonly clearOwner: (clientId: string) => Effect.Effect<void>;
readonly respond: (
response: PreviewAutomationResponse,
) => Effect.Effect<void, PreviewAutomationError>;
readonly invoke: <A = unknown>(
request: PreviewAutomationInvokeInput,
) => Effect.Effect<A, PreviewAutomationError>;
}
export class PreviewAutomationBroker extends Context.Service<
PreviewAutomationBroker,
PreviewAutomationBrokerShape
>()("t3/mcp/PreviewAutomationBroker") {}
interface ClientConnection {
readonly clientId: string;
readonly queue: Queue.Queue<
Parameters<PreviewAutomationBrokerShape["respond"]>[0] extends never
? never
: import("@t3tools/contracts").PreviewAutomationRequest
>;
}
interface PendingRequest {
readonly clientId: string;
readonly deferred: Deferred.Deferred<unknown, PreviewAutomationError>;
}
interface BrokerState {
readonly clients: ReadonlyMap<string, ClientConnection>;
readonly owners: ReadonlyMap<string, PreviewAutomationOwner>;
readonly pending: ReadonlyMap<string, PendingRequest>;
readonly requestSequence: number;
}
const makeResponseError = (
error: NonNullable<PreviewAutomationResponse["error"]>,
): PreviewAutomationError => {
switch (error._tag) {
case "PreviewAutomationNoFocusedOwnerError":
return new PreviewAutomationNoFocusedOwnerError({ message: error.message });
case "PreviewAutomationUnsupportedClientError":
return new PreviewAutomationUnsupportedClientError({ message: error.message });
case "PreviewAutomationTabNotFoundError":
return new PreviewAutomationTabNotFoundError({ message: error.message });
case "PreviewAutomationTimeoutError":
return new PreviewAutomationTimeoutError({ message: error.message });
case "PreviewAutomationControlInterruptedError":
return new PreviewAutomationControlInterruptedError({ message: error.message });
case "PreviewAutomationInvalidSelectorError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
return new PreviewAutomationInvalidSelectorError({
message: error.message,
selector:
detail && "selector" in detail && typeof detail.selector === "string"
? detail.selector
: "",
});
}
case "PreviewAutomationResultTooLargeError": {
const detail =
typeof error.detail === "object" && error.detail !== null ? error.detail : undefined;
return new PreviewAutomationResultTooLargeError({
message: error.message,
maximumBytes:
detail && "maximumBytes" in detail && typeof detail.maximumBytes === "number"
? detail.maximumBytes
: 64_000,
});
}
case "PreviewAutomationUnavailableError":
return new PreviewAutomationUnavailableError({ message: error.message });
default:
return new PreviewAutomationExecutionError({
message: error.message,
detail: error.detail,
});
}
};
const make = Effect.gen(function* PreviewAutomationBrokerMake() {
const state = yield* SynchronizedRef.make<BrokerState>({
clients: new Map(),
owners: new Map(),
pending: new Map(),
requestSequence: 0,
});
const disconnect = Effect.fn("PreviewAutomationBroker.disconnect")(function* (
clientId: string,
queue: ClientConnection["queue"],
) {
const toFail = yield* SynchronizedRef.modify(state, (current) => {
if (current.clients.get(clientId)?.queue !== queue) {
return [[] as ReadonlyArray<PendingRequest>, current] as const;
}
const clients = new Map(current.clients);
const owners = new Map(current.owners);
const pending = new Map(current.pending);
const disconnected: PendingRequest[] = [];
clients.delete(clientId);
owners.delete(clientId);
for (const [requestId, entry] of pending) {
if (entry.clientId === clientId) {
pending.delete(requestId);
disconnected.push(entry);
}
}
return [disconnected, { ...current, clients, owners, pending }] as const;
});
yield* Effect.forEach(
toFail,
({ deferred }) =>
Deferred.fail(
deferred,
new PreviewAutomationUnavailableError({
message: "The preview automation client disconnected.",
}),
),
{ discard: true },
);
yield* Queue.shutdown(queue);
});
const connect: PreviewAutomationBrokerShape["connect"] = Effect.fn(
"PreviewAutomationBroker.connect",
)(function* (clientId) {
const queue = yield* Queue.unbounded<import("@t3tools/contracts").PreviewAutomationRequest>();
const previous = yield* SynchronizedRef.modify(state, (current) => {
const clients = new Map(current.clients);
clients.set(clientId, { clientId, queue });
return [current.clients.get(clientId), { ...current, clients }] as const;
});
if (previous) yield* disconnect(clientId, previous.queue);
return Stream.fromQueue(queue).pipe(Stream.ensuring(disconnect(clientId, queue)));
});
const reportOwner: PreviewAutomationBrokerShape["reportOwner"] = Effect.fn(
"PreviewAutomationBroker.reportOwner",
)(function* (owner) {
yield* SynchronizedRef.update(state, (current) => {
const owners = new Map(current.owners);
owners.set(owner.clientId, owner);
return { ...current, owners };
});
});
const clearOwner: PreviewAutomationBrokerShape["clearOwner"] = Effect.fn(
"PreviewAutomationBroker.clearOwner",
)(function* (clientId) {
yield* SynchronizedRef.update(state, (current) => {
const owners = new Map(current.owners);
owners.delete(clientId);
return { ...current, owners };
});
});
const respond: PreviewAutomationBrokerShape["respond"] = Effect.fn(
"PreviewAutomationBroker.respond",
)(function* (response) {
const pending = yield* SynchronizedRef.modify(state, (current) => {
const entry = current.pending.get(response.requestId);
if (!entry) return [undefined, current] as const;
const next = new Map(current.pending);
next.delete(response.requestId);
return [entry, { ...current, pending: next }] as const;
});
if (!pending) return;
if (response.ok) {
yield* Deferred.succeed(pending.deferred, response.result);
} else {
yield* Deferred.fail(
pending.deferred,
response.error
? makeResponseError(response.error)
: new PreviewAutomationExecutionError({
message: "Preview automation failed without an error payload.",
}),
);
}
});
const invoke = Effect.fn("PreviewAutomationBroker.invoke")(function* <A = unknown>(
input: Parameters<PreviewAutomationBrokerShape["invoke"]>[0],
): Effect.fn.Return<A, PreviewAutomationError> {
const current = yield* SynchronizedRef.get(state);
const candidates = Array.from(current.owners.values())
.filter(
(owner) =>
owner.environmentId === input.scope.environmentId &&
owner.threadId === input.scope.threadId &&
owner.supportsAutomation,
)
.sort((left, right) => right.focusedAt.localeCompare(left.focusedAt));
const owner = candidates[0];
if (!owner) {
return yield* new PreviewAutomationNoFocusedOwnerError({
message: "No desktop browser host is available for this thread.",
});
}
const connection = current.clients.get(owner.clientId);
if (!connection) {
return yield* new PreviewAutomationUnavailableError({
message: "The browser host is not connected.",
});
}
if (
input.operation !== "open" &&
input.operation !== "status" &&
!owner.tabId &&
!input.tabId
) {
return yield* new PreviewAutomationTabNotFoundError({
message: "The browser host does not have an active tab.",
});
}
const timeoutMs = input.timeoutMs ?? 15_000;
const deferred = yield* Deferred.make<unknown, PreviewAutomationError>();
const requestId = yield* SynchronizedRef.modify(state, (next) => {
const requestId = `preview-${next.requestSequence}`;
const pending = new Map(next.pending);
pending.set(requestId, { clientId: owner.clientId, deferred });
return [requestId, { ...next, pending, requestSequence: next.requestSequence + 1 }] as const;
});
const removePending = SynchronizedRef.update(state, (next) => {
if (!next.pending.has(requestId)) return next;
const pending = new Map(next.pending);
pending.delete(requestId);
return { ...next, pending };
});
const awaitResponse = Effect.fn("PreviewAutomationBroker.awaitResponse")(function* () {
const offered = yield* Queue.offer(connection.queue, {
requestId,
threadId: input.scope.threadId,
tabId: input.tabId ?? owner.tabId ?? undefined,
operation: input.operation,
input: input.input,
timeoutMs,
});
if (!offered) {
return yield* new PreviewAutomationUnavailableError({
message: "The preview automation client is no longer accepting requests.",
});
}
const result = yield* Deferred.await(deferred).pipe(Effect.timeoutOption(timeoutMs));
return yield* Option.match(result, {
onNone: () =>
Effect.fail(
new PreviewAutomationTimeoutError({
message: `Preview automation timed out after ${timeoutMs}ms.`,
}),
),
onSome: (value) => Effect.succeed(value as A),
});
});
return yield* awaitResponse().pipe(Effect.ensuring(removePending));
});
return PreviewAutomationBroker.of({ connect, reportOwner, clearOwner, respond, invoke });
}).pipe(Effect.withSpan("PreviewAutomationBroker.make"));
export const layer = Layer.effect(PreviewAutomationBroker, make);
/** Exposed for tests. */
export const __testing = {
make,
};
@@ -0,0 +1,63 @@
import * as Effect from "effect/Effect";
import type {
PreviewAutomationOperation,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
import { PreviewSnapshotToolkit, PreviewStandardToolkit, PreviewToolkit } from "./tools.ts";
const invoke = Effect.fn("PreviewToolkit.invoke")(function* <A>(
operation: PreviewAutomationOperation,
input: unknown,
timeoutMs?: number,
): Effect.fn.Return<
A,
import("@t3tools/contracts").PreviewAutomationError,
McpInvocationContext.McpInvocationContext | PreviewAutomationBroker.PreviewAutomationBroker
> {
const scope = yield* McpInvocationContext.requireMcpCapability("preview");
const broker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
return yield* broker.invoke<A>({
scope,
operation,
input,
...(timeoutMs === undefined ? {} : { timeoutMs }),
});
});
const handlers = {
preview_status: () => invoke<PreviewAutomationStatus>("status", {}),
preview_open: (input) =>
invoke<PreviewAutomationStatus>("open", {
...input,
show: input.show ?? true,
reuseExistingTab: input.reuseExistingTab ?? true,
}),
preview_navigate: (input) => invoke<PreviewAutomationStatus>("navigate", input, input.timeoutMs),
preview_snapshot: () => invoke<PreviewAutomationSnapshot>("snapshot", {}),
preview_click: (input) => invoke<void>("click", input, input.timeoutMs).pipe(Effect.as(null)),
preview_type: (input) => invoke<void>("type", input, input.timeoutMs).pipe(Effect.as(null)),
preview_press: (input) => invoke<void>("press", input).pipe(Effect.as(null)),
preview_scroll: (input) => invoke<void>("scroll", input).pipe(Effect.as(null)),
preview_evaluate: (input) =>
invoke<unknown>("evaluate", input).pipe(Effect.map((result) => result ?? null)),
preview_wait_for: (input) =>
invoke<void>("waitFor", input, input.timeoutMs).pipe(Effect.as(null)),
preview_recording_start: () => invoke<PreviewAutomationRecordingStatus>("recordingStart", {}),
preview_recording_stop: () => invoke<PreviewAutomationRecordingArtifact>("recordingStop", {}),
} satisfies Parameters<typeof PreviewToolkit.toLayer>[0];
const { preview_snapshot, ...standardHandlers } = handlers;
export const PreviewStandardToolkitHandlersLive = PreviewStandardToolkit.toLayer(standardHandlers);
export const PreviewSnapshotToolkitHandlersLive = PreviewSnapshotToolkit.toLayer({
preview_snapshot,
});
export const PreviewToolkitHandlersLive = PreviewToolkit.toLayer(handlers);
@@ -0,0 +1,37 @@
import { expect, it } from "@effect/vitest";
import { Tool } from "effect/unstable/ai";
import { PreviewToolkit } from "./tools.ts";
const schemaHasDescription = (schema: unknown): boolean => {
if (!schema || typeof schema !== "object") return false;
const record = schema as Record<string, unknown>;
if (typeof record.description === "string" && record.description.length > 0) return true;
return [record.anyOf, record.oneOf, record.allOf]
.filter(Array.isArray)
.some((members) => members.some(schemaHasDescription));
};
it("exports provider-compatible object schemas with described parameters", () => {
for (const tool of Object.values(PreviewToolkit.tools)) {
const schema = Tool.getJsonSchema(tool) as {
readonly type?: unknown;
readonly properties?: Readonly<Record<string, unknown>>;
readonly anyOf?: unknown;
readonly oneOf?: unknown;
};
expect(
tool.description?.length ?? 0,
`${tool.name} should have a useful description`,
).toBeGreaterThan(40);
expect(schema.type, `${tool.name} must export a top-level object schema`).toBe("object");
expect(schema.anyOf, `${tool.name} must not export a root anyOf`).toBeUndefined();
expect(schema.oneOf, `${tool.name} must not export a root oneOf`).toBeUndefined();
for (const [field, fieldSchema] of Object.entries(schema.properties ?? {})) {
expect(
schemaHasDescription(fieldSchema),
`${tool.name}.${field} should explain what data the agent must pass`,
).toBe(true);
}
}
});
@@ -0,0 +1,196 @@
import {
PreviewAutomationClickInput,
PreviewAutomationError,
PreviewAutomationEvaluateInput,
PreviewAutomationNavigateInput,
PreviewAutomationOpenInput,
PreviewAutomationPressInput,
PreviewAutomationRecordingArtifact,
PreviewAutomationRecordingStatus,
PreviewAutomationScrollInput,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/unstable/ai";
import * as McpInvocationContext from "../../McpInvocationContext.ts";
import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
const dependencies = [
McpInvocationContext.McpInvocationContext,
PreviewAutomationBroker.PreviewAutomationBroker,
];
const browserTool = <T extends Tool.Any>(tool: T): T =>
tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
const safeBrowserTool = <T extends Tool.Any>(tool: T): T =>
browserTool(tool).annotate(Tool.Destructive, false) as T;
const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;
export const PreviewStatusTool = Tool.make("preview_status", {
description:
"Report whether the scoped thread has an automation-capable desktop preview, including its active tab, URL, title, visibility, and loading state.",
success: PreviewAutomationStatus,
failure: PreviewAutomationError,
dependencies,
})
.annotate(Tool.Title, "Get preview status")
.annotate(Tool.Readonly, true)
.annotate(Tool.Destructive, false)
.annotate(Tool.Idempotent, true);
export const PreviewOpenTool = browserTool(
Tool.make("preview_open", {
description:
"Show and initialize the browser preview for the scoped thread, optionally reusing its current tab and navigating to a URL.",
parameters: PreviewAutomationOpenInput,
success: PreviewAutomationStatus,
failure: PreviewAutomationError,
dependencies,
})
.annotate(Tool.Title, "Open browser preview")
.annotate(Tool.Destructive, false),
);
export const PreviewNavigateTool = safeBrowserTool(
Tool.make("preview_navigate", {
description:
"Navigate the active collaborative browser tab. Pass {url:'https://t3.chat'} for a website, or {target:{kind:'environment-port',port:5173}} for a dev server in the current environment. Exactly one of url or target is required. Defaults to waiting for page loading to stop.",
parameters: PreviewAutomationNavigateInput,
success: PreviewAutomationStatus,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Navigate browser preview"),
);
export const PreviewSnapshotTool = readonlyBrowserTool(
Tool.make("preview_snapshot", {
description:
"Inspect the current page before interacting. Returns URL/title/loading state, visible text, semantic interactive elements with reusable selectors and coordinates, accessibility data, recent console/network failures, action history, and a PNG screenshot.",
success: PreviewAutomationSnapshot,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Inspect browser page"),
);
export const PreviewClickTool = browserTool(
Tool.make("preview_click", {
description:
"Click exactly one page target. Prefer locator with a Playwright selector such as role=button[name='Send']; selector accepts legacy CSS; x and y are viewport CSS pixels and must be supplied together. Call preview_snapshot first when the target is unknown.",
parameters: PreviewAutomationClickInput,
success: Schema.Null,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Click preview page"),
);
export const PreviewTypeTool = browserTool(
Tool.make("preview_type", {
description:
"Insert literal text into one input. Prefer locator with a Playwright role/text selector; selector accepts legacy CSS. If neither is supplied, types into the currently focused element. Set clear=true to replace existing text.",
parameters: PreviewAutomationTypeInput,
success: Schema.Null,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Type into preview page"),
);
export const PreviewPressTool = browserTool(
Tool.make("preview_press", {
description:
"Press one keyboard key in the active page, for example {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}. This targets the page's current focus.",
parameters: PreviewAutomationPressInput,
success: Schema.Null,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Press key in preview page"),
);
export const PreviewScrollTool = safeBrowserTool(
Tool.make("preview_scroll", {
description:
"Scroll by CSS pixels. Positive deltaY scrolls down and positive deltaX scrolls right. Without locator/selector it scrolls the viewport; otherwise it scrolls that container. At least one delta is required.",
parameters: PreviewAutomationScrollInput,
success: Schema.Null,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Scroll preview page"),
);
export const PreviewEvaluateTool = browserTool(
Tool.make("preview_evaluate", {
description:
"Evaluate a JavaScript expression in the page's main frame and return a serializable result up to 64 KB. Prefer preview_snapshot and semantic click/type/wait tools; use this for inspection or interactions those tools cannot express. The expression may mutate page state.",
parameters: PreviewAutomationEvaluateInput,
success: Schema.Unknown,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Evaluate JavaScript in preview"),
);
export const PreviewWaitForTool = readonlyBrowserTool(
Tool.make("preview_wait_for", {
description:
"Wait until all supplied conditions match: a Playwright locator, legacy CSS selector, visible-text substring, and/or URL substring. Provide at least one condition. Defaults to 15 seconds, maximum 60 seconds.",
parameters: PreviewAutomationWaitForInput,
success: Schema.Null,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Wait for preview page condition"),
);
export const PreviewRecordingStartTool = safeBrowserTool(
Tool.make("preview_recording_start", {
description:
"Start recording the active collaborative browser tab while keeping it interactive for both agent and human use.",
success: PreviewAutomationRecordingStatus,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Start browser recording"),
);
export const PreviewRecordingStopTool = safeBrowserTool(
Tool.make("preview_recording_stop", {
description: "Stop the active browser recording and save it as a local evidence artifact.",
success: PreviewAutomationRecordingArtifact,
failure: PreviewAutomationError,
dependencies,
}).annotate(Tool.Title, "Stop browser recording"),
);
export const PreviewToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewSnapshotTool,
PreviewClickTool,
PreviewTypeTool,
PreviewPressTool,
PreviewScrollTool,
PreviewEvaluateTool,
PreviewWaitForTool,
PreviewRecordingStartTool,
PreviewRecordingStopTool,
);
export const PreviewStandardToolkit = Toolkit.make(
PreviewStatusTool,
PreviewOpenTool,
PreviewNavigateTool,
PreviewClickTool,
PreviewTypeTool,
PreviewPressTool,
PreviewScrollTool,
PreviewEvaluateTool,
PreviewWaitForTool,
PreviewRecordingStartTool,
PreviewRecordingStopTool,
);
export const PreviewSnapshotToolkit = Toolkit.make(PreviewSnapshotTool);
@@ -1,3 +1,4 @@
import { httpHeaderRedactionLayer } from "@t3tools/shared/httpObservability";
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -18,6 +19,7 @@ export const ObservabilityLive = Layer.unwrap(
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
httpHeaderRedactionLayer,
);
const tracerLayer = Layer.unwrap(
@@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-lifecycle");
const turnId = TurnId.make("turn-lifecycle-1");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-tl1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-tl1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-lifecycle"),
title: "Turn lifecycle",
modelSelection: {
instanceId: ProviderInstanceId.make("claude"),
model: "claude-opus",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl2"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:01.000Z",
commandId: CommandId.make("cmd-tl2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl2"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt: "2026-01-01T00:00:01.000Z",
},
},
});
// Interim assistant message completes mid-turn (commentary between
// tool calls) — the turn must stay running and unsettled.
yield* eventStore.append({
type: "thread.message-sent",
eventId: EventId.make("evt-tl3"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:00:05.000Z",
commandId: CommandId.make("cmd-tl3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl3"),
metadata: {},
payload: {
threadId,
messageId: MessageId.make("message-tl-interim"),
role: "assistant",
text: "interim commentary",
turnId,
streaming: false,
createdAt: "2026-01-01T00:00:05.000Z",
updatedAt: "2026-01-01T00:00:05.000Z",
},
});
yield* projectionPipeline.bootstrap;
const runningRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
// The session leaving "running" is the turn-end signal.
yield* eventStore.append({
type: "thread.session-set",
eventId: EventId.make("evt-tl4"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: "2026-01-01T00:01:00.000Z",
commandId: CommandId.make("cmd-tl4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-tl4"),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "ready",
providerName: "claude",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: "2026-01-01T00:01:00.000Z",
},
},
});
yield* projectionPipeline.bootstrap;
const settledRows = yield* sql<{
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
`;
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
}),
);
it.effect("settles a superseded running turn when a new turn becomes active", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("thread-turn-supersede");
const oldTurnId = TurnId.make("turn-superseded");
const newTurnId = TurnId.make("turn-steer");
yield* eventStore.append({
type: "thread.created",
eventId: EventId.make("evt-ts1"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: now,
commandId: CommandId.make("cmd-ts1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-ts1"),
metadata: {},
payload: {
threadId,
projectId: ProjectId.make("project-turn-supersede"),
title: "Turn supersede",
modelSelection: {
instanceId: ProviderInstanceId.make("opencode"),
model: "big-pickle",
},
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
});
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
eventStore.append({
type: "thread.session-set",
eventId: EventId.make(eventId),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: updatedAt,
commandId: CommandId.make(`cmd-${eventId}`),
causationEventId: null,
correlationId: CorrelationId.make(`cmd-${eventId}`),
metadata: {},
payload: {
threadId,
session: {
threadId,
status: "running",
providerName: "opencode",
runtimeMode: "full-access",
activeTurnId: turnId,
lastError: null,
updatedAt,
},
},
});
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
// A steer: a new turn becomes active without the provider ever
// completing the previous one.
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
yield* projectionPipeline.bootstrap;
const rows = yield* sql<{
readonly turnId: string;
readonly state: string;
readonly completedAt: string | null;
}>`
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
ORDER BY requested_at
`;
assert.deepEqual(rows, [
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
{ turnId: newTurnId, state: "running", completedAt: null },
]);
}),
);
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -1656,6 +1877,142 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
}),
);
it.effect("clears stale pending user input from projected shell summaries", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "project.created",
eventId: EventId.make("evt-stale-user-input-1"),
aggregateKind: "project",
aggregateId: ProjectId.make("project-stale-user-input"),
occurredAt: "2026-02-26T12:35:00.000Z",
commandId: CommandId.make("cmd-stale-user-input-1"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-1"),
metadata: {},
payload: {
projectId: ProjectId.make("project-stale-user-input"),
title: "Project Stale User Input",
workspaceRoot: "/tmp/project-stale-user-input",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-02-26T12:35:00.000Z",
updatedAt: "2026-02-26T12:35:00.000Z",
},
});
yield* appendAndProject({
type: "thread.created",
eventId: EventId.make("evt-stale-user-input-2"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:01.000Z",
commandId: CommandId.make("cmd-stale-user-input-2"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-2"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
projectId: ProjectId.make("project-stale-user-input"),
title: "Thread Stale User Input",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
runtimeMode: "approval-required",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-26T12:35:01.000Z",
updatedAt: "2026-02-26T12:35:01.000Z",
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-3"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:02.000Z",
commandId: CommandId.make("cmd-stale-user-input-3"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-stale-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: "2026-02-26T12:35:02.000Z",
},
},
});
yield* appendAndProject({
type: "thread.activity-appended",
eventId: EventId.make("evt-stale-user-input-4"),
aggregateKind: "thread",
aggregateId: ThreadId.make("thread-stale-user-input"),
occurredAt: "2026-02-26T12:35:03.000Z",
commandId: CommandId.make("cmd-stale-user-input-4"),
causationEventId: null,
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
metadata: {},
payload: {
threadId: ThreadId.make("thread-stale-user-input"),
activity: {
id: EventId.make("activity-stale-user-input-failed"),
tone: "error",
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
payload: {
requestId: "user-input-request-stale-1",
detail:
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
},
turnId: null,
createdAt: "2026-02-26T12:35:03.000Z",
},
},
});
const threadRows = yield* sql<{
readonly pendingUserInputCount: number;
}>`
SELECT pending_user_input_count AS "pendingUserInputCount"
FROM projection_threads
WHERE thread_id = 'thread-stale-user-input'
`;
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
}),
);
it.effect("ignores non-stale provider approval response failures", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
@@ -2,6 +2,7 @@ import {
ApprovalRequestId,
type ChatAttachment,
type OrchestrationEvent,
type OrchestrationSessionStatus,
ThreadId,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
@@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
type ProjectorName =
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
/**
* Turn state to settle still-running turns with when their session leaves the
* "running" status, or null while the session is (re)starting or running and
* turns must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSessionStatus,
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
interface ProjectorDefinition {
readonly name: ProjectorName;
readonly apply: (
@@ -141,7 +165,9 @@ function derivePendingUserInputCountFromActivities(
activity.kind === "provider.user-input.respond.failed" &&
detail !== null &&
(detail.includes("stale pending user-input request") ||
detail.includes("unknown pending user-input request"))
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request"))
) {
openRequestIds.delete(requestId);
}
@@ -999,9 +1025,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.session-set": {
const turnId = event.payload.session.activeTurnId;
if (turnId === null || event.payload.session.status !== "running") {
// Leaving the "running" session status is the turn-end signal:
// settle still-running turns so their duration reflects the whole
// turn rather than the last assistant message.
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
if (settledTurnState === null) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
return;
}
// A new active turn supersedes any still-running turn on the same
// thread — steering can open a new turn without the provider ever
// completing the previous one.
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(
otherRunningTurns.filter(
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
),
(turn) =>
turn.turnId === null
? Effect.void
: projectionTurnRepository.upsertByTurnId({
...turn,
turnId: turn.turnId,
state: "completed",
completedAt: event.payload.session.updatedAt,
}),
{ concurrency: 1 },
);
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId,
@@ -1080,6 +1154,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
if (event.payload.turnId === null || event.payload.role !== "assistant") {
return;
}
// A completed assistant message only settles the turn once the
// session is no longer running it — providers may emit several
// assistant messages per turn (commentary between tool calls), and
// the turn must stay unsettled until the provider reports turn end
// (projected as thread.session-set leaving the "running" status).
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const settlesTurn = !event.payload.streaming && !turnStillRunning;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1088,16 +1175,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming
? existingTurn.value.state
: existingTurn.value.state === "interrupted"
state: settlesTurn
? existingTurn.value.state === "interrupted"
? "interrupted"
: existingTurn.value.state === "error"
? "error"
: "completed",
completedAt: event.payload.streaming
? existingTurn.value.completedAt
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
: "completed"
: existingTurn.value.state,
completedAt: settlesTurn
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
: existingTurn.value.completedAt,
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
});
@@ -1110,10 +1197,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.messageId,
state: event.payload.streaming ? "running" : "completed",
state: settlesTurn ? "completed" : "running",
requestedAt: event.payload.createdAt,
startedAt: event.payload.createdAt,
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
completedAt: settlesTurn ? event.payload.updatedAt : null,
checkpointTurnCount: null,
checkpointRef: null,
checkpointStatus: null,
@@ -1160,6 +1247,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
case "thread.turn-diff-completed": {
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const session = yield* projectionThreadSessionRepository.getByThreadId({
threadId: event.payload.threadId,
});
const turnStillRunning =
Option.isSome(session) &&
session.value.status === "running" &&
session.value.activeTurnId === event.payload.turnId;
const existingTurn = yield* projectionTurnRepository.getByTurnId({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
@@ -1175,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? existingTurn.value.state : nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
@@ -1193,7 +1289,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
sourceProposedPlanThreadId: null,
sourceProposedPlanId: null,
assistantMessageId: event.payload.assistantMessageId,
state: nextState,
state: turnStillRunning ? "running" : nextState,
requestedAt: event.payload.completedAt,
startedAt: event.payload.completedAt,
completedAt: event.payload.completedAt,
@@ -28,6 +28,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { it as effectIt } from "@effect/vitest";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
@@ -40,6 +41,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../../provider/Services/ProviderService.ts";
import { makeProviderRegistryLayer } from "../../provider/testUtils/providerRegistryMock.ts";
import { TextGeneration, type TextGenerationShape } from "../../textGeneration/TextGeneration.ts";
import { RepositoryIdentityResolverLive } from "../../project/Layers/RepositoryIdentityResolver.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
@@ -142,6 +144,7 @@ describe("ProviderCommandReactor", () => {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
readonly sessionModelSwitch?: "unsupported" | "in-session";
readonly requiresNewThreadForModelChange?: boolean;
}) {
const now = "2026-01-01T00:00:00.000Z";
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
@@ -280,6 +283,14 @@ describe("ProviderCommandReactor", () => {
}),
),
);
const providerSnapshots = [
{
instanceId: modelSelection.instanceId,
...(input?.requiresNewThreadForModelChange === true
? { requiresNewThreadForModelChange: true }
: {}),
},
];
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
const service: ProviderServiceShape = {
@@ -335,6 +346,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
Layer.provideMerge(Layer.succeed(ProviderService, service)),
Layer.provideMerge(makeProviderRegistryLayer(providerSnapshots as never)),
Layer.provideMerge(
Layer.mock(GitWorkflowService)({
renameBranch,
@@ -879,6 +891,80 @@ describe("ProviderCommandReactor", () => {
});
});
effectIt.effect(
"rejects changing models after start when the provider requires a new thread",
() =>
Effect.gen(function* () {
const harness = yield* Effect.promise(() =>
createHarness({ requiresNewThreadForModelChange: true }),
);
const now = "2026-01-01T00:00:00.000Z";
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-1"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-1"),
role: "user",
text: "first",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1));
yield* harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-restricted-2"),
threadId: ThreadId.make("thread-1"),
message: {
messageId: asMessageId("user-message-restricted-2"),
role: "user",
text: "second",
attachments: [],
},
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5.1-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
});
yield* Effect.promise(() =>
waitFor(async () => {
const readModel = await harness.readModel();
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.make("thread-1"),
);
return (
thread?.activities.some(
(activity) => activity.kind === "provider.turn.start.failed",
) ?? false
);
}),
);
expect(harness.sendTurn).toHaveBeenCalledTimes(1);
const readModel = yield* Effect.promise(() => harness.readModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining(
"cannot switch models after the conversation has started",
),
},
});
}),
);
it("starts a first turn on the requested provider instance even when it differs from the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
@@ -1857,7 +1943,7 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
const harness = await createHarness();
const now = "2026-01-01T00:00:00.000Z";
harness.respondToUserInput.mockImplementation(() =>
@@ -1865,7 +1951,7 @@ describe("ProviderCommandReactor", () => {
new ProviderAdapterRequestError({
provider: ProviderDriverKind.make("claudeAgent"),
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
detail: "Unknown pending Codex user input request: user-input-request-1",
}),
),
);
@@ -31,6 +31,7 @@ import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import type { ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../textGeneration/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProviderRegistry } from "../../provider/Services/ProviderRegistry.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
@@ -140,9 +141,19 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = findProviderAdapterRequestError(cause);
if (error) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
const detail = error.detail.toLowerCase();
return (
detail.includes("unknown pending user-input request") ||
detail.includes("unknown pending user input request") ||
detail.includes("unknown pending codex user input request")
);
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
const message = Cause.pretty(cause).toLowerCase();
return (
message.includes("unknown pending user-input request") ||
message.includes("unknown pending user input request") ||
message.includes("unknown pending codex user input request")
);
}
function stalePendingRequestDetail(
@@ -180,6 +191,7 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const providerService = yield* ProviderService;
const providerRegistry = yield* ProviderRegistry;
const gitWorkflow = yield* GitWorkflowService;
const vcsStatusBroadcaster = yield* VcsStatusBroadcaster;
const textGeneration = yield* TextGeneration;
@@ -305,6 +317,38 @@ const make = Effect.gen(function* () {
.pipe(Effect.map(Option.getOrUndefined));
});
const rejectStartedThreadModelChangeIfRequired = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly currentModelSelection: ModelSelection;
readonly requestedModelSelection: ModelSelection | undefined;
}) {
const requestedModelSelection = input.requestedModelSelection;
if (
requestedModelSelection === undefined ||
(input.currentModelSelection.instanceId === requestedModelSelection.instanceId &&
input.currentModelSelection.model === requestedModelSelection.model)
) {
return;
}
const providers = yield* providerRegistry.getProviders;
const requiresNewThread =
providers.find((snapshot) => snapshot.instanceId === input.currentModelSelection.instanceId)
?.requiresNewThreadForModelChange === true ||
providers.find((snapshot) => snapshot.instanceId === requestedModelSelection.instanceId)
?.requiresNewThreadForModelChange === true;
if (!requiresNewThread) {
return;
}
return yield* new ProviderAdapterRequestError({
provider: providerErrorLabelFromInstanceHint({
instanceId: String(requestedModelSelection.instanceId),
modelSelectionInstanceId: String(input.currentModelSelection.instanceId),
}),
method: "thread.turn.start",
detail: `Thread '${input.threadId}' cannot switch models after the conversation has started. Start a new thread to use '${requestedModelSelection.model}'.`,
});
});
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
threadId: ThreadId,
createdAt: string,
@@ -384,6 +428,20 @@ const make = Effect.gen(function* () {
});
}
const preferredProvider: ProviderDriverKind = desiredDriverKind;
if (thread.session !== null) {
yield* rejectStartedThreadModelChangeIfRequired({
threadId,
currentModelSelection:
activeSession?.model !== undefined
? {
...thread.modelSelection,
instanceId: currentInstanceId,
model: activeSession.model,
}
: thread.modelSelection,
requestedModelSelection,
});
}
if (
thread.session !== null &&
requestedModelSelection !== undefined &&
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
Effect.andThen(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
instanceId: ProviderInstanceId.make("codex"),
model: "gpt-5-codex",
},
interactionMode: "plan",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
branch: null,
worktreePath: null,
createdAt,
}),
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.make("cmd-session-set-plan-source-guarded"),
threadId: sourceThreadId,
session: {
threadId: sourceThreadId,
status: "ready",
providerName: "codex",
runtimeMode: "approval-required",
activeTurnId: null,
updatedAt: createdAt,
lastError: null,
},
createdAt,
}),
),
);
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
@@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => {
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
});
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
// Steering a running turn: the server requests a new turn while the old
// one is still active, and providers like opencode open the new turn
// without ever completing the superseded one. The new turn.started must
// replace the active turn instead of being rejected as stale.
const harness = await createHarness();
const threadId = asThreadId("thread-1");
const oldTurnId = asTurnId("turn-steered-over");
const newTurnId = asTurnId("turn-from-steer");
const createdAt = "2026-01-01T00:00:00.000Z";
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: oldTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-steered-over"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: oldTurnId,
});
await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
2_000,
threadId,
);
// The steer: a user-requested turn start while the old turn still runs.
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-turn-start-steer"),
threadId,
message: {
messageId: asMessageId("msg-steer"),
role: "user",
text: "actually, do 15 instead",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt,
}),
);
// The provider session tracks the new turn before emitting turn.started
// (sendTurn updates the session first).
harness.setProviderSession({
provider: ProviderDriverKind.make("codex"),
status: "running",
runtimeMode: "approval-required",
threadId,
createdAt,
updatedAt: createdAt,
activeTurnId: newTurnId,
});
harness.emit({
type: "turn.started",
eventId: asEventId("evt-turn-started-from-steer"),
provider: ProviderDriverKind.make("codex"),
createdAt,
threadId,
turnId: newTurnId,
});
const threadAfterSteer = await waitForThread(
harness.readModel,
(thread) =>
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
2_000,
threadId,
);
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
expect(threadAfterSteer.latestTurn?.state).toBe("running");
});
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
const harness = await createHarness();
const sourceThreadId = asThreadId("thread-plan");
@@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () {
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
// A turn.started that conflicts with the active turn is legitimate when
// the server itself has a turn start pending for this thread AND the
// provider session already tracks the event's turn as its active turn:
// steering a running turn makes some providers (e.g. opencode) open a
// new turn without ever completing the superseded one. A stale
// turn.started for some other turn id still gets rejected.
const conflictingTurnStartIsPendingTurnStart =
event.type === "turn.started" && conflictsWithActiveTurn
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
Option.isSome(
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId: thread.id,
}),
)
: false;
const shouldApplyThreadLifecycle = (() => {
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
return true;
@@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () {
case "thread.started":
return true;
case "turn.started":
return !conflictsWithActiveTurn;
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
case "turn.completed":
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
return false;
+62 -23
View File
@@ -267,37 +267,76 @@ describe("orchestration projector", () => {
),
);
const afterRunning = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
session: {
const settledAt = "2026-02-23T08:01:00.000Z";
const [afterRunning, afterReady] = await Effect.runPromise(
Effect.flatMap(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: startedAt,
commandId: "cmd-running",
payload: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
session: {
threadId: "thread-1",
status: "running",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: "turn-1",
lastError: null,
updatedAt: startedAt,
},
},
},
}),
}),
),
(running) =>
Effect.map(
projectEvent(
running,
makeEvent({
sequence: 3,
type: "thread.session-set",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: settledAt,
commandId: "cmd-ready",
payload: {
threadId: "thread-1",
session: {
threadId: "thread-1",
status: "ready",
providerName: "codex",
providerSessionId: "session-1",
providerThreadId: "provider-thread-1",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: settledAt,
},
},
}),
),
(ready) => [running, ready] as const,
),
),
);
const thread = afterRunning.threads[0];
expect(thread?.latestTurn?.turnId).toBe("turn-1");
expect(thread?.session?.status).toBe("running");
// Leaving the "running" session status settles the running turn with the
// session timestamp as the turn end.
const settledThread = afterReady.threads[0];
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
expect(settledThread?.latestTurn?.state).toBe("completed");
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
});
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
+59 -15
View File
@@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
return "completed" as const;
}
/**
* Turn state to settle a still-running latest turn with when its session
* leaves the "running" status, or null while the session is (re)starting or
* running and the turn must stay unsettled.
*/
function settledTurnStateForSessionStatus(
status: OrchestrationSession["status"],
): "completed" | "interrupted" | "error" | null {
switch (status) {
case "idle":
case "ready":
return "completed";
case "error":
return "error";
case "interrupted":
case "stopped":
return "interrupted";
case "starting":
case "running":
return null;
}
}
function updateThread(
threads: ReadonlyArray<OrchestrationThread>,
threadId: ThreadId,
@@ -438,6 +461,9 @@ export function projectEvent(
"session",
);
// Leaving the "running" session status is the turn-end signal: settle
// a still-running latest turn so its duration reflects the whole turn.
const settledTurnState = settledTurnStateForSessionStatus(session.status);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
@@ -461,7 +487,18 @@ export function projectEvent(
? thread.latestTurn.assistantMessageId
: null,
}
: thread.latestTurn,
: thread.latestTurn !== null &&
thread.latestTurn.state === "running" &&
settledTurnState !== null
? {
...thread.latestTurn,
state: settledTurnState,
// A running turn's completedAt can only hold a mid-turn
// placeholder checkpoint timestamp — the session leaving
// "running" is the authoritative turn end.
completedAt: session.updatedAt,
}
: thread.latestTurn,
updatedAt: event.occurredAt,
}),
};
@@ -544,24 +581,31 @@ export function projectEvent(
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
.slice(-MAX_THREAD_CHECKPOINTS);
// Mid-turn diff updates produce placeholder checkpoints; record the
// checkpoint, but don't settle a turn its session is still running.
const turnStillRunning =
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
checkpoints,
latestTurn: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
latestTurn: turnStillRunning
? thread.latestTurn
: {
turnId: payload.turnId,
state: checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
: payload.completedAt,
startedAt:
thread.latestTurn?.turnId === payload.turnId
? (thread.latestTurn.startedAt ?? payload.completedAt)
: payload.completedAt,
completedAt: payload.completedAt,
assistantMessageId: payload.assistantMessageId,
},
updatedAt: event.occurredAt,
}),
};
+260
View File
@@ -0,0 +1,260 @@
import { it } from "@effect/vitest";
import { type PreviewEvent, ThreadId } from "@t3tools/contracts";
import { Effect, PubSub } from "effect";
import { expect } from "vite-plus/test";
import * as PreviewManager from "./Manager.ts";
const DRAIN_LIMIT = 100;
interface EventCollector {
/** Drain everything published since the last call (or since subscribe). */
readonly drain: Effect.Effect<ReadonlyArray<PreviewEvent>>;
}
/**
* Each `it.effect` shares the live PreviewManager layer across the whole
* `it.layer` block, so tests that assert per-thread counts must use a unique
* thread id to avoid bleeding state from earlier tests.
*/
let nextThreadId = 0;
const freshThreadId = () => ThreadId.make(`thread-${++nextThreadId}`);
/**
* Subscribe to the manager's event stream BEFORE the test publishes. We
* use `subscribeEvents` (synchronous PubSub.subscribe under the hood) so
* no event can land between subscribe and the consumer drain.
*/
const collectEvents = Effect.gen(function* () {
const manager = yield* PreviewManager.PreviewManager;
const subscription = yield* manager.subscribeEvents;
const collector: EventCollector = {
drain: PubSub.takeUpTo(subscription, DRAIN_LIMIT),
};
return collector;
}).pipe(Effect.withSpan("preview.test.collectEvents"));
it.layer(PreviewManager.layer)("PreviewManager", (it) => {
it.effect("opens a session and emits opened with normalized URL", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const snapshot = yield* manager.open({ threadId, url: "localhost:5173" });
expect(snapshot.tabId.startsWith("tab_")).toBe(true);
expect(snapshot.navStatus._tag).toBe("Loading");
if (snapshot.navStatus._tag === "Loading") {
expect(snapshot.navStatus.url).toBe("http://localhost:5173/");
}
const events = yield* collector.drain;
expect(events).toHaveLength(1);
expect(events[0]?.type).toBe("opened");
if (events[0]?.type === "opened") {
expect(events[0].tabId).toBe(snapshot.tabId);
}
}),
);
it.effect("opens an Idle tab when no URL is supplied", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const snapshot = yield* manager.open({ threadId });
expect(snapshot.navStatus._tag).toBe("Idle");
}),
);
it.effect("treats bare hosts as https", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const snapshot = yield* manager.open({ threadId, url: "example.com" });
if (snapshot.navStatus._tag === "Loading") {
expect(snapshot.navStatus.url).toBe("https://example.com/");
}
}),
);
it.effect("rejects empty URL with PreviewInvalidUrlError", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const error = yield* Effect.flip(manager.open({ threadId, url: " " }));
expect(error._tag).toBe("PreviewInvalidUrlError");
}),
);
it.effect("navigate updates snapshot and emits navigated", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
const snapshot = yield* manager.navigate({
threadId,
tabId: opened.tabId,
url: "http://localhost:5173/about",
resolvedTitle: "About",
});
expect(snapshot.navStatus._tag).toBe("Success");
if (snapshot.navStatus._tag === "Success") {
expect(snapshot.navStatus.url).toBe("http://localhost:5173/about");
expect(snapshot.navStatus.title).toBe("About");
}
const events = yield* collector.drain;
expect(events.map((e) => e.type)).toEqual(["opened", "navigated"]);
}),
);
it.effect("navigate fails for unknown tab", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const error = yield* Effect.flip(
manager.navigate({
threadId,
tabId: "tab_missing",
url: "http://localhost:5173",
}),
);
expect(error._tag).toBe("PreviewSessionLookupError");
}),
);
it.effect("reportStatus emits failed for LoadFailed nav", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const opened = yield* manager.open({ threadId, url: "http://localhost:5173" });
yield* manager.reportStatus({
threadId,
tabId: opened.tabId,
navStatus: {
_tag: "LoadFailed",
url: "http://localhost:5173",
title: "",
code: -105,
description: "ERR_NAME_NOT_RESOLVED",
},
canGoBack: false,
canGoForward: false,
});
const events = yield* collector.drain;
const failed = events.find((e) => e.type === "failed");
expect(failed?.type).toBe("failed");
if (failed?.type === "failed") {
expect(failed.code).toBe(-105);
expect(failed.description).toBe("ERR_NAME_NOT_RESOLVED");
}
}),
);
it.effect("close removes the session and emits closed", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
yield* manager.open({ threadId, url: "http://localhost:5173" });
yield* manager.close({ threadId });
const result = yield* manager.list({ threadId });
expect(result.sessions).toHaveLength(0);
const events = yield* collector.drain;
const closed = events.find((e) => e.type === "closed");
expect(closed?.type).toBe("closed");
}),
);
it.effect("close is idempotent for unknown threads", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
yield* manager.close({ threadId });
const result = yield* manager.list({ threadId });
expect(result.sessions).toHaveLength(0);
}),
);
it.effect("list returns every snapshot for the thread sorted by updatedAt", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const first = yield* manager.open({ threadId, url: "http://localhost:5173" });
const second = yield* manager.open({ threadId, url: "http://localhost:3000" });
const result = yield* manager.list({ threadId });
expect(result.sessions).toHaveLength(2);
const ids = result.sessions.map((s) => s.tabId);
expect(ids).toContain(first.tabId);
expect(ids).toContain(second.tabId);
}),
);
it.effect("open creates an independent tab on every call", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const collector = yield* collectEvents;
const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
const b = yield* manager.open({ threadId, url: "http://localhost:3000/path" });
expect(a.tabId).not.toBe(b.tabId);
const list = yield* manager.list({ threadId });
expect(list.sessions).toHaveLength(2);
const events = yield* collector.drain;
expect(events.map((e) => e.type)).toEqual(["opened", "opened"]);
}),
);
it.effect("close with mismatching tabId is a no-op", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
yield* manager.open({ threadId, url: "http://localhost:5173" });
yield* manager.close({ threadId, tabId: "tab_missing" });
const list = yield* manager.list({ threadId });
expect(list.sessions).toHaveLength(1);
}),
);
it.effect("close with explicit tabId removes only that tab", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const a = yield* manager.open({ threadId, url: "http://localhost:5173" });
const b = yield* manager.open({ threadId, url: "http://localhost:3000" });
yield* manager.close({ threadId, tabId: a.tabId });
const list = yield* manager.list({ threadId });
expect(list.sessions.map((s) => s.tabId)).toEqual([b.tabId]);
}),
);
it.effect("multiple subscribers receive every event independently", () =>
Effect.gen(function* () {
const threadId = freshThreadId();
const manager = yield* PreviewManager.PreviewManager;
const aSub = yield* manager.subscribeEvents;
const bSub = yield* manager.subscribeEvents;
yield* manager.open({ threadId, url: "http://localhost:5173" });
yield* manager.open({ threadId, url: "http://localhost:3000" });
const aEvents = yield* PubSub.takeUpTo(aSub, DRAIN_LIMIT);
const bEvents = yield* PubSub.takeUpTo(bSub, DRAIN_LIMIT);
expect(aEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
expect(bEvents.map((e) => e.type)).toEqual(["opened", "opened"]);
}),
);
});
+362
View File
@@ -0,0 +1,362 @@
/**
* In-memory PreviewManager implementation.
*
* Sessions are keyed by `(threadId, tabId)`; a single thread can host
* multiple tabs (browser-style). `open` always creates a new tab — tab
* lifecycle is owned by the renderer.
*
* Events are published via Effect's `PubSub`, so subscriber failures are
* isolated from the publishing call (a closed WS subscriber queue cannot
* fail an in-progress `navigate()`).
*/
import {
type PreviewCloseInput,
type PreviewEvent,
type PreviewError,
PreviewInvalidUrlError,
type PreviewListInput,
type PreviewListResult,
type PreviewNavigateInput,
type PreviewOpenInput,
type PreviewRefreshInput,
type PreviewReportStatusInput,
PreviewSessionLookupError,
type PreviewSessionSnapshot,
} from "@t3tools/contracts";
import {
newPreviewTabId,
normalizePreviewUrl,
PreviewUrlNormalizationError,
} from "@t3tools/shared/preview";
import {
Context,
DateTime,
Effect,
Layer,
PubSub,
type Scope,
Stream,
SynchronizedRef,
} from "effect";
export interface PreviewManagerShape {
readonly open: (input: PreviewOpenInput) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly navigate: (
input: PreviewNavigateInput,
) => Effect.Effect<PreviewSessionSnapshot, PreviewError>;
readonly reportStatus: (input: PreviewReportStatusInput) => Effect.Effect<void, PreviewError>;
readonly refresh: (input: PreviewRefreshInput) => Effect.Effect<void, PreviewError>;
readonly close: (input: PreviewCloseInput) => Effect.Effect<void, PreviewError>;
readonly list: (input: PreviewListInput) => Effect.Effect<PreviewListResult>;
readonly events: Stream.Stream<PreviewEvent>;
readonly subscribeEvents: Effect.Effect<PubSub.Subscription<PreviewEvent>, never, Scope.Scope>;
}
export class PreviewManager extends Context.Service<PreviewManager, PreviewManagerShape>()(
"t3/preview/Manager/PreviewManager",
) {}
interface PreviewSessionState {
readonly threadId: string;
readonly tabId: string;
readonly snapshot: PreviewSessionSnapshot;
}
interface ManagerState {
/** All sessions across every thread, keyed by `${threadId}\u0000${tabId}`. */
readonly sessions: ReadonlyMap<string, PreviewSessionState>;
}
const initialState: ManagerState = { sessions: new Map() };
const compositeKey = (threadId: string, tabId: string): string => `${threadId}\u0000${tabId}`;
const sessionsForThread = (
state: ManagerState,
threadId: string,
): ReadonlyArray<PreviewSessionState> => {
const out: PreviewSessionState[] = [];
for (const session of state.sessions.values()) {
if (session.threadId === threadId) out.push(session);
}
return out;
};
const normalizeUrl = (rawUrl: string): Effect.Effect<string, PreviewInvalidUrlError> =>
Effect.try({
try: () => normalizePreviewUrl(rawUrl),
catch: (cause) =>
new PreviewInvalidUrlError({
rawUrl,
detail:
cause instanceof PreviewUrlNormalizationError
? cause.detail
: cause instanceof Error
? cause.message
: String(cause),
}),
});
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
const buildLoadingSnapshot = (input: {
readonly threadId: string;
readonly tabId: string;
readonly url: string;
readonly title: string;
readonly updatedAt: string;
}): PreviewSessionSnapshot => ({
threadId: input.threadId,
tabId: input.tabId,
navStatus: { _tag: "Loading", url: input.url, title: input.title },
canGoBack: false,
canGoForward: false,
updatedAt: input.updatedAt,
});
const buildIdleSnapshot = (input: {
readonly threadId: string;
readonly tabId: string;
readonly updatedAt: string;
}): PreviewSessionSnapshot => ({
threadId: input.threadId,
tabId: input.tabId,
navStatus: { _tag: "Idle" },
canGoBack: false,
canGoForward: false,
updatedAt: input.updatedAt,
});
const make = Effect.gen(function* PreviewManagerMake() {
const stateRef = yield* SynchronizedRef.make<ManagerState>(initialState);
// Unbounded PubSub is fine here — events are tiny and we don't want to
// block publishers if a subscriber is slow. WS clients backpressure on
// their own queues downstream.
const eventsPubSub = yield* PubSub.unbounded<PreviewEvent>();
const events: Stream.Stream<PreviewEvent> = Stream.fromPubSub(eventsPubSub);
/**
* Atomic read-modify-write over the session for `(threadId, tabId)`. The
* mutator runs under the SynchronizedRef so concurrent writers cannot
* interleave. Lookup failures travel through the modify result so both
* branches yield the same `[A, S]` shape `modifyEffect` requires.
*
* The event is published INSIDE the lock so observers see events in the
* same order as the underlying state transitions. Publishing an unbounded
* PubSub is non-blocking, so this is cheap.
*/
const mutateExistingSession = <R, E>(
threadId: string,
tabId: string,
mutator: (
session: PreviewSessionState,
) => Effect.Effect<{ next: PreviewSessionState; emit: PreviewEvent | null; result: R }, E>,
): Effect.Effect<R, E | PreviewSessionLookupError> => {
type ModifyResult =
| { kind: "fail"; error: PreviewSessionLookupError }
| { kind: "ok"; result: R };
return SynchronizedRef.modifyEffect(stateRef, (state) => {
const session = state.sessions.get(compositeKey(threadId, tabId));
if (!session) {
return Effect.succeed([
{ kind: "fail", error: new PreviewSessionLookupError({ threadId, tabId }) },
state,
] as readonly [ModifyResult, ManagerState]);
}
return mutator(session).pipe(
Effect.flatMap(
Effect.fn("PreviewManager.commitMutation")(function* ({ next, emit, result }) {
if (emit) yield* PubSub.publish(eventsPubSub, emit);
const sessions = new Map(state.sessions);
sessions.set(compositeKey(threadId, tabId), next);
return [{ kind: "ok", result } as ModifyResult, { sessions }] as readonly [
ModifyResult,
ManagerState,
];
}),
),
);
}).pipe(
Effect.flatMap((modify) =>
modify.kind === "fail" ? Effect.fail(modify.error) : Effect.succeed(modify.result),
),
);
};
const open: PreviewManagerShape["open"] = Effect.fn("PreviewManager.open")(function* (input) {
const tabId = newPreviewTabId();
const updatedAt = yield* currentIsoTimestamp;
const snapshot = input.url
? buildLoadingSnapshot({
threadId: input.threadId,
tabId,
url: yield* normalizeUrl(input.url),
title: "",
updatedAt,
})
: buildIdleSnapshot({ threadId: input.threadId, tabId, updatedAt });
yield* SynchronizedRef.update(stateRef, (state) => {
const sessions = new Map(state.sessions);
sessions.set(compositeKey(input.threadId, tabId), {
threadId: input.threadId,
tabId,
snapshot,
});
return { sessions };
});
yield* PubSub.publish(eventsPubSub, {
type: "opened",
threadId: input.threadId,
tabId,
createdAt: snapshot.updatedAt,
snapshot,
});
return snapshot;
});
const navigate: PreviewManagerShape["navigate"] = Effect.fn("PreviewManager.navigate")(
function* (input) {
const url = yield* normalizeUrl(input.url);
return yield* mutateExistingSession(
input.threadId,
input.tabId,
Effect.fn("PreviewManager.navigateSession")(function* (session) {
const updatedAt = yield* currentIsoTimestamp;
const previousTitle =
session.snapshot.navStatus._tag === "Idle" ? "" : session.snapshot.navStatus.title;
const resolvedTitle = input.resolvedTitle ?? previousTitle;
const snapshot: PreviewSessionSnapshot = {
threadId: session.threadId,
tabId: session.tabId,
navStatus: { _tag: "Success", url, title: resolvedTitle },
canGoBack: session.snapshot.canGoBack,
canGoForward: session.snapshot.canGoForward,
updatedAt,
};
return {
next: { ...session, snapshot },
emit: {
type: "navigated",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
snapshot,
},
result: snapshot,
};
}),
);
},
);
const reportStatus: PreviewManagerShape["reportStatus"] = Effect.fn(
"PreviewManager.reportStatus",
)(function* (input) {
yield* mutateExistingSession(
input.threadId,
input.tabId,
Effect.fn("PreviewManager.reportSessionStatus")(function* (session) {
const updatedAt = yield* currentIsoTimestamp;
const snapshot: PreviewSessionSnapshot = {
threadId: session.threadId,
tabId: session.tabId,
navStatus: input.navStatus,
canGoBack: input.canGoBack,
canGoForward: input.canGoForward,
updatedAt,
};
const emit: PreviewEvent =
input.navStatus._tag === "LoadFailed"
? {
type: "failed",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
url: input.navStatus.url,
title: input.navStatus.title,
code: input.navStatus.code,
description: input.navStatus.description,
}
: {
type: "navigated",
threadId: session.threadId,
tabId: session.tabId,
createdAt: snapshot.updatedAt,
snapshot,
};
return {
next: { ...session, snapshot },
emit,
result: undefined as void,
};
}),
);
});
const refresh: PreviewManagerShape["refresh"] = Effect.fn("PreviewManager.refresh")(
function* (input) {
// Verify the session exists; the desktop bridge handles the actual reload
// and will report progress back via `reportStatus`. No event emitted.
yield* mutateExistingSession(input.threadId, input.tabId, (session) =>
Effect.succeed({ next: session, emit: null, result: undefined as void }),
);
},
);
const close: PreviewManagerShape["close"] = Effect.fn("PreviewManager.close")(function* (input) {
const createdAt = yield* currentIsoTimestamp;
const events = yield* SynchronizedRef.modify(stateRef, (state) => {
const eventsToEmit: PreviewEvent[] = [];
const sessions = new Map(state.sessions);
const targets = input.tabId
? [state.sessions.get(compositeKey(input.threadId, input.tabId))].filter(
(entry): entry is PreviewSessionState => entry !== undefined,
)
: sessionsForThread(state, input.threadId);
for (const target of targets) {
sessions.delete(compositeKey(target.threadId, target.tabId));
eventsToEmit.push({
type: "closed",
threadId: target.threadId,
tabId: target.tabId,
createdAt,
});
}
if (eventsToEmit.length === 0) {
return [eventsToEmit, state] as const;
}
return [eventsToEmit, { sessions }] as const;
});
if (events.length > 0) {
yield* Effect.forEach(events, (event) => PubSub.publish(eventsPubSub, event), {
discard: true,
});
}
});
const list: PreviewManagerShape["list"] = Effect.fn("PreviewManager.list")(function* (input) {
return yield* SynchronizedRef.get(stateRef).pipe(
Effect.map(
(state): PreviewListResult => ({
sessions: sessionsForThread(state, input.threadId)
.map((s) => s.snapshot)
.toSorted((a, b) => a.updatedAt.localeCompare(b.updatedAt)),
}),
),
);
});
return {
open,
navigate,
reportStatus,
refresh,
close,
list,
events,
subscribeEvents: PubSub.subscribe(eventsPubSub),
} satisfies PreviewManagerShape;
}).pipe(Effect.withSpan("PreviewManager.make"));
export const layer = Layer.effect(PreviewManager, make);
+263
View File
@@ -0,0 +1,263 @@
import * as net from "node:net";
import { assert, describe, it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Net from "@t3tools/shared/Net";
import { Effect, Layer } from "effect";
import { ProcessRunner, ProcessSpawnError } from "../processRunner.ts";
import * as PortScanner from "./PortScanner.ts";
const { parseLsofOutput, parsePortFromLsofName, parseWindowsListenerOutput, serversEqual } =
PortScanner.__testing;
const TestProcessRunner = Layer.succeed(ProcessRunner, {
run: (input) =>
Effect.fail(
new ProcessSpawnError({
command: input.command,
args: input.args,
cwd: input.cwd,
cause: "process command unavailable in fallback test",
}),
),
});
const TestPortDiscoveryLive = PortScanner.layer.pipe(
Layer.provide(
Layer.mergeAll(
TestProcessRunner,
Net.layer,
Layer.succeed(PortScanner.CurrentPlatform, "win32"),
),
),
);
const openServer = (port: number): Effect.Effect<net.Server | null> =>
Effect.callback((resume) => {
const server = net.createServer();
server.once("error", () => {
resume(Effect.succeed(null));
});
server.listen(port, "127.0.0.1", () => {
resume(Effect.succeed(server));
});
return Effect.sync(() => {
server.close();
});
});
const closeServer = (server: net.Server): Effect.Effect<void> =>
Effect.callback((resume) => {
server.close(() => resume(Effect.void));
});
const openCommonDevServer = Effect.fn("PortScannerTest.openCommonDevServer")(function* (
ports: ReadonlyArray<number>,
) {
for (const port of ports) {
const server = yield* openServer(port);
if (server !== null) return { port, server };
}
return yield* Effect.die(
new Error("No common development port was available for the preview scanner test"),
);
});
const commonDevServer = Effect.acquireRelease(
openCommonDevServer(PortScanner.COMMON_DEV_PORTS),
({ server }) => closeServer(server),
);
describe("parsePortFromLsofName", () => {
it("parses *:port", () => {
assert.equal(parsePortFromLsofName("*:5173"), 5173);
});
it("parses 127.0.0.1:port", () => {
assert.equal(parsePortFromLsofName("127.0.0.1:5173"), 5173);
});
it("parses localhost:port", () => {
assert.equal(parsePortFromLsofName("localhost:5173"), 5173);
});
it("parses [::1]:port", () => {
assert.equal(parsePortFromLsofName("[::1]:5173"), 5173);
});
it("ignores non-local hosts", () => {
assert.equal(parsePortFromLsofName("192.168.1.10:5173"), null);
});
it("strips trailing description", () => {
assert.equal(parsePortFromLsofName("*:5173 (LISTEN)"), 5173);
});
it("rejects garbage", () => {
assert.equal(parsePortFromLsofName(""), null);
assert.equal(parsePortFromLsofName("not-a-port"), null);
assert.equal(parsePortFromLsofName("*:0"), null);
assert.equal(parsePortFromLsofName("*:99999"), null);
});
});
describe("parseLsofOutput", () => {
it("parses a typical lsof -F pcn output", () => {
const sample = [
"p12345",
"cnode",
"n*:5173",
"p67890",
"cnext-server",
"n127.0.0.1:3000",
"n127.0.0.1:9229", // node debug port too — same process
"p13579",
"cChrome",
"n192.168.1.10:443", // not local — ignored
].join("\n");
const servers = parseLsofOutput(sample);
assert.deepStrictEqual(servers, [
{
host: "localhost",
port: 3000,
url: "http://localhost:3000",
processName: "next-server",
pid: 67890,
terminal: null,
},
{
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: null,
},
{
host: "localhost",
port: 9229,
url: "http://localhost:9229",
processName: "next-server",
pid: 67890,
terminal: null,
},
]);
});
it("handles empty input", () => {
assert.deepStrictEqual(parseLsofOutput(""), []);
});
it("dedupes by host:port", () => {
const sample = ["p1", "cnode", "n*:5173", "n127.0.0.1:5173"].join("\n");
const servers = parseLsofOutput(sample);
assert.equal(servers.length, 1);
assert.equal(servers[0]?.port, 5173);
});
it("attributes listeners to a registered terminal process", () => {
const servers = parseLsofOutput(
["p12345", "cnode", "n*:5173"].join("\n"),
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
assert.deepStrictEqual(servers[0]?.terminal, {
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
});
});
});
describe("serversEqual", () => {
const a = {
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 1,
terminal: null,
};
it("returns true for identical lists", () => {
assert.equal(serversEqual([a], [{ ...a }]), true);
});
it("returns false for different lengths", () => {
assert.equal(serversEqual([a], []), false);
});
it("returns false for different processName", () => {
assert.equal(serversEqual([a], [{ ...a, processName: "other" }]), false);
});
});
describe("parseWindowsListenerOutput", () => {
it("parses and attributes PowerShell listener records", () => {
const servers = parseWindowsListenerOutput(
"0.0.0.0|5173|12345|node",
new Map([
[
12345,
{
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
],
]),
);
assert.deepStrictEqual(servers, [
{
host: "localhost",
port: 5173,
url: "http://localhost:5173",
processName: "node",
pid: 12345,
terminal: {
threadId: ThreadId.make("thread-1"),
terminalId: "terminal-1",
},
},
]);
});
});
/**
* Integration tests against a real TCP listener. The test layer forces the
* Windows code path (TCP-probe fallback) so we don't depend on `lsof` being
* installed.
*/
it.layer(TestPortDiscoveryLive)("PortDiscovery integration (TCP probe fallback)", (it) => {
it.effect(
"scan() returns a server we just opened on a curated dev port",
Effect.fn("PortScannerTest.scanFindsCommonDevServer")(function* () {
const { port } = yield* commonDevServer;
const scanner = yield* PortScanner.PortDiscovery;
const result = yield* scanner.scan();
const found = result.find((server) => server.port === port);
assert.notEqual(found, undefined);
assert.equal(found?.host, "localhost");
}),
);
it.effect(
"retain drives an immediate broadcast to subscribers",
Effect.fn("PortScannerTest.retainBroadcastsImmediately")(function* () {
const { port } = yield* commonDevServer;
const received: number[] = [];
const scanner = yield* PortScanner.PortDiscovery;
yield* scanner.subscribe((servers) =>
Effect.sync(() => {
for (const server of servers) received.push(server.port);
}),
);
yield* scanner.retain;
assert.isTrue(received.includes(port));
}),
);
});
+377
View File
@@ -0,0 +1,377 @@
/**
* In-process PortScanner implementation.
*
* macOS/Linux: parses `lsof -iTCP -sTCP:LISTEN -P -n -F pcn` (-F output is a
* stable line-prefixed field format; this is the only `lsof` flag set we rely
* on).
*
* Windows / lsof missing: checks a curated list of common dev ports through
* the shared Net service.
*
* Polling is reference-counted via scoped `retain`. A single layer-scoped fiber
* polls forever, but each tick is a no-op when the retain count is zero.
*/
import { ThreadId, type DiscoveredLocalServer } from "@t3tools/contracts";
import * as Net from "@t3tools/shared/Net";
import { LSOF_LOCAL_HOST_TOKENS } from "@t3tools/shared/preview";
import { Cause, Context, Duration, Effect, Layer, Option, Ref, Schedule, Scope } from "effect";
import { ProcessRunner } from "../processRunner.ts";
export interface PortDiscoveryShape {
readonly scan: () => Effect.Effect<ReadonlyArray<DiscoveredLocalServer>>;
readonly subscribe: (
listener: (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>,
) => Effect.Effect<void, never, Scope.Scope>;
readonly retain: Effect.Effect<void, never, Scope.Scope>;
readonly registerTerminalProcesses: (input: {
readonly threadId: string;
readonly terminalId: string;
readonly processIds: ReadonlyArray<number>;
}) => Effect.Effect<void>;
readonly unregisterTerminal: (input: {
readonly threadId: string;
readonly terminalId: string;
}) => Effect.Effect<void>;
}
export class PortDiscovery extends Context.Service<PortDiscovery, PortDiscoveryShape>()(
"t3/preview/PortScanner/PortDiscovery",
) {}
export const CurrentPlatform = Context.Reference<NodeJS.Platform>(
"t3/preview/PortScanner/CurrentPlatform",
{
defaultValue: () => process.platform,
},
);
export const COMMON_DEV_PORTS: ReadonlyArray<number> = Object.freeze([
3000, 3001, 3333, 4173, 4200, 4321, 5000, 5173, 5174, 5175, 5500, 8000, 8080, 8081, 8888, 9000,
]);
const POLL_INTERVAL = Duration.seconds(3);
const LSOF_TIMEOUT = Duration.seconds(5);
const WINDOWS_LISTENER_TIMEOUT = Duration.seconds(5);
type Listener = (servers: ReadonlyArray<DiscoveredLocalServer>) => Effect.Effect<void>;
interface ScannerState {
readonly lastSnapshot: ReadonlyArray<DiscoveredLocalServer>;
readonly listeners: ReadonlySet<Listener>;
readonly terminalProcesses: ReadonlyMap<
string,
{
readonly owner: TerminalProcessOwner;
readonly processIds: ReadonlySet<number>;
}
>;
readonly retainCount: number;
}
interface TerminalProcessOwner {
readonly threadId: ThreadId;
readonly terminalId: string;
}
const terminalOwnerKey = (owner: {
readonly threadId: string;
readonly terminalId: string;
}): string => `${owner.threadId}\u0000${owner.terminalId}`;
const parseLsofOutput = (
raw: string,
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
): ReadonlyArray<DiscoveredLocalServer> => {
const seen = new Map<string, DiscoveredLocalServer>();
let pid: number | null = null;
let processName: string | null = null;
for (const line of raw.split("\n")) {
if (line.length === 0) continue;
const tag = line.charAt(0);
const value = line.slice(1);
if (tag === "p") {
const parsed = Number.parseInt(value, 10);
pid = Number.isFinite(parsed) && parsed > 0 ? parsed : null;
processName = null;
continue;
}
if (tag === "c") {
processName = value.trim() || null;
continue;
}
if (tag === "n") {
const portMatch = parsePortFromLsofName(value);
if (portMatch == null) continue;
const url = `http://localhost:${portMatch}`;
const key = `localhost:${portMatch}`;
if (seen.has(key)) continue;
seen.set(key, {
host: "localhost",
port: portMatch,
url,
processName,
pid,
terminal: pid === null ? null : (terminalByProcessId.get(pid) ?? null),
});
}
}
return Array.from(seen.values()).toSorted((a, b) => a.port - b.port);
};
const parsePortFromLsofName = (name: string): number | null => {
// Examples: "*:5173", "127.0.0.1:5173", "[::1]:5173", "localhost:5173",
// "192.168.1.10:5173 (LISTEN)" — we only care if the host part is local.
const trimmed = name.split(" ", 1)[0]?.trim() ?? "";
if (trimmed.length === 0) return null;
const lastColon = trimmed.lastIndexOf(":");
if (lastColon < 0) return null;
const hostPart = trimmed.slice(0, lastColon);
const portPart = trimmed.slice(lastColon + 1);
if (!LSOF_LOCAL_HOST_TOKENS.has(hostPart)) return null;
const port = Number.parseInt(portPart, 10);
if (!Number.isFinite(port) || port <= 0 || port >= 65536) return null;
return port;
};
const parseWindowsListenerOutput = (
raw: string,
terminalByProcessId: ReadonlyMap<number, TerminalProcessOwner> = new Map(),
): ReadonlyArray<DiscoveredLocalServer> => {
const seen = new Map<number, DiscoveredLocalServer>();
for (const line of raw.split(/\r?\n/g)) {
const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4);
const host = hostRaw?.trim() ?? "";
if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue;
const port = Number(portRaw);
const pid = Number(pidRaw);
if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue;
const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null;
if (seen.has(port)) continue;
seen.set(port, {
host: "localhost",
port,
url: `http://localhost:${port}`,
processName: processNameRaw?.trim() || null,
pid: normalizedPid,
terminal: normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null),
});
}
return [...seen.values()].toSorted((left, right) => left.port - right.port);
};
const serversEqual = (
left: ReadonlyArray<DiscoveredLocalServer>,
right: ReadonlyArray<DiscoveredLocalServer>,
): boolean => {
if (left.length !== right.length) return false;
for (let i = 0; i < left.length; i += 1) {
const a = left[i];
const b = right[i];
if (!a || !b) return false;
if (
a.host !== b.host ||
a.port !== b.port ||
a.url !== b.url ||
a.processName !== b.processName ||
a.pid !== b.pid ||
a.terminal?.threadId !== b.terminal?.threadId ||
a.terminal?.terminalId !== b.terminal?.terminalId
) {
return false;
}
}
return true;
};
const make = Effect.gen(function* PortDiscoveryMake() {
const net = yield* Net.NetService;
const processRunner = yield* ProcessRunner;
const platform = yield* CurrentPlatform;
const stateRef = yield* Ref.make<ScannerState>({
lastSnapshot: [],
listeners: new Set(),
terminalProcesses: new Map(),
retainCount: 0,
});
const probeCommonPorts = Effect.fn("PortDiscovery.probeCommonPorts")(function* () {
const results = yield* Effect.forEach(
COMMON_DEV_PORTS,
(port) =>
net.isPortAvailableOnLoopback(port).pipe(
Effect.map((available) => ({
port,
listening: !available,
})),
),
{ concurrency: "unbounded" },
);
return results
.filter((result) => result.listening)
.map<DiscoveredLocalServer>((result) => ({
host: "localhost",
port: result.port,
url: `http://localhost:${result.port}`,
processName: null,
pid: null,
terminal: null,
}));
});
const scanOnce = Effect.fn("PortDiscovery.scan")(function* () {
const state = yield* Ref.get(stateRef);
const terminalByProcessId = new Map<number, TerminalProcessOwner>();
for (const registration of state.terminalProcesses.values()) {
for (const processId of registration.processIds) {
terminalByProcessId.set(processId, registration.owner);
}
}
if (platform === "win32") {
const command =
'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }';
const listeners = yield* processRunner
.run({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: WINDOWS_LISTENER_TIMEOUT,
maxOutputBytes: 1024 * 1024,
outputMode: "truncate",
})
.pipe(
Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)),
Effect.option,
);
if (Option.isSome(listeners)) return listeners.value;
return yield* probeCommonPorts();
}
const lsofResult = yield* processRunner
.run({
command: "lsof",
args: ["-iTCP", "-sTCP:LISTEN", "-P", "-n", "-F", "pcn"],
timeout: LSOF_TIMEOUT,
maxOutputBytes: 1024 * 1024,
outputMode: "truncate",
})
.pipe(
Effect.map((result) => parseLsofOutput(result.stdout, terminalByProcessId)),
Effect.option,
);
if (Option.isSome(lsofResult)) return lsofResult.value;
return yield* probeCommonPorts();
});
const broadcast = Effect.fn("PortDiscovery.broadcast")(function* (
servers: ReadonlyArray<DiscoveredLocalServer>,
) {
const listeners = (yield* Ref.get(stateRef)).listeners;
yield* Effect.forEach(listeners, (listener) => listener(servers), { discard: true });
});
const pollTick = Effect.fn("PortDiscovery.pollTick")(
function* () {
if ((yield* Ref.get(stateRef)).retainCount <= 0) return;
const next = yield* scanOnce();
const changed = yield* Ref.modify(stateRef, (state) =>
serversEqual(state.lastSnapshot, next)
? [false, state]
: [true, { ...state, lastSnapshot: next }],
);
if (changed) yield* broadcast(next);
},
Effect.catchCause((cause: Cause.Cause<never>) =>
Effect.logWarning("preview port scan failed", Cause.pretty(cause)),
),
);
// Single layer-scoped polling fiber. Ticks are no-ops when no client is
// currently retained, so the cost is one Ref.get every POLL_INTERVAL.
yield* Effect.forkScoped(pollTick().pipe(Effect.repeat(Schedule.spaced(POLL_INTERVAL))));
const acquireRetention = Effect.fn("PortDiscovery.retain")(function* () {
const wasIdle = yield* Ref.modify(stateRef, (state) => [
state.retainCount === 0,
{ ...state, retainCount: state.retainCount + 1 },
]);
if (wasIdle) {
// Run an immediate scan + broadcast so the new retainer doesn't have
// to wait up to POLL_INTERVAL for the first emission.
yield* pollTick();
}
});
const retain: PortDiscoveryShape["retain"] = Effect.acquireRelease(acquireRetention(), () =>
Ref.update(stateRef, (state) => ({
...state,
retainCount: Math.max(0, state.retainCount - 1),
})),
);
const subscribe: PortDiscoveryShape["subscribe"] = Effect.fn("PortDiscovery.subscribe")(
(listener) =>
Effect.acquireRelease(
Ref.update(stateRef, (state) => ({
...state,
listeners: new Set([...state.listeners, listener]),
})),
() =>
Ref.update(stateRef, (state) => {
const listeners = new Set(state.listeners);
listeners.delete(listener);
return { ...state, listeners };
}),
),
);
const registerTerminalProcesses: PortDiscoveryShape["registerTerminalProcesses"] = Effect.fn(
"PortDiscovery.registerTerminalProcesses",
)(function* (input) {
const owner = {
threadId: ThreadId.make(input.threadId),
terminalId: input.terminalId,
};
const processIds = new Set(
input.processIds.filter((processId) => Number.isInteger(processId) && processId > 0),
);
yield* Ref.update(stateRef, (state) => {
const terminalProcesses = new Map(state.terminalProcesses);
const key = terminalOwnerKey(owner);
if (processIds.size === 0) {
terminalProcesses.delete(key);
} else {
terminalProcesses.set(key, { owner, processIds });
}
return { ...state, terminalProcesses };
});
});
const unregisterTerminal: PortDiscoveryShape["unregisterTerminal"] = Effect.fn(
"PortDiscovery.unregisterTerminal",
)(function* (input) {
yield* Ref.update(stateRef, (state) => {
const terminalProcesses = new Map(state.terminalProcesses);
terminalProcesses.delete(terminalOwnerKey(input));
return { ...state, terminalProcesses };
});
});
return PortDiscovery.of({
scan: scanOnce,
subscribe,
retain,
registerTerminalProcesses,
unregisterTerminal,
});
}).pipe(Effect.withSpan("PortDiscovery.make"));
export const layer = Layer.effect(PortDiscovery, make);
/** Exposed for tests. */
export const __testing = {
parseLsofOutput,
parsePortFromLsofName,
parseWindowsListenerOutput,
serversEqual,
};
@@ -7,9 +7,10 @@ import * as Path from "effect/Path";
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(ProjectFaviconResolverLive),
Layer.provideMerge(ProjectFaviconResolverLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(NodeServices.layer),
);
Loaded 100 of 416 files, more files were not shown because too many files have changed in this diff. Show more