TypeScript
chore: delete dead code, unused deps, and duplicate helpers (#9129)
Theo Browne08aad594f005
diff --git a/apps/desktop/src/preview/PickLabelPosition.ts b/apps/desktop/src/preview/PickLabelPosition.tsdeleted file mode 100644index cf7f3c811f8..00000000000--- a/apps/desktop/src/preview/PickLabelPosition.ts+++ /dev/null@@ -1,46 +0,0 @@-/**- * 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 };-}diff --git a/apps/mobile/package.json b/apps/mobile/package.jsonindex 488ca3e16b2..293833b20e2 100644--- a/apps/mobile/package.json+++ b/apps/mobile/package.json@@ -106,7 +106,6 @@"expo-video": "~57.0.3","expo-web-browser": "~57.0.2","expo-widgets": "~57.0.15",- "punycode": "^2.3.1","react": "19.2.3","react-dom": "19.2.3","react-native": "0.86.3",diff --git a/apps/mobile/src/components/GlassSafeAreaView.tsx b/apps/mobile/src/components/GlassSafeAreaView.tsxdeleted file mode 100644index 16a5fc4a479..00000000000--- a/apps/mobile/src/components/GlassSafeAreaView.tsx+++ /dev/null@@ -1,41 +0,0 @@-import type { ReactNode } from "react";-import { View, type StyleProp, type ViewStyle } from "react-native";-import { useSafeAreaInsets } from "react-native-safe-area-context";--import { GlassSurface } from "./GlassSurface";--export interface GlassSafeAreaViewProps {- readonly leftSlot?: ReactNode;- readonly centerSlot?: ReactNode;- readonly rightSlot?: ReactNode;- readonly style?: StyleProp<ViewStyle>;-}--export function GlassSafeAreaView({- leftSlot,- centerSlot,- rightSlot,- style,-}: GlassSafeAreaViewProps) {- const insets = useSafeAreaInsets();- const headerPaddingTop = insets.top + 16;-- return (- <View className="border-b border-header-border bg-header" style={style}>- <GlassSurface- chrome="none"- glassEffectStyle="regular"- style={{ borderRadius: 0, backgroundColor: "transparent" }}- >- <View- className="flex-row items-center gap-2.5 px-5 pb-4"- style={{ paddingTop: headerPaddingTop }}- >- <View className="items-start justify-center">{leftSlot}</View>- <View className="flex-1 items-center justify-center overflow-hidden">{centerSlot}</View>- <View className="items-end justify-center">{rightSlot}</View>- </View>- </GlassSurface>- </View>- );-}diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.tsindex b0f77d7704b..a2d4261de60 100644--- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts+++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts@@ -828,18 +828,6 @@ export function unregisterAgentAwarenessConnection(environmentId: EnvironmentId)removeAgentAwarenessConnection(environmentId);}-export function unregisterAllAgentAwarenessConnections(): void {- environmentConnections.clear();- pushTokenSubscription?.remove();- pushTokenSubscription = null;- appStateSubscription?.remove();- appStateSubscription = null;- if (activeLiveActivityRegistrationRetry) {- clearTimeout(activeLiveActivityRegistrationRetry);- activeLiveActivityRegistrationRetry = null;- }-}-export function refreshAgentAwarenessRegistration(): Effect.Effect<void,never,diff --git a/apps/mobile/src/features/cloud/managedRelayState.ts b/apps/mobile/src/features/cloud/managedRelayState.tsindex eec1e3410e6..8c41d74841e 100644--- a/apps/mobile/src/features/cloud/managedRelayState.ts+++ b/apps/mobile/src/features/cloud/managedRelayState.ts@@ -4,10 +4,7 @@ import {managedRelaySessionAtom,readManagedRelaySnapshotState,} from "@t3tools/client-runtime/relay";-import type {- RelayClientEnvironmentRecord,- RelayEnvironmentStatusResponse,-} from "@t3tools/contracts/relay";+import type { RelayClientEnvironmentRecord } from "@t3tools/contracts/relay";import { AsyncResult, Atom } from "effect/unstable/reactivity";import { useCallback, useEffect } from "react";@@ -26,10 +23,6 @@ const EMPTY_ENVIRONMENTS_ATOM = Atom.make(AsyncResult.success<ReadonlyArray<RelayClientEnvironmentRecord>>([]),).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environments:null"));-const EMPTY_ENVIRONMENT_STATUS_ATOM = Atom.make(- AsyncResult.initial<RelayEnvironmentStatusResponse, never>(false),-).pipe(Atom.keepAlive, Atom.withLabel("managed-relay:mobile:environment-status:null"));-export function useManagedRelayEnvironments() {const session = useAtomValue(managedRelaySessionAtom);const accountId = session?.accountId ?? null;@@ -59,39 +52,6 @@ export function useManagedRelayEnvironments() {};}-export function useManagedRelayEnvironmentStatus(environment: RelayClientEnvironmentRecord) {- const session = useAtomValue(managedRelaySessionAtom);- const accountId = session?.accountId ?? null;- const atom = accountId- ? managedRelayQueryManager.environmentStatusAtom({ accountId, environment })- : EMPTY_ENVIRONMENT_STATUS_ATOM;- const result = useAtomValue(atom);- const snapshot = readManagedRelaySnapshotState(result);- useEffect(() => {- if (snapshot.error) {- console.error("[t3-cloud] Relay environment status failed", {- environmentId: environment.environmentId,- message: snapshot.error,- traceId: snapshot.errorTraceId,- });- }- }, [environment.environmentId, snapshot.error, snapshot.errorTraceId]);- const refresh = useCallback(() => {- if (accountId) {- managedRelayQueryManager.refreshEnvironmentStatus(appAtomRegistry, {- accountId,- environment,- });- }- }, [accountId, environment]);-- return {- ...snapshot,- accountId,- refresh,- };-}-export function refreshManagedRelayEnvironments(): void {const session = appAtomRegistry.get(managedRelaySessionAtom);if (session) {diff --git a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.tsindex 438b50a27ee..08ab53971b6 100644--- a/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts+++ b/apps/mobile/src/features/diffs/nativeReviewDiffSurface.test.ts@@ -44,21 +44,6 @@ describe("resolveNativeReviewDiffView", () => {expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");});- it("does not fall back to stale legacy native review diff view names", async () => {- globalThis.expo = {- getViewConfig: vi.fn().mockImplementation((moduleName: string) => {- if (moduleName === "T3ReviewDiffView") {- return { validAttributes: {}, directEventTypes: {} };- }- return null;- }),- } as unknown as typeof globalThis.expo;- expoMocks.requireNativeView.mockReturnValue(nativeView);- const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");- expect(resolveNativeReviewDiffView()).toBeNull();- expect(expoMocks.requireNativeView).not.toHaveBeenCalled();- });-it("returns null when the view manager cannot be required", async () => {setExpoViewConfigAvailable();const cause = new Error("boom");diff --git a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsxindex 052c89a7e62..95177ed3e92 100644--- a/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx+++ b/apps/mobile/src/features/files/ThreadFilesRouteScreen.tsx@@ -12,7 +12,11 @@ import {ThreadId,} from "@t3tools/contracts";import { videoMimeType } from "@t3tools/shared/video";-import { mediaMimeTypeFromExtension } from "@t3tools/shared/filePreview";+import {+ isWorkspaceBrowserPreviewPath,+ isWorkspaceImagePreviewPath,+ mediaMimeTypeFromExtension,+} from "@t3tools/shared/filePreview";import { mediaFileReference } from "@t3tools/client-runtime/media-reference";import { AndroidHeaderIconButton, AndroidScreenHeader } from "../../components/AndroidScreenHeader";@@ -56,8 +60,6 @@ import { WorkspaceFileVideoPreview } from "./WorkspaceFileVideoPreview";import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";import {basename,- isBrowserPreviewFile,- isImagePreviewFile,isMarkdownPreviewFile,isSvgImagePreviewFile,isVideoPreviewFile,@@ -92,7 +94,9 @@ function normalizeRouteLine(value: string | null): number | null {function defaultViewMode(path: string | null): FileViewMode {return path !== null &&- (isBrowserPreviewFile(path) || isImagePreviewFile(path) || isVideoPreviewFile(path))+ (isWorkspaceBrowserPreviewPath(path) ||+ isWorkspaceImagePreviewPath(path) ||+ isVideoPreviewFile(path))? "preview": "source";}@@ -114,8 +118,8 @@ function FileContent(props: {// Reopening a mutable host file must not reuse a poster from an earlier visit.const thumbnailInstanceId = useId();const isMarkdown = isMarkdownPreviewFile(props.relativePath);- const isBrowserFile = isBrowserPreviewFile(props.relativePath);- const isImageFile = isImagePreviewFile(props.relativePath);+ const isBrowserFile = isWorkspaceBrowserPreviewPath(props.relativePath);+ const isImageFile = isWorkspaceImagePreviewPath(props.relativePath);if (isVideoPreviewFile(props.relativePath)) {return (@@ -520,8 +524,10 @@ export function ThreadFileScreen(props: ThreadFileRouteScreenProps) {const previewKey = JSON.stringify([environmentId, cwd, relativePath, previewRevision]);const [fullScreenPreview, setFullScreenPreview] = useState<FilePreviewSource | null>(null);const isVideoFile = relativePath !== null && isVideoPreviewFile(relativePath);- const isBrowserFile = relativePath !== null && !isVideoFile && isBrowserPreviewFile(relativePath);- const isImageFile = relativePath !== null && !isVideoFile && isImagePreviewFile(relativePath);+ const isBrowserFile =+ relativePath !== null && !isVideoFile && isWorkspaceBrowserPreviewPath(relativePath);+ const isImageFile =+ relativePath !== null && !isVideoFile && isWorkspaceImagePreviewPath(relativePath);const canPreview =relativePath !== null &&(isMarkdownPreviewFile(relativePath) || isBrowserFile || isImageFile || isVideoFile);diff --git a/apps/mobile/src/features/files/filePath.test.ts b/apps/mobile/src/features/files/filePath.test.tsindex af0ace61fc0..376068c2115 100644--- a/apps/mobile/src/features/files/filePath.test.ts+++ b/apps/mobile/src/features/files/filePath.test.ts@@ -1,11 +1,6 @@import { describe, expect, it } from "vite-plus/test";-import {- isBrowserPreviewFile,- isImagePreviewFile,- isSvgImagePreviewFile,- resolveWorkspaceRelativeFilePath,-} from "./filePath";+import { isSvgImagePreviewFile, resolveWorkspaceRelativeFilePath } from "./filePath";describe("resolveWorkspaceRelativeFilePath", () => {it("keeps normalized workspace-relative paths", () => {@@ -29,13 +24,6 @@ describe("resolveWorkspaceRelativeFilePath", () => {});describe("file preview types", () => {- it("recognizes browser and image previews", () => {- expect(isBrowserPreviewFile("reports/summary.html")).toBe(true);- expect(isImagePreviewFile("assets/icon.png")).toBe(true);- expect(isImagePreviewFile("assets/diagram.SVG?raw=1")).toBe(true);- expect(isImagePreviewFile("src/image.ts")).toBe(false);- });-it("identifies SVG images that need web rendering", () => {expect(isSvgImagePreviewFile("assets/diagram.svg#icon")).toBe(true);expect(isSvgImagePreviewFile("assets/photo.png")).toBe(false);diff --git a/apps/mobile/src/features/files/filePath.ts b/apps/mobile/src/features/files/filePath.tsindex 12217aab74f..76672ec5658 100644--- a/apps/mobile/src/features/files/filePath.ts+++ b/apps/mobile/src/features/files/filePath.ts@@ -1,8 +1,4 @@-import {- isWorkspaceBrowserPreviewPath,- isWorkspaceImagePreviewPath,- isWorkspaceVideoPreviewPath,-} from "@t3tools/shared/filePreview";+import { isWorkspaceVideoPreviewPath } from "@t3tools/shared/filePreview";export interface FileBreadcrumb {readonly label: string;@@ -88,14 +84,6 @@ export function resolveWorkspaceRelativeFilePath(return normalizeRelativePath(normalizedTarget.slice(normalizedRoot.length + 1));}-export function isBrowserPreviewFile(path: string): boolean {- return isWorkspaceBrowserPreviewPath(path);-}--export function isImagePreviewFile(path: string): boolean {- return isWorkspaceImagePreviewPath(path);-}-export function isVideoPreviewFile(path: string): boolean {return isWorkspaceVideoPreviewPath(path);}diff --git a/apps/mobile/src/features/files/preload-workspace-file.ts b/apps/mobile/src/features/files/preload-workspace-file.tsindex 7df750883f5..a91e4f84b0d 100644--- a/apps/mobile/src/features/files/preload-workspace-file.ts+++ b/apps/mobile/src/features/files/preload-workspace-file.ts@@ -1,9 +1,13 @@import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";import type { EnvironmentId } from "@t3tools/contracts";+import {+ isWorkspaceBrowserPreviewPath,+ isWorkspaceImagePreviewPath,+} from "@t3tools/shared/filePreview";import { appAtomRegistry } from "../../state/atom-registry";import { projectEnvironment } from "../../state/projects";-import { isBrowserPreviewFile, isImagePreviewFile, isVideoPreviewFile } from "./filePath";+import { isVideoPreviewFile } from "./filePath";import { prepareSourceFileDocument } from "./source-file-document";import { sourceHighlightAtom } from "./sourceHighlightingState";import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";@@ -26,8 +30,8 @@ export function preloadWorkspaceFileContents(input: {readonly theme: ReviewDiffTheme;}): void {if (- isBrowserPreviewFile(input.relativePath) ||- isImagePreviewFile(input.relativePath) ||+ isWorkspaceBrowserPreviewPath(input.relativePath) ||+ isWorkspaceImagePreviewPath(input.relativePath) ||isVideoPreviewFile(input.relativePath)) {return;diff --git a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsxindex 150584aedea..e35367b7471 100644--- a/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx+++ b/apps/mobile/src/features/review/ReviewHighlighterProvider.tsx@@ -1,4 +1,4 @@-import { createContext, type ReactNode, useContext, useMemo } from "react";+import { createContext, type ReactNode, useMemo } from "react";import { type ReviewHighlighterState, useReviewHighlighterState } from "./reviewHighlighterState";@@ -18,7 +18,3 @@ export function ReviewHighlighterProvider(props: { readonly children: ReactNode</ReviewHighlighterContext.Provider>);}--export function useReviewHighlighterStatus(): ReviewHighlighterState {- return useContext(ReviewHighlighterContext);-}diff --git a/apps/mobile/src/features/review/diffParser.ts b/apps/mobile/src/features/review/diffParser.tsdeleted file mode 100644index 76e8872f8ab..00000000000--- a/apps/mobile/src/features/review/diffParser.ts+++ /dev/null@@ -1,158 +0,0 @@-export type ParsedDiffLineType = "context" | "add" | "delete" | "meta" | "hunk";--export interface ParsedDiffLine {- readonly id: string;- readonly type: ParsedDiffLineType;- readonly oldLine: number | null;- readonly newLine: number | null;- readonly content: string;-}--export interface ParsedDiffFile {- readonly id: string;- readonly oldPath: string | null;- readonly newPath: string | null;- readonly lines: ReadonlyArray<ParsedDiffLine>;-}--function parseHunkStart(- line: string,-): { readonly oldLine: number; readonly newLine: number } | null {- const match = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);- if (!match) {- return null;- }-- return {- oldLine: Number.parseInt(match[1] ?? "0", 10),- newLine: Number.parseInt(match[2] ?? "0", 10),- };-}--function parseDiffPath(line: string, prefix: "--- " | "+++ "): string | null {- if (!line.startsWith(prefix)) {- return null;- }- const raw = line.slice(prefix.length).trim();- if (raw === "/dev/null") {- return null;- }- return raw.replace(/^[ab]\//, "");-}--export function parseUnifiedDiff(diff: string): ReadonlyArray<ParsedDiffFile> {- const files: ParsedDiffFile[] = [];- let current: {- oldPath: string | null;- newPath: string | null;- lines: ParsedDiffLine[];- } | null = null;- let oldLine: number | null = null;- let newLine: number | null = null;-- const pushCurrent = () => {- if (!current) {- return;- }- files.push({- id: `${current.oldPath ?? "null"}:${current.newPath ?? "null"}:${files.length}`,- oldPath: current.oldPath,- newPath: current.newPath,- lines: current.lines,- });- };-- for (const rawLine of diff.replace(/\r\n/g, "\n").split("\n")) {- if (rawLine.startsWith("diff --git ")) {- pushCurrent();- const match = rawLine.match(/^diff --git a\/(.+) b\/(.+)$/);- current = {- oldPath: match?.[1] ?? null,- newPath: match?.[2] ?? null,- lines: [],- };- oldLine = null;- newLine = null;- continue;- }-- if (!current) {- if (rawLine.trim().length === 0) {- continue;- }- current = { oldPath: null, newPath: null, lines: [] };- }-- const oldPath = parseDiffPath(rawLine, "--- ");- if (oldPath !== null || rawLine === "--- /dev/null") {- current.oldPath = oldPath;- continue;- }-- const newPath = parseDiffPath(rawLine, "+++ ");- if (newPath !== null || rawLine === "+++ /dev/null") {- current.newPath = newPath;- continue;- }-- const hunk = parseHunkStart(rawLine);- if (hunk) {- oldLine = hunk.oldLine;- newLine = hunk.newLine;- current.lines.push({- id: `${current.lines.length}:hunk`,- type: "hunk",- oldLine: null,- newLine: null,- content: rawLine,- });- continue;- }-- if (oldLine === null || newLine === null) {- current.lines.push({- id: `${current.lines.length}:meta`,- type: "meta",- oldLine: null,- newLine: null,- content: rawLine,- });- continue;- }-- const marker = rawLine[0];- const content = rawLine.length > 0 ? rawLine.slice(1) : "";- if (marker === "+") {- current.lines.push({- id: `${current.lines.length}:add:${newLine}`,- type: "add",- oldLine: null,- newLine,- content,- });- newLine += 1;- } else if (marker === "-") {- current.lines.push({- id: `${current.lines.length}:delete:${oldLine}`,- type: "delete",- oldLine,- newLine: null,- content,- });- oldLine += 1;- } else {- current.lines.push({- id: `${current.lines.length}:context:${oldLine}:${newLine}`,- type: "context",- oldLine,- newLine,- content: marker === " " ? content : rawLine,- });- oldLine += 1;- newLine += 1;- }- }-- pushCurrent();- return files.filter((file) => file.lines.length > 0 || file.oldPath || file.newPath);-}diff --git a/apps/mobile/src/features/review/reviewCommentSelection.ts b/apps/mobile/src/features/review/reviewCommentSelection.tsindex 5e6e1c3683a..8ec9bbb43a3 100644--- a/apps/mobile/src/features/review/reviewCommentSelection.ts+++ b/apps/mobile/src/features/review/reviewCommentSelection.ts@@ -84,16 +84,6 @@ export function getReviewUnifiedLineNumber(line: ReviewRenderableLineRow): numbereturn line.newLineNumber ?? line.oldLineNumber;}-export function formatReviewLineLabel(line: ReviewRenderableLineRow): string {- if (line.newLineNumber !== null) {- return `new line ${line.newLineNumber}`;- }- if (line.oldLineNumber !== null) {- return `old line ${line.oldLineNumber}`;- }- return "file";-}-export function getReviewChangeMarker(change: ReviewRenderableLineRow["change"]): string {if (change === "add") return "+";if (change === "delete") return "-";diff --git a/apps/mobile/src/features/review/reviewState.ts b/apps/mobile/src/features/review/reviewState.tsindex 3fce8131dd1..a86d53c3585 100644--- a/apps/mobile/src/features/review/reviewState.ts+++ b/apps/mobile/src/features/review/reviewState.ts@@ -242,20 +242,6 @@ export function updateReviewExpandedFileIds(});}-export function updateReviewRevealedLargeFileIds(- threadKey: string,- sectionId: string,- update: (current: ReadonlyArray<string> | undefined) => ReadonlyArray<string> | undefined,-): void {- const atom = reviewRevealedLargeFileIdsByThreadKeyAtom(threadKey);- const current = appAtomRegistry.get(atom);- const nextValue = update(current[sectionId]);- appAtomRegistry.set(atom, {- ...current,- [sectionId]: nextValue,- });-}-export function updateReviewViewedFileIds(threadKey: string,sectionId: string,diff --git a/apps/mobile/src/features/review/shikiReviewHighlighter.ts b/apps/mobile/src/features/review/shikiReviewHighlighter.tsindex 008a0761949..c684a668643 100644--- a/apps/mobile/src/features/review/shikiReviewHighlighter.ts+++ b/apps/mobile/src/features/review/shikiReviewHighlighter.ts@@ -814,22 +814,6 @@ function storeResolvedHighlightedFile(cacheKey: string, highlighted: ReviewHighl}}-export function clearReviewHighlightFileCache(): void {- highlightCache.clear();- resolvedHighlightCache.clear();-}--export function getCachedHighlightedReviewFile(- file: ReviewRenderableFile,- theme: ReviewDiffTheme,-): ReviewHighlightedFile | null {- if (REVIEW_HIGHLIGHTER_DISABLE_RESULT_CACHE) {- return null;- }-- return resolvedHighlightCache.get(getHighlightCacheKey(file, theme)) ?? null;-}-export async function highlightReviewFile(file: ReviewRenderableFile,theme: ReviewDiffTheme,diff --git a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx b/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsxdeleted file mode 100644index e3fa761d65c..00000000000--- a/apps/mobile/src/features/terminal/ThreadTerminalPanel.tsx+++ /dev/null@@ -1,256 +0,0 @@-import { DEFAULT_TERMINAL_ID, type EnvironmentId, type ThreadId } from "@t3tools/contracts";-import { SymbolView } from "../../components/AppSymbol";-import { memo, useCallback, useEffect, useMemo, useRef } from "react";-import { Pressable, View } from "react-native";--import { AppText as Text } from "../../components/AppText";-import { terminalEnvironment } from "../../state/terminal";-import { useAtomCommand } from "../../state/use-atom-command";-import { useAttachedTerminalSession } from "../../state/use-terminal-session";-import { TerminalSurface } from "./NativeTerminalSurface";-import { hasNativeTerminalSurface } from "./nativeTerminalModule";-import {- buildThreadTerminalAttachInput,- type TerminalGridSize,- type ThreadTerminalSubscriptionIdentity,-} from "./threadTerminalPanelModel";--interface ThreadTerminalPanelProps {- readonly environmentId: EnvironmentId;- readonly threadId: ThreadId;- readonly cwd: string;- readonly worktreePath: string | null;- readonly visible: boolean;- readonly onClose: () => void;-}--const DEFAULT_TERMINAL_COLS = 80;-const DEFAULT_TERMINAL_ROWS = 24;--export const ThreadTerminalPanel = memo(function ThreadTerminalPanel(- props: ThreadTerminalPanelProps,-) {- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");- const resizeTerminal = useAtomCommand(terminalEnvironment.resize, "terminal resize");- const closeTerminal = useAtomCommand(terminalEnvironment.close, "terminal close");- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");- const nativeTerminalAvailable = hasNativeTerminalSurface();- const terminalId = DEFAULT_TERMINAL_ID;- const lastGridSizeRef = useRef<TerminalGridSize>({- cols: DEFAULT_TERMINAL_COLS,- rows: DEFAULT_TERMINAL_ROWS,- });- const subscriptionIdentity = useMemo<ThreadTerminalSubscriptionIdentity>(- () => ({- environmentId: props.environmentId,- threadId: props.threadId,- terminalId,- cwd: props.cwd,- worktreePath: props.worktreePath,- }),- [props.cwd, props.environmentId, props.threadId, props.worktreePath, terminalId],- );- const attachInput = useMemo(- () =>- props.visible- ? buildThreadTerminalAttachInput(subscriptionIdentity, lastGridSizeRef.current)- : null,- [props.visible, subscriptionIdentity],- );- const terminal = useAttachedTerminalSession({- environmentId: props.environmentId,- terminal: attachInput,- });-- const terminalKey = `${props.environmentId}:${props.threadId}:${terminalId}`;- const isRunning = terminal.status === "running" || terminal.status === "starting";-- // Close the session and dismiss the panel when the process ends while- // attached (e.g. typing `exit`), mirroring the web drawer's- // onSessionExited flow.- const runningTerminalKeyRef = useRef<string | null>(null);- const reopenedStaleTerminalKeyRef = useRef<string | null>(null);-- // Attach subscriptions are cached with an idle TTL; reopening the panel- // after its session ended reuses the stale stream without a new attach- // RPC. Issue an explicit open so the server respawns the session and its- // snapshot flows into the live subscription.- useEffect(() => {- if (isRunning) {- reopenedStaleTerminalKeyRef.current = null;- return;- }- if (- attachInput === null ||- (terminal.status !== "closed" && terminal.status !== "exited") ||- terminal.version === 0 ||- runningTerminalKeyRef.current === terminalKey ||- reopenedStaleTerminalKeyRef.current === terminalKey- ) {- return;- }- reopenedStaleTerminalKeyRef.current = terminalKey;- void openTerminal({- environmentId: props.environmentId,- input: {- threadId: props.threadId,- terminalId,- cwd: props.cwd,- worktreePath: props.worktreePath,- cols: lastGridSizeRef.current.cols,- rows: lastGridSizeRef.current.rows,- },- }).then((result) => {- // Release the guard on failure so a later render can retry the respawn.- if (result._tag === "Failure" && reopenedStaleTerminalKeyRef.current === terminalKey) {- reopenedStaleTerminalKeyRef.current = null;- }- });- }, [- attachInput,- isRunning,- openTerminal,- props.cwd,- props.environmentId,- props.threadId,- props.worktreePath,- terminal.status,- terminal.version,- terminalId,- terminalKey,- ]);-- useEffect(() => {- // Forget both markers while hidden: if the process ends while the panel- // is unobserved (or was just auto-closed), the next show must take the- // stale-reopen path instead of treating it as a live exit or skipping- // the respawn.- if (attachInput === null) {- runningTerminalKeyRef.current = null;- reopenedStaleTerminalKeyRef.current = null;- return;- }- if (isRunning) {- runningTerminalKeyRef.current = terminalKey;- return;- }- // The web drawer treats both exited and closed as session end.- const sessionEnded = terminal.status === "exited" || terminal.status === "closed";- if (!sessionEnded || runningTerminalKeyRef.current !== terminalKey) {- return;- }- runningTerminalKeyRef.current = null;- // Mark this key handled so the stale-attach effect doesn't respawn the- // session the user just ended.- reopenedStaleTerminalKeyRef.current = terminalKey;- void closeTerminal({- environmentId: props.environmentId,- input: {- threadId: props.threadId,- terminalId,- },- });- props.onClose();- }, [attachInput, closeTerminal, isRunning, props, terminal.status, terminalId, terminalKey]);-- const sendResize = useCallback(- (size: TerminalGridSize) => {- void resizeTerminal({- environmentId: props.environmentId,- input: {- threadId: props.threadId,- terminalId,- cols: size.cols,- rows: size.rows,- },- });- },- [props.environmentId, props.threadId, resizeTerminal, terminalId],- );-- useEffect(() => {- if (isRunning) {- sendResize(lastGridSizeRef.current);- }- }, [isRunning, sendResize]);-- const handleInput = useCallback(- (data: string) => {- if (!isRunning) {- return;- }-- void writeTerminal({- environmentId: props.environmentId,- input: {- threadId: props.threadId,- terminalId,- data,- },- });- },- [isRunning, props.environmentId, props.threadId, terminalId, writeTerminal],- );-- const handleResize = useCallback(- (size: TerminalGridSize) => {- const previousSize = lastGridSizeRef.current;- if (size.cols === previousSize.cols && size.rows === previousSize.rows) {- return;- }-- lastGridSizeRef.current = size;- if (!isRunning) {- return;- }-- sendResize(size);- },- [isRunning, sendResize],- );-- if (!props.visible) {- return null;- }-- return (- <View className="absolute inset-x-3 bottom-28 top-28 overflow-hidden rounded-[8px] border border-border bg-screen shadow-2xl">- <View className="flex-row items-center justify-between border-b border-border px-3 py-2">- <View className="min-w-0 flex-1">- <Text className="font-t3-bold text-sm text-foreground" numberOfLines={1}>- Terminal- </Text>- <Text className="text-2xs text-foreground-muted" numberOfLines={1}>- {nativeTerminalAvailable ? "Native Ghostty surface" : "Text fallback active"}- </Text>- </View>- <View className="flex-row items-center gap-2">- {terminal.error ? (- <Text className="max-w-44 text-right text-2xs text-red-300" numberOfLines={1}>- {terminal.error}- </Text>- ) : null}- <Pressable- className="h-8 w-8 items-center justify-center rounded-[8px] bg-subtle"- onPress={props.onClose}- >- <SymbolView- name="xmark"- size={13}- tintColorClassName={"accent-icon"}- type="monochrome"- />- </Pressable>- </View>- </View>- <TerminalSurface- terminalKey={terminalKey}- buffer={terminal.buffer}- isRunning={isRunning}- onInput={handleInput}- onResize={handleResize}- style={{ flex: 1 }}- />- </View>- );-});diff --git a/apps/mobile/src/features/terminal/threadTerminalPanelModel.ts b/apps/mobile/src/features/terminal/threadTerminalPanelModel.tsdeleted file mode 100644index 07ef46a7bc6..00000000000--- a/apps/mobile/src/features/terminal/threadTerminalPanelModel.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { EnvironmentId, TerminalAttachInput } from "@t3tools/contracts";--export interface ThreadTerminalSubscriptionIdentity {- readonly environmentId: EnvironmentId;- readonly threadId: TerminalAttachInput["threadId"];- readonly terminalId: TerminalAttachInput["terminalId"];- readonly cwd: string;- readonly worktreePath: string | null;-}--export interface TerminalGridSize {- readonly cols: number;- readonly rows: number;-}--export function buildThreadTerminalAttachInput(- identity: ThreadTerminalSubscriptionIdentity,- gridSize: TerminalGridSize,-): TerminalAttachInput {- return {- threadId: identity.threadId,- terminalId: identity.terminalId,- cwd: identity.cwd,- worktreePath: identity.worktreePath,- cols: gridSize.cols,- rows: gridSize.rows,- };-}diff --git a/apps/mobile/src/features/threads/threadPresentation.ts b/apps/mobile/src/features/threads/threadPresentation.tsindex b91c7152a16..59cf108a01d 100644--- a/apps/mobile/src/features/threads/threadPresentation.ts+++ b/apps/mobile/src/features/threads/threadPresentation.ts@@ -2,11 +2,6 @@ import type { StatusTone } from "../../components/StatusPill";import type { OrchestrationLatestTurn, OrchestrationSession } from "@t3tools/contracts";import { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";-export function threadSortValue(thread: EnvironmentThreadShell): number {- const candidate = Date.parse(thread.updatedAt ?? thread.createdAt);- return Number.isNaN(candidate) ? 0 : candidate;-}-export type ThreadStatusKind =| "pending-approval"| "awaiting-input"@@ -25,12 +20,6 @@ export interface ThreadStatusPresentation extends StatusTone {readonly pulse: boolean;}-/** Neutral icon colors for threads with no actionable status. */-export const THREAD_STATUS_NEUTRAL_ICON = {- iconColor: "#8e8e93",- iconBackground: "rgba(142,142,147,0.22)",-} as const;-function isLatestTurnSettled(latestTurn: OrchestrationLatestTurn | null,session: OrchestrationSession | null,diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.test.ts b/apps/mobile/src/features/threads/use-composer-command-menu.test.tsindex 18ae2bbb234..9db123450f9 100644--- a/apps/mobile/src/features/threads/use-composer-command-menu.test.ts+++ b/apps/mobile/src/features/threads/use-composer-command-menu.test.ts@@ -1,6 +1,6 @@import { describe, expect, it, vi } from "vite-plus/test";-vi.mock("../../state/use-composer-path-search", () => ({+vi.mock("../../state/queries", () => ({useComposerPathSearch: () => ({ entries: [], isPending: false }),}));diff --git a/apps/mobile/src/features/threads/use-composer-command-menu.ts b/apps/mobile/src/features/threads/use-composer-command-menu.tsindex ac703a547fd..cca15c61781 100644--- a/apps/mobile/src/features/threads/use-composer-command-menu.ts+++ b/apps/mobile/src/features/threads/use-composer-command-menu.ts@@ -16,7 +16,7 @@ import {import { useCallback, useEffect, useMemo, useRef, useState } from "react";import type { ComposerEditorSelection } from "../../components/ComposerEditor";-import { useComposerPathSearch } from "../../state/use-composer-path-search";+import { useComposerPathSearch } from "../../state/queries";import type { ComposerCommandItem } from "./ComposerCommandPopover";import { matchesSlashSkillQuery } from "./composerSlashSkillSearch";diff --git a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.tsindex 25ec4ff0e7d..61c4fb65cdc 100644--- a/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts+++ b/apps/mobile/src/features/threads/use-legacy-plan-mode-enabled.ts@@ -9,10 +9,6 @@ import { resolveLegacyPlanModeEnabled } from "./legacy-plan-mode";* Keep the legacy composer mode hidden until the preference has loaded and is* explicitly enabled.*/-export function useLegacyPlanModeEnabled(): boolean {- return useLegacyPlanModeState().enabled;-}-export function useLegacyPlanModeState(): { readonly enabled: boolean; readonly loaded: boolean } {const preferences = useAtomValue(mobilePreferencesAtom);const loaded = AsyncResult.isSuccess(preferences);diff --git a/apps/mobile/src/state/auth.ts b/apps/mobile/src/state/auth.tsdeleted file mode 100644index 835dee7f783..00000000000--- a/apps/mobile/src/state/auth.ts+++ /dev/null@@ -1,5 +0,0 @@-import { createAuthEnvironmentAtoms } from "@t3tools/client-runtime/state/auth";--import { connectionAtomRuntime } from "../connection/runtime";--export const authEnvironment = createAuthEnvironmentAtoms(connectionAtomRuntime);diff --git a/apps/mobile/src/state/git.ts b/apps/mobile/src/state/git.tsdeleted file mode 100644index 66bb3dc0bde..00000000000--- a/apps/mobile/src/state/git.ts+++ /dev/null@@ -1,5 +0,0 @@-import { createGitEnvironmentAtoms } from "@t3tools/client-runtime/state/git";--import { connectionAtomRuntime } from "../connection/runtime";--export const gitEnvironment = createGitEnvironmentAtoms(connectionAtomRuntime);diff --git a/apps/mobile/src/state/use-composer-path-search.ts b/apps/mobile/src/state/use-composer-path-search.tsdeleted file mode 100644index 485b472dcb0..00000000000--- a/apps/mobile/src/state/use-composer-path-search.ts+++ /dev/null@@ -1,7 +0,0 @@-import { type ComposerPathSearchTarget } from "@t3tools/client-runtime/state/threads";--import { useComposerPathSearch as useComposerPathSearchQuery } from "../state/queries";--export function useComposerPathSearch(target: ComposerPathSearchTarget) {- return useComposerPathSearchQuery(target);-}diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.tsindex c43486623c4..c4e1c62ef50 100644--- a/apps/server/integration/OrchestrationEngineHarness.integration.ts+++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts@@ -29,7 +29,7 @@ import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Laimport { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";import { ProjectionPendingApprovalRepositoryLive } from "../src/persistence/Layers/ProjectionPendingApprovals.ts";-import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";+import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";@@ -45,7 +45,7 @@ import {ProviderEventLoggers,} from "../src/provider/Layers/ProviderEventLoggers.ts";import { ProviderService } from "../src/provider/Services/ProviderService.ts";-import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";+import { AnalyticsService } from "../src/telemetry/AnalyticsService.ts";import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityResolver.ts";import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";@@ -271,7 +271,7 @@ export const makeOrchestrationIntegrationHarness = (Layer.provide(OrchestrationCommandReceiptRepositoryLive),);const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(- Layer.provide(ProviderSessionRuntimeRepositoryLive),+ Layer.provide(ProviderSessionRuntime.layer),);const realCodexRegistry = Layer.effect(ProviderAdapterRegistry,diff --git a/apps/server/integration/providerService.integration.test.ts b/apps/server/integration/providerService.integration.test.tsindex 6089d22d9aa..3ad85b1a68b 100644--- a/apps/server/integration/providerService.integration.test.ts+++ b/apps/server/integration/providerService.integration.test.ts@@ -25,7 +25,7 @@ import {} from "../src/provider/Services/ProviderService.ts";import * as ServerConfig from "../src/config.ts";import { ServerSettingsService } from "../src/serverSettings.ts";-import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";+import { AnalyticsService } from "../src/telemetry/AnalyticsService.ts";import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";import * as ProviderSessionRuntime from "../src/persistence/ProviderSessionRuntime.ts";diff --git a/apps/server/scripts/cursor-acp-model-mismatch-probe.ts b/apps/server/scripts/cursor-acp-model-mismatch-probe.tsdeleted file mode 100644index 7e4e88aeb2b..00000000000--- a/apps/server/scripts/cursor-acp-model-mismatch-probe.ts+++ /dev/null@@ -1,442 +0,0 @@-// @effect-diagnostics nodeBuiltinImport:off-import * as NodeChildProcess from "node:child_process";-import * as NodeProcess from "node:process";-import * as NodeReadline from "node:readline";-import * as NodeTimers from "node:timers";-import { resolveSpawnCommand } from "@t3tools/shared/shell";-import * as Effect from "effect/Effect";--type JsonPrimitive = null | boolean | number | string;-type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };--type JsonRpcId = number | string;--type JsonRpcMessage = {- jsonrpc?: string;- id?: JsonRpcId;- method?: string;- params?: JsonValue;- result?: JsonValue;- error?: JsonValue;- headers?: JsonValue;-};--type SelectLeafOption = {- value: string;- label?: string;- name?: string;-};--type SelectGroupOption = {- label?: string;- name?: string;- options: SelectLeafOption[];-};--type SessionConfigOption = {- id: string;- name?: string;- category?: string;- type?: string;- options?: Array<SelectLeafOption | SelectGroupOption>;-};--type SessionNewResult = {- sessionId: string;- configOptions?: SessionConfigOption[];-};--type SetConfigResult = {- configOptions?: SessionConfigOption[];-};--type PendingRequest = {- method: string;- resolve: (value: JsonValue | undefined) => void;- reject: (error: Error) => void;-};--const targetCwd = NodeProcess.argv[2] ?? NodeProcess.cwd();-const targetModel = NodeProcess.argv[3] ?? "gpt-5.4";-const promptText = NodeProcess.argv[4] ?? "helo";-const targetReasoning = NodeProcess.env.CURSOR_REASONING ?? "";-const targetContext = NodeProcess.env.CURSOR_CONTEXT ?? "";-const targetFast = NodeProcess.env.CURSOR_FAST ?? "";-const agentBin = NodeProcess.env.CURSOR_AGENT_BIN ?? "cursor-agent";-const promptWaitMs = Number(NodeProcess.env.CURSOR_PROMPT_WAIT_MS ?? "4000");-const requestTimeoutMs = Number(NodeProcess.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");--function logSection(title: string, value: unknown) {- NodeProcess.stdout.write(`\n=== ${title} ===\n`);- NodeProcess.stdout.write(`${JSON.stringify(value, null, 2)}\n`);-}--function fail(message: string): never {- throw new Error(message);-}--function asString(value: JsonValue | undefined): string | null {- return typeof value === "string" ? value : null;-}--function flattenSelectValues(option: SessionConfigOption | undefined): string[] {- if (!option || option.type !== "select" || !Array.isArray(option.options)) {- return [];- }-- const values: string[] = [];- for (const entry of option.options) {- if (!entry || typeof entry !== "object") {- continue;- }- if ("value" in entry && typeof entry.value === "string") {- values.push(entry.value);- continue;- }- if ("options" in entry && Array.isArray(entry.options)) {- for (const nested of entry.options) {- if (nested && typeof nested === "object" && typeof nested.value === "string") {- values.push(nested.value);- }- }- }- }- return values;-}--function findConfigOption(- configOptions: SessionConfigOption[],- predicate: (option: SessionConfigOption) => boolean,-): SessionConfigOption | undefined {- return configOptions.find(predicate);-}--function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {- const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();- return haystack.includes(keyword.toLowerCase());-}--function sleep(ms: number) {- return new Promise<void>((resolve) => {- // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test.- NodeTimers.setTimeout(resolve, ms);- });-}--class JsonRpcChild {- readonly child: NodeChildProcess.ChildProcessWithoutNullStreams;- readonly pending = new Map<JsonRpcId, PendingRequest>();- nextId = 1;- closed = false;-- constructor(bin: string, args: string[], cwd: string) {- const spawnCommand = Effect.runSync(resolveSpawnCommand(bin, args));- this.child = NodeChildProcess.spawn(spawnCommand.command, spawnCommand.args, {- cwd,- shell: spawnCommand.shell,- stdio: ["pipe", "pipe", "pipe"],- env: NodeProcess.env,- });-- this.child.on("exit", (code, signal) => {- this.closed = true;- const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;- for (const pending of this.pending.values()) {- pending.reject(new Error(`${detail} while waiting for ${pending.method}`));- }- this.pending.clear();- });-- this.child.on("error", (error) => {- this.closed = true;- for (const pending of this.pending.values()) {- pending.reject(error);- }- this.pending.clear();- });-- const stdout = NodeReadline.createInterface({ input: this.child.stdout });- stdout.on("line", (line) => {- void this.handleStdoutLine(line);- });-- const stderr = NodeReadline.createInterface({ input: this.child.stderr });- stderr.on("line", (line) => {- NodeProcess.stdout.write(`[stderr] ${line}\n`);- });- }-- write(message: JsonRpcMessage) {- if (this.closed) {- fail("ACP process is already closed.");- }- const payload = JSON.stringify({- jsonrpc: "2.0",- headers: [],- ...message,- });- NodeProcess.stdout.write(`>>> ${payload}\n`);- this.child.stdin.write(`${payload}\n`);- }-- async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {- const id = this.nextId++;-- const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {- // @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout.- const timeout = NodeTimers.setTimeout(() => {- this.pending.delete(id);- reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));- }, timeoutMs);-- this.pending.set(id, {- method,- resolve: (value) => {- NodeTimers.clearTimeout(timeout);- resolve(value);- },- reject: (error) => {- NodeTimers.clearTimeout(timeout);- reject(error);- },- });- });-- this.write({- id,- method,- params,- });-- return responsePromise;- }-- notify(method: string, params: JsonValue) {- this.write({- method,- params,- });- }-- respond(id: JsonRpcId, result: JsonValue) {- this.write({- id,- result,- });- }-- respondError(id: JsonRpcId, code: number, message: string) {- this.write({- id,- error: {- code,- message,- },- });- }-- async handleStdoutLine(line: string) {- if (line.trim().length === 0) {- return;- }-- NodeProcess.stdout.write(`<<< ${line}\n`);-- let message: JsonRpcMessage;- try {- message = JSON.parse(line) as JsonRpcMessage;- } catch (error) {- NodeProcess.stdout.write(`[parse-error] ${(error as Error).message}\n`);- return;- }-- if (typeof message.id !== "undefined" && !message.method) {- const pending = this.pending.get(message.id);- if (!pending) {- return;- }- this.pending.delete(message.id);- if (typeof message.error !== "undefined") {- pending.reject(- new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),- );- return;- }- pending.resolve(message.result);- return;- }-- if (message.method === "session/request_permission" && typeof message.id !== "undefined") {- this.respond(message.id, {- outcome: {- outcome: "selected",- optionId: "allow",- },- });- return;- }-- if (typeof message.id !== "undefined" && message.id !== "") {- this.respondError(- message.id,- -32601,- `Unhandled server request: ${message.method ?? "unknown"}`,- );- }- }-- async close() {- if (this.closed) {- return;- }- this.child.kill("SIGTERM");- await sleep(250);- if (!this.closed) {- this.child.kill("SIGKILL");- }- }-}--async function setSelectOptionIfAdvertised(- rpc: JsonRpcChild,- sessionId: string,- configOptions: SessionConfigOption[],- predicate: (option: SessionConfigOption) => boolean,- value: string,- label: string,-) {- if (value.length === 0) {- return configOptions;- }-- const option = findConfigOption(configOptions, predicate);- const values = flattenSelectValues(option);- if (!option || !values.includes(value)) {- logSection(`SKIP_${label}`, {- requestedValue: value,- availableValues: values,- });- return configOptions;- }-- const response = (await rpc.request("session/set_config_option", {- sessionId,- configId: option.id,- value,- })) as SetConfigResult | null | undefined;-- logSection(`SET_${label}_RESPONSE`, response);- return response?.configOptions ?? configOptions;-}--async function main() {- const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);-- try {- const initializeResponse = await rpc.request("initialize", {- protocolVersion: 1,- clientCapabilities: {- fs: { readTextFile: false, writeTextFile: false },- terminal: false,- _meta: {- parameterizedModelPicker: true,- },- },- clientInfo: {- name: "cursor-acp-model-mismatch-probe",- version: "0.0.0",- },- });- logSection("INITIALIZE_RESPONSE", initializeResponse);-- const authenticateResponse = await rpc.request("authenticate", {- methodId: "cursor_login",- });- logSection("AUTHENTICATE_RESPONSE", authenticateResponse);-- const sessionResponse = (await rpc.request("session/new", {- cwd: targetCwd,- mcpServers: [],- })) as SessionNewResult;- logSection("SESSION_NEW_RESPONSE", sessionResponse);-- const sessionId = asString(sessionResponse.sessionId);- if (!sessionId) {- fail("session/new did not return a sessionId.");- }-- let configOptions = sessionResponse.configOptions ?? [];- const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");- const advertisedModels = flattenSelectValues(modelConfig);- logSection("ADVERTISED_MODEL_VALUES", advertisedModels);-- if (!modelConfig || modelConfig.type !== "select") {- fail("Cursor ACP did not expose a select-type model config option.");- }-- if (!advertisedModels.includes(targetModel)) {- fail(- `Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,- );- }-- const setModelResponse = (await rpc.request("session/set_config_option", {- sessionId,- configId: modelConfig.id,- value: targetModel,- })) as SetConfigResult | null | undefined;- logSection("SET_MODEL_RESPONSE", setModelResponse);-- configOptions = setModelResponse?.configOptions ?? configOptions;-- configOptions = await setSelectOptionIfAdvertised(- rpc,- sessionId,- configOptions,- (option) => option.category === "thought_level",- targetReasoning,- "REASONING",- );-- configOptions = await setSelectOptionIfAdvertised(- rpc,- sessionId,- configOptions,- (option) => option.category === "model_config" && matchesKeyword(option, "context"),- targetContext,- "CONTEXT",- );-- configOptions = await setSelectOptionIfAdvertised(- rpc,- sessionId,- configOptions,- (option) => option.category === "model_config" && matchesKeyword(option, "fast"),- targetFast,- "FAST",- );-- const promptResponse = await rpc.request("session/prompt", {- sessionId,- prompt: [- {- type: "text",- text: promptText,- },- ],- });- logSection("PROMPT_RESPONSE", promptResponse);-- await sleep(promptWaitMs);- rpc.notify("session/cancel", { sessionId });- } finally {- await rpc.close();- }-}--void main().catch((error: unknown) => {- NodeProcess.stderr.write(- `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,- );- process.exitCode = 1;-});diff --git a/apps/server/src/bin.test.ts b/apps/server/src/bin.test.tsindex 4cccfc6a1a7..0deb261dbf9 100644--- a/apps/server/src/bin.test.ts+++ b/apps/server/src/bin.test.ts@@ -187,11 +187,19 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Efit.layer(NodeServices.layer)("bin cli parsing", (it) => {it.effect("accepts the built-in lowercase log-level flag values", () =>- runCliWithRuntime(["--log-level", "debug", "--version"]),+ Effect.gen(function* () {+ const { output } = yield* captureStdout(runCli(["--log-level", "debug", "--version"]));++ assert.include(output, "0.0.0");+ }),);it.effect("accepts canonical --no-<flag> boolean negation", () =>- runCliWithRuntime(["--no-log-websocket-events", "--version"]),+ Effect.gen(function* () {+ const { output } = yield* captureStdout(runCli(["--no-log-websocket-events", "--version"]));++ assert.include(output, "0.0.0");+ }),);it.effect("rejects invalid log-level casing before launching the server", () =>diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.tsindex 5b05b773b31..f739a4e2f22 100644--- a/apps/server/src/cli/config.ts+++ b/apps/server/src/cli/config.ts@@ -21,12 +21,12 @@ export const modeFlag = Flag.choice("mode", ServerConfig.RuntimeMode.literals).pFlag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),Flag.optional,);-export const portFlag = Flag.integer("port").pipe(+const portFlag = Flag.integer("port").pipe(Flag.withSchema(PortSchema),Flag.withDescription("Port for the HTTP/WebSocket server."),Flag.optional,);-export const hostFlag = Flag.string("host").pipe(+const hostFlag = Flag.string("host").pipe(Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),Flag.optional,);@@ -36,34 +36,34 @@ export const baseDirFlag = Flag.string("base-dir").pipe(),Flag.optional,);-export const devUrlFlag = Flag.string("dev-url").pipe(+const devUrlFlag = Flag.string("dev-url").pipe(Flag.withSchema(Schema.URLFromString),Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),Flag.optional,);-export const noBrowserFlag = Flag.boolean("no-browser").pipe(+const noBrowserFlag = Flag.boolean("no-browser").pipe(Flag.withDescription("Disable automatic browser opening."),Flag.optional,);-export const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(+const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(Flag.withSchema(Schema.Int),Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),Flag.optional,);-export const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(+const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(Flag.withDescription("Create a project for the current working directory on startup when missing.",),Flag.optional,);-export const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(+const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(Flag.withDescription("Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",),Flag.withAlias("log-ws-events"),Flag.optional,);-export const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(+const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(Flag.withDescription("Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",),@@ -161,7 +161,7 @@ export interface CliAuthLocationFlags {readonly devUrl?: Option.Option<URL>;}-export const sharedServerLocationFlags = {+export const authLocationFlags = {baseDir: baseDirFlag,devUrl: devUrlFlag,} as const;@@ -190,8 +190,6 @@ export const sharedServerCommandFlags = {tailscaleServePort: tailscaleServePortFlag,} as const;-export const authLocationFlags = sharedServerLocationFlags;-const resolveOptionPrecedence = <Value>(...values: ReadonlyArray<Option.Option<Value>>): Option.Option<Value> => Option.firstSomeOf(values);diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.tsindex 38fa3be8bb5..d40e0d97e48 100644--- a/apps/server/src/cli/pair.ts+++ b/apps/server/src/cli/pair.ts@@ -43,6 +43,7 @@ import * as ServerConfig from "../config.ts";import { resolveBaseDir } from "../os-jank.ts";import {type PersistedServerRuntimeState,+ isProcessAlive,readPersistedServerRuntimeState,} from "../serverRuntimeState.ts";import {@@ -229,17 +230,6 @@ const probeEnvironmentDescriptor = (return { _tag: "descriptor", descriptor } as const;}).pipe(Effect.catch((outcome) => Effect.succeed(outcome)));-// signal 0 delivers nothing; it only reports whether the pid exists. EPERM-// means it exists but belongs to another user, which still counts as alive.-const isProcessAlive = (pid: number): boolean => {- try {- process.kill(pid, 0);- return true;- } catch (error) {- return error instanceof Error && "code" in error && error.code === "EPERM";- }-};-interface DiscoveredPairTarget {readonly baseDir: string;readonly variant: PairStateVariant;diff --git a/apps/server/src/cli/triage.ts b/apps/server/src/cli/triage.tsindex 76d577a12c3..bcf5970310f 100644--- a/apps/server/src/cli/triage.ts+++ b/apps/server/src/cli/triage.ts@@ -29,7 +29,7 @@ import { Command, Flag } from "effect/unstable/cli";import packageJson from "../../package.json" with { type: "json" };import * as ServerConfig from "../config.ts";import { resolveBaseDir } from "../os-jank.ts";-import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";+import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";import { baseDirFlag } from "./config.ts";import { resolveCliCommand } from "./invocation.ts";import {@@ -76,17 +76,6 @@ export class TriageAgentSpawnError extends Schema.TaggedErrorClass<TriageAgentSp}}-// signal 0 delivers nothing; it only reports whether the pid exists. EPERM-// means it exists but belongs to another user, which still counts as alive.-const isProcessAlive = (pid: number): boolean => {- try {- process.kill(pid, 0);- return true;- } catch (error) {- return error instanceof Error && "code" in error && error.code === "EPERM";- }-};-/** One human-readable line about the local server, for `context.md`. */const describeServerProcess = Effect.fn("triage.describeServerProcess")(function* (serverRuntimeStatePath: string,diff --git a/apps/server/src/cloud/bootService.ts b/apps/server/src/cloud/bootService.tsindex 6b7e13d0bbb..969f45e6780 100644--- a/apps/server/src/cloud/bootService.ts+++ b/apps/server/src/cloud/bootService.ts@@ -30,19 +30,19 @@ import {} from "./serviceProtocol.ts";const BOOT_SERVICE_NAME = "t3code";-export const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;+const BOOT_SERVICE_UNIT_FILE = `${BOOT_SERVICE_NAME}.service`;// `.service` suffix keeps the label distinct from the desktop app's bundle id// (com.t3tools.t3code), so launchd and TCC records never collide.-export const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";-export const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;-export const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";+const BOOT_SERVICE_LAUNCHD_LABEL = "com.t3tools.t3code.service";+const BOOT_SERVICE_PLIST_FILE = `${BOOT_SERVICE_LAUNCHD_LABEL}.plist`;+const BOOT_SERVICE_UNIT_ENV = "T3_BOOT_SERVICE_UNIT";/** systemd expands `%` specifiers, including in unquoted append-log paths. */-export function escapeSystemdSpecifiers(value: string): string {+function escapeSystemdSpecifiers(value: string): string {return value.replaceAll("%", "%%");}-export function quoteSystemdValue(value: string): string {+function quoteSystemdValue(value: string): string {const escaped = escapeSystemdSpecifiers(value);return /[\s"'\\]/.test(escaped)? `"${escaped.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`@@ -92,7 +92,7 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {}/** Plist values are emitted as XML text nodes; only these three need escaping. */-export function escapeXmlText(value: string): string {+function escapeXmlText(value: string): string {return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");}@@ -199,7 +199,7 @@ export interface BootServiceManager {readonly finalize: ReadonlyArray<BootServiceStep>;}-export function systemdManager(input: {+function systemdManager(input: {readonly path: Path.Path;readonly homeDir: string;}): BootServiceManager {@@ -266,7 +266,7 @@ export function systemdManager(input: {};}-export function launchdManager(input: {+function launchdManager(input: {readonly path: Path.Path;readonly homeDir: string;readonly uid: number;@@ -348,7 +348,7 @@ export function launchdManager(input: {}/** Undefined means this host cannot run the background service. */-export function selectBootServiceManager(input: {+function selectBootServiceManager(input: {readonly platform: NodeJS.Platform;readonly homeDir: string;readonly uid: number | undefined;diff --git a/apps/server/src/httpCors.ts b/apps/server/src/httpCors.tsindex aeb8dbce5a5..3fdc165bab7 100644--- a/apps/server/src/httpCors.ts+++ b/apps/server/src/httpCors.ts@@ -6,9 +6,3 @@ export const browserApiCorsAllowedHeaders = ["content-type","dpop",] as const;--export const browserApiCorsHeaders = {- "access-control-allow-origin": "*",- "access-control-allow-methods": browserApiCorsAllowedMethods.join(", "),- "access-control-allow-headers": browserApiCorsAllowedHeaders.join(", "),-} as const;diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.tsindex 10d98bf6429..1795808bc17 100644--- a/apps/server/src/keybindings.ts+++ b/apps/server/src/keybindings.ts@@ -96,10 +96,6 @@ export const ResolvedKeybindingFromConfig = KeybindingRule.pipe(),);-export const ResolvedKeybindingsFromConfig = Schema.Array(ResolvedKeybindingFromConfig).check(- Schema.isMaxLength(MAX_KEYBINDINGS_COUNT),-);-function isSameKeybindingRule(left: KeybindingRule, right: KeybindingRule): boolean {return (left.command === right.command &&diff --git a/apps/server/src/mcp/toolkits/preview/tools.ts b/apps/server/src/mcp/toolkits/preview/tools.tsindex 3baf56a7962..33528d8bb38 100644--- a/apps/server/src/mcp/toolkits/preview/tools.ts+++ b/apps/server/src/mcp/toolkits/preview/tools.ts@@ -33,12 +33,15 @@ const PreviewActionResult = Schema.Record(Schema.String, Schema.Never).annotate(description: "The preview action completed successfully.",});+/** Drives the real browser and can destroy page state. */const browserTool = <T extends Tool.Any>(tool: T): T =>tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;+/** Same open-world browser access, but the action does not destroy page state. */const safeBrowserTool = <T extends Tool.Any>(tool: T): T =>- browserTool(tool).annotate(Tool.Destructive, false) as T;+ tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, false) as T;+/** A safe browser action that only observes, so it is also repeatable. */const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.tsindex 8f1e3e89851..beaad93d5ee 100644--- a/apps/server/src/orchestration/commandInvariants.ts+++ b/apps/server/src/orchestration/commandInvariants.ts@@ -170,19 +170,3 @@ export function requireThreadAbsent(input: {),);}--export function requireNonNegativeInteger(input: {- readonly commandType: OrchestrationCommand["type"];- readonly field: string;- readonly value: number;-}): Effect.Effect<void, OrchestrationCommandInvariantError> {- if (Number.isInteger(input.value) && input.value >= 0) {- return Effect.void;- }- return Effect.fail(- invariantError(- input.commandType,- `${input.field} must be an integer greater than or equal to 0.`,- ),- );-}diff --git a/apps/server/src/pathExpansion.ts b/apps/server/src/pathExpansion.tsindex bacdaece0b1..ec3f03faa5b 100644--- a/apps/server/src/pathExpansion.ts+++ b/apps/server/src/pathExpansion.ts@@ -2,6 +2,8 @@import * as NodeOS from "node:os";import * as NodePath from "node:path";+import type * as Path from "effect/Path";+/*** Expand a leading `~` (or `~/…`, `~\…`) in a user-supplied path to the* current user's home directory. Spawned processes don't get shell@@ -22,3 +24,19 @@ export function expandHomePath(value: string): string {}return value;}++/**+ * Same expansion as `expandHomePath`, but joins with a caller-supplied+ * `Path.Path` service instead of `node:path`. Use this inside Effect code that+ * already has `Path.Path` in context so the platform layer stays in control of+ * separator handling.+ */+export function expandHomePathWith(value: string, path: Path.Path): string {+ if (value === "~") {+ return NodeOS.homedir();+ }+ if (value.startsWith("~/") || value.startsWith("~\\")) {+ return path.join(NodeOS.homedir(), value.slice(2));+ }+ return value;+}diff --git a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts b/apps/server/src/persistence/Layers/ProviderSessionRuntime.tsdeleted file mode 100644index 52e4f8f7408..00000000000--- a/apps/server/src/persistence/Layers/ProviderSessionRuntime.ts+++ /dev/null@@ -1,2 +0,0 @@-/** @deprecated Compatibility alias for the excluded orchestration integration harness. */-export { layer as ProviderSessionRuntimeRepositoryLive } from "../ProviderSessionRuntime.ts";diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.tsindex 8abbe87fce3..84b0d52eea7 100644--- a/apps/server/src/persistence/Migrations.ts+++ b/apps/server/src/persistence/Migrations.ts@@ -1,16 +1,15 @@/**- * MigrationsLive - Migration runner with inline loader+ * Migration runner with an inline loader.** Uses Migrator.make with fromRecord to define migrations inline.* All migrations are statically imported - no dynamic file system loading.*- * Migrations run automatically when the MigrationLayer is provided,- * ensuring the database schema is always up-to-date before the application starts.+ * `runMigrations` is called by the SQLite persistence layer at startup, so the+ * schema is always up to date before the application starts.*/import * as Migrator from "effect/unstable/sql/Migrator";import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";// Import all migrations staticallyimport Migration0001 from "./Migrations/001_OrchestrationEvents.ts";@@ -154,22 +153,3 @@ export const runMigrations = Effect.fn("runMigrations")(function* ({: Effect.log("Migrations ran successfully").pipe(Effect.annotateLogs({ migrations }));return executedMigrations;});--/**- * Layer that runs migrations when the layer is built.- *- * Use this to ensure migrations run before your application starts.- * Migrations are run automatically - no separate script is needed.- *- * @example- * ```typescript- * import { MigrationsLive } from "@acme/db/Migrations"- * import * as SqliteClient from "@acme/db/SqliteClient"- *- * // Migrations run automatically when SqliteClient is provided- * const AppLayer = MigrationsLive.pipe(- * Layer.provideMerge(SqliteClient.layer({ filename: "database.sqlite" }))- * )- * ```- */-export const MigrationsLive = Layer.effectDiscard(runMigrations());diff --git a/apps/server/src/provider/Drivers/ClaudeDriver.ts b/apps/server/src/provider/Drivers/ClaudeDriver.tsindex 571862c2a29..f1606bea7d7 100644--- a/apps/server/src/provider/Drivers/ClaudeDriver.ts+++ b/apps/server/src/provider/Drivers/ClaudeDriver.ts@@ -12,7 +12,7 @@** @module provider/Drivers/ClaudeDriver*/-import { ClaudeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";+import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Cache from "effect/Cache";import * as Duration from "effect/Duration";import * as Crypto from "effect/Crypto";@@ -43,7 +43,7 @@ import {type ProviderDriver,type ProviderInstance,} from "../ProviderDriver.ts";-import type { ServerProviderDraft } from "../providerSnapshot.ts";+import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,@@ -95,22 +95,6 @@ export type ClaudeDriverEnv =| ServerConfig| ServerSettingsService;-const withInstanceIdentity =- (input: {- readonly instanceId: ProviderInstance["instanceId"];- readonly displayName: string | undefined;- readonly accentColor: string | undefined;- readonly continuationGroupKey: string;- }) =>- (snapshot: ServerProviderDraft): ServerProvider => ({- ...snapshot,- instanceId: input.instanceId,- driver: DRIVER_KIND,- ...(input.displayName ? { displayName: input.displayName } : {}),- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- continuation: { groupKey: input.continuationGroupKey },- });-export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {driverKind: DRIVER_KIND,metadata: {@@ -143,6 +127,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv> = {const continuationGroupKey = yield* makeClaudeContinuationGroupKey(effectiveConfig);const stampIdentity = withInstanceIdentity({instanceId,+ driverKind: DRIVER_KIND,displayName,accentColor,continuationGroupKey,diff --git a/apps/server/src/provider/Drivers/CodexDriver.ts b/apps/server/src/provider/Drivers/CodexDriver.tsindex 80a848c7ce3..6bb14321a72 100644--- a/apps/server/src/provider/Drivers/CodexDriver.ts+++ b/apps/server/src/provider/Drivers/CodexDriver.ts@@ -21,7 +21,7 @@** @module provider/Drivers/CodexDriver*/-import { CodexSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";+import { CodexSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -41,7 +41,7 @@ import { ProviderEventLoggers } from "../Layers/ProviderEventLoggers.ts";import { makeManagedServerProvider } from "../makeManagedServerProvider.ts";import * as ModelManifest from "../ModelManifest.ts";import type { ProviderDriver, ProviderInstance } from "../ProviderDriver.ts";-import type { ServerProviderDraft } from "../providerSnapshot.ts";+import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,@@ -85,28 +85,6 @@ export type CodexDriverEnv =| ServerConfig| ServerSettingsService;-/**- * Stamp instance identity onto a `ServerProvider` snapshot produced by the- * driver-kind-only codex helpers. Once `buildServerProvider` in- * `providerSnapshot.ts` is widened to accept `instanceId`/`driver`, this- * wrapper disappears.- */-const withInstanceIdentity =- (input: {- readonly instanceId: ProviderInstance["instanceId"];- readonly displayName: string | undefined;- readonly accentColor: string | undefined;- readonly continuationGroupKey: string;- }) =>- (snapshot: ServerProviderDraft): ServerProvider => ({- ...snapshot,- instanceId: input.instanceId,- driver: DRIVER_KIND,- ...(input.displayName ? { displayName: input.displayName } : {}),- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- continuation: { groupKey: input.continuationGroupKey },- });-export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {driverKind: DRIVER_KIND,metadata: {@@ -127,6 +105,7 @@ export const CodexDriver: ProviderDriver<CodexSettings, CodexDriverEnv> = {const continuationIdentity = codexContinuationIdentity(homeLayout);const stampIdentity = withInstanceIdentity({instanceId,+ driverKind: DRIVER_KIND,displayName,accentColor,continuationGroupKey: continuationIdentity.continuationKey,diff --git a/apps/server/src/provider/Drivers/CursorDriver.ts b/apps/server/src/provider/Drivers/CursorDriver.tsindex 2101664d5cb..1187b6b0350 100644--- a/apps/server/src/provider/Drivers/CursorDriver.ts+++ b/apps/server/src/provider/Drivers/CursorDriver.ts@@ -11,7 +11,7 @@** @module provider/Drivers/CursorDriver*/-import { CursorSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";+import { CursorSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -38,7 +38,7 @@ import {type ProviderDriver,type ProviderInstance,} from "../ProviderDriver.ts";-import type { ServerProviderDraft } from "../providerSnapshot.ts";+import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {makeProviderMaintenanceCapabilities,@@ -75,22 +75,6 @@ export type CursorDriverEnv =| ServerConfig| ServerSettingsService;-const withInstanceIdentity =- (input: {- readonly instanceId: ProviderInstance["instanceId"];- readonly displayName: string | undefined;- readonly accentColor: string | undefined;- readonly continuationGroupKey: string;- }) =>- (snapshot: ServerProviderDraft): ServerProvider => ({- ...snapshot,- instanceId: input.instanceId,- driver: DRIVER_KIND,- ...(input.displayName ? { displayName: input.displayName } : {}),- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- continuation: { groupKey: input.continuationGroupKey },- });-export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {driverKind: DRIVER_KIND,metadata: {@@ -115,6 +99,7 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {});const stampIdentity = withInstanceIdentity({instanceId,+ driverKind: DRIVER_KIND,displayName,accentColor,continuationGroupKey: continuationIdentity.continuationKey,diff --git a/apps/server/src/provider/Drivers/GrokDriver.ts b/apps/server/src/provider/Drivers/GrokDriver.tsindex 0b4e957fe1b..32d6149c3b5 100644--- a/apps/server/src/provider/Drivers/GrokDriver.ts+++ b/apps/server/src/provider/Drivers/GrokDriver.ts@@ -1,4 +1,4 @@-import { GrokSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";+import { GrokSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -25,7 +25,7 @@ import {type ProviderDriver,type ProviderInstance,} from "../ProviderDriver.ts";-import type { ServerProviderDraft } from "../providerSnapshot.ts";+import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {makeManualOnlyProviderMaintenanceCapabilities,@@ -58,22 +58,6 @@ export type GrokDriverEnv =| ServerConfig| ServerSettingsService;-const withInstanceIdentity =- (input: {- readonly instanceId: ProviderInstance["instanceId"];- readonly displayName: string | undefined;- readonly accentColor: string | undefined;- readonly continuationGroupKey: string;- }) =>- (snapshot: ServerProviderDraft): ServerProvider => ({- ...snapshot,- instanceId: input.instanceId,- driver: DRIVER_KIND,- ...(input.displayName ? { displayName: input.displayName } : {}),- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- continuation: { groupKey: input.continuationGroupKey },- });-export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {driverKind: DRIVER_KIND,metadata: {@@ -97,6 +81,7 @@ export const GrokDriver: ProviderDriver<GrokSettings, GrokDriverEnv> = {});const stampIdentity = withInstanceIdentity({instanceId,+ driverKind: DRIVER_KIND,displayName,accentColor,continuationGroupKey: continuationIdentity.continuationKey,diff --git a/apps/server/src/provider/Drivers/OpenCodeDriver.ts b/apps/server/src/provider/Drivers/OpenCodeDriver.tsindex 58ccf591202..4ba0b858c62 100644--- a/apps/server/src/provider/Drivers/OpenCodeDriver.ts+++ b/apps/server/src/provider/Drivers/OpenCodeDriver.ts@@ -12,7 +12,7 @@** @module provider/Drivers/OpenCodeDriver*/-import { OpenCodeSettings, ProviderDriverKind, type ServerProvider } from "@t3tools/contracts";+import { OpenCodeSettings, ProviderDriverKind } from "@t3tools/contracts";import * as Crypto from "effect/Crypto";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -40,7 +40,7 @@ import {type ProviderDriver,type ProviderInstance,} from "../ProviderDriver.ts";-import type { ServerProviderDraft } from "../providerSnapshot.ts";+import { withInstanceIdentity } from "./instanceIdentity.ts";import { mergeProviderInstanceEnvironment } from "../ProviderInstanceEnvironment.ts";import {enrichProviderSnapshotWithVersionAdvisory,@@ -89,22 +89,6 @@ export type OpenCodeDriverEnv =| ServerConfig| ServerSettingsService;-const withInstanceIdentity =- (input: {- readonly instanceId: ProviderInstance["instanceId"];- readonly displayName: string | undefined;- readonly accentColor: string | undefined;- readonly continuationGroupKey: string;- }) =>- (snapshot: ServerProviderDraft): ServerProvider => ({- ...snapshot,- instanceId: input.instanceId,- driver: DRIVER_KIND,- ...(input.displayName ? { displayName: input.displayName } : {}),- ...(input.accentColor ? { accentColor: input.accentColor } : {}),- continuation: { groupKey: input.continuationGroupKey },- });-export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv> = {driverKind: DRIVER_KIND,metadata: {@@ -127,6 +111,7 @@ export const OpenCodeDriver: ProviderDriver<OpenCodeSettings, OpenCodeDriverEnv>});const stampIdentity = withInstanceIdentity({instanceId,+ driverKind: DRIVER_KIND,displayName,accentColor,continuationGroupKey: continuationIdentity.continuationKey,diff --git a/apps/server/src/provider/Drivers/instanceIdentity.ts b/apps/server/src/provider/Drivers/instanceIdentity.tsnew file mode 100644index 00000000000..2fbc1c4a9f0--- /dev/null+++ b/apps/server/src/provider/Drivers/instanceIdentity.ts@@ -0,0 +1,28 @@+import type { ProviderDriverKind, ServerProvider } from "@t3tools/contracts";++import type { ProviderInstance } from "../ProviderDriver.ts";+import type { ServerProviderDraft } from "../providerSnapshot.ts";++/**+ * Stamp instance identity onto a `ServerProvider` snapshot produced by the+ * driver-kind-only snapshot helpers. Every driver builds its snapshot without+ * knowing its own instance, so it pipes the draft through this stamper before+ * publishing. Once `buildServerProvider` in `providerSnapshot.ts` is widened to+ * accept `instanceId`/`driver`, this wrapper disappears.+ */+export const withInstanceIdentity =+ (input: {+ readonly instanceId: ProviderInstance["instanceId"];+ readonly driverKind: ProviderDriverKind;+ readonly displayName: string | undefined;+ readonly accentColor: string | undefined;+ readonly continuationGroupKey: string;+ }) =>+ (snapshot: ServerProviderDraft): ServerProvider => ({+ ...snapshot,+ instanceId: input.instanceId,+ driver: input.driverKind,+ ...(input.displayName ? { displayName: input.displayName } : {}),+ ...(input.accentColor ? { accentColor: input.accentColor } : {}),+ continuation: { groupKey: input.continuationGroupKey },+ });diff --git a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.tsindex fb75652e385..0cc4b6c93cb 100644--- a/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts+++ b/apps/server/src/provider/Layers/ProviderInstanceRegistryLive.ts@@ -411,24 +411,6 @@ export const makeProviderInstanceRegistry = <R>(input: {return { registry, mutator };});-/**- * Assemble a `ProviderInstanceRegistry` Layer bound to a fixed set of- * drivers and a pre-resolved `ProviderInstanceConfigMap`. Used by tests- * that want explicit control over the registry's source-of-truth without- * wiring up the settings watcher.- *- * Only exposes the public registry tag — hot-reload consumers should use- * `ProviderInstanceRegistryMutableLayer` (below) or the hydration layer.- */-export const ProviderInstanceRegistryLayer = <R>(input: {- readonly drivers: ReadonlyArray<AnyProviderDriver<R>>;- readonly configMap: ProviderInstanceConfigMap;-}): Layer.Layer<ProviderInstanceRegistry, never, R> =>- Layer.effect(- ProviderInstanceRegistry,- makeProviderInstanceRegistry(input).pipe(Effect.map((built) => built.registry)),- ) as Layer.Layer<ProviderInstanceRegistry, never, R>;-/*** Layer variant that also exposes the mutator tag. Consumed by* `ProviderInstanceRegistryHydrationLive` to reconcile on settingsdiff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.tsindex 310550c08f9..ff884b5f900 100644--- a/apps/server/src/provider/Layers/ProviderRegistry.ts+++ b/apps/server/src/provider/Layers/ProviderRegistry.ts@@ -148,30 +148,6 @@ export const mergeProviderSnapshot = (: {}),};-export const mergeProviderSnapshots = (- previousProviders: ReadonlyArray<ServerProvider>,- nextProviders: ReadonlyArray<ServerProvider>,-): ReadonlyArray<ServerProvider> => {- const mergedProviders = new Map(- previousProviders.map((provider) => [snapshotInstanceKey(provider), provider] as const),- );-- for (const provider of nextProviders) {- mergedProviders.set(- snapshotInstanceKey(provider),- mergeProviderSnapshot(mergedProviders.get(snapshotInstanceKey(provider)), provider),- );- }-- return orderProviderSnapshots([...mergedProviders.values()]);-};--export const selectProvidersByKind = (- providers: ReadonlyArray<ServerProvider>,- providerKinds: ReadonlySet<ProviderDriverKind>,-): ReadonlyArray<ServerProvider> =>- providers.filter((provider) => providerKinds.has(provider.driver));-export const haveProvidersChanged = (previousProviders: ReadonlyArray<ServerProvider>,nextProviders: ReadonlyArray<ServerProvider>,diff --git a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts b/apps/server/src/provider/Layers/ProviderSessionDirectory.tsindex 23075bd9a06..253a954d210 100644--- a/apps/server/src/provider/Layers/ProviderSessionDirectory.ts+++ b/apps/server/src/provider/Layers/ProviderSessionDirectory.ts@@ -195,7 +195,3 @@ export const ProviderSessionDirectoryLive = Layer.effect(ProviderSessionDirectory,makeProviderSessionDirectory,);--export function makeProviderSessionDirectoryLive() {- return Layer.effect(ProviderSessionDirectory, makeProviderSessionDirectory);-}diff --git a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.tsindex bd25e9815ae..4de5247ac16 100644--- a/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts+++ b/apps/server/src/provider/acp/AcpCoreRuntimeEvents.ts@@ -8,11 +8,15 @@ import {type ProviderRuntimeEvent,type RuntimeRequestId,type ThreadId,- type ToolLifecycleItemType,type TurnId,} from "@t3tools/contracts";-import type { AcpPermissionRequest, AcpPlanUpdate, AcpToolCallState } from "./AcpRuntimeModel.ts";+import {+ type AcpPermissionRequest,+ type AcpPlanUpdate,+ type AcpToolCallState,+ canonicalItemTypeFromAcpToolKind,+} from "./AcpRuntimeModel.ts";type AcpAdapterRawSource = Extract<RuntimeEventRawSource,@@ -44,22 +48,6 @@ function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonical}}-function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {- switch (kind) {- case "execute":- return "command_execution";- case "edit":- case "delete":- case "move":- return "file_change";- case "search":- case "fetch":- return "web_search";- default:- return "dynamic_tool_call";- }-}-function runtimeItemStatusFromAcpToolStatus(status: AcpToolCallState["status"],): "inProgress" | "completed" | "failed" | undefined {diff --git a/apps/server/src/provider/acp/AcpRuntimeModel.ts b/apps/server/src/provider/acp/AcpRuntimeModel.tsindex 8fd7af3c561..a81a2faf5e0 100644--- a/apps/server/src/provider/acp/AcpRuntimeModel.ts+++ b/apps/server/src/provider/acp/AcpRuntimeModel.ts@@ -430,7 +430,11 @@ function normalizeToolKind(kind: unknown): string | undefined {return typeof kind === "string" && kind.trim().length > 0 ? kind.trim() : undefined;}-function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {+/**+ * Map an ACP tool kind onto the canonical runtime item type used by the+ * thread activity model. Unknown kinds fall back to a generic tool call.+ */+export function canonicalItemTypeFromAcpToolKind(kind: string | undefined): ToolLifecycleItemType {switch (kind) {case "execute":return "command_execution";diff --git a/apps/server/src/provider/providerStatusCache.ts b/apps/server/src/provider/providerStatusCache.tsindex 2fe0424b4f5..abc625f1731 100644--- a/apps/server/src/provider/providerStatusCache.ts+++ b/apps/server/src/provider/providerStatusCache.ts@@ -1,5 +1,4 @@import {- type ProviderDriverKind,type ProviderInstanceId,type ServerProvider,ServerProvider as ServerProviderSchema,@@ -98,23 +97,6 @@ export const resolveProviderStatusCachePath = Effect.fn("resolveProviderStatusCa},);-/**- * Legacy kind-keyed path resolver retained for callers that still think in- * terms of `ProviderDriverKind`. Prefer `resolveProviderStatusCachePath` with an- * `instanceId`; new code should route through the instance registry.- *- * @deprecated use `resolveProviderStatusCachePath` with an instance id.- */-export const resolveLegacyProviderStatusCachePath = Effect.fn(- "resolveLegacyProviderStatusCachePath",-)(function* (input: {- readonly cacheDir: string;- readonly provider: ProviderDriverKind;-}): Effect.fn.Return<string, never, Path.Path> {- const path = yield* Path.Path;- return path.join(input.cacheDir, `${input.provider}.json`);-});-export const readProviderStatusCache = (filePath: string) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.tsindex e3f7e482b2e..fc5b2c9e545 100644--- a/apps/server/src/serverRuntimeStartup.test.ts+++ b/apps/server/src/serverRuntimeStartup.test.ts@@ -74,6 +74,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loaEffect.scoped(Effect.gen(function* () {const releaseCounts = yield* Deferred.make<void, never>();+ const countsStarted = yield* Deferred.make<void, never>();yield* ServerRuntimeStartup.launchStartupHeartbeat.pipe(Effect.provideService(ProjectionSnapshotQuery.ProjectionSnapshotQuery, {@@ -83,7 +84,8 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loagetArchivedShellSnapshot: () => Effect.die("unused"),getSnapshotSequence: () => Effect.die("unused"),getCounts: () =>- Deferred.await(releaseCounts).pipe(+ Deferred.succeed(countsStarted, undefined).pipe(+ Effect.andThen(Deferred.await(releaseCounts)),Effect.as({projectCount: 2,threadCount: 3,@@ -104,6 +106,13 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loaflush: Effect.void,}),);++ // The heartbeat is forked, so the caller is already back here while+ // getCounts is still parked. Awaiting countsStarted proves the forked+ // work really ran; releaseCounts staying incomplete proves the caller+ // never waited for it.+ yield* Deferred.await(countsStarted);+ assert.equal(yield* Deferred.isDone(releaseCounts), false);}),),);diff --git a/apps/server/src/serverRuntimeState.ts b/apps/server/src/serverRuntimeState.tsindex b32f3814547..c08e5a82902 100644--- a/apps/server/src/serverRuntimeState.ts+++ b/apps/server/src/serverRuntimeState.ts@@ -104,6 +104,21 @@ export const clearPersistedServerRuntimeState = (path: string) =>);});+/**+ * Report whether the pid recorded in a persisted runtime state is still+ * running. Signal 0 delivers nothing; it only reports whether the pid exists.+ * EPERM means it exists but belongs to another user, which still counts as+ * alive.+ */+export const isProcessAlive = (pid: number): boolean => {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error instanceof Error && "code" in error && error.code === "EPERM";+ }+};+export const readPersistedServerRuntimeState = (path: string) =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.test.ts b/apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.test.tsindex 21db25e7991..cacdd1a3cd9 100644--- a/apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.test.ts+++ b/apps/server/src/sourceControl/AzureDevOpsSourceControlProvider.test.ts@@ -115,20 +115,3 @@ it.effect("creates Azure DevOps PRs through provider-neutral input names", () =>});}),);--it.effect("uses Azure CLI repository detection for default branch lookup", () =>- Effect.gen(function* () {- let cwdInput: string | null = null;- const provider = yield* makeProvider({- getDefaultBranch: (input) => {- cwdInput = input.cwd;- return Effect.succeed("main");- },- });-- const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });-- assert.strictEqual(defaultBranch, "main");- assert.strictEqual(cwdInput, "/repo");- }),-);diff --git a/apps/server/src/sourceControl/BitbucketSourceControlProvider.test.ts b/apps/server/src/sourceControl/BitbucketSourceControlProvider.test.tsindex eeb4c8fbdd2..52a15547c57 100644--- a/apps/server/src/sourceControl/BitbucketSourceControlProvider.test.ts+++ b/apps/server/src/sourceControl/BitbucketSourceControlProvider.test.ts@@ -149,20 +149,3 @@ it.effect("creates Bitbucket PRs through provider-neutral input names", () =>});}),);--it.effect("uses Bitbucket API repository detection for default branch lookup", () =>- Effect.gen(function* () {- let cwdInput: string | null = null;- const provider = yield* makeProvider({- getDefaultBranch: (input) => {- cwdInput = input.cwd;- return Effect.succeed("main");- },- });-- const defaultBranch = yield* provider.getDefaultBranch({ cwd: "/repo" });-- assert.strictEqual(defaultBranch, "main");- assert.strictEqual(cwdInput, "/repo");- }),-);diff --git a/apps/server/src/sourceControl/SourceControlRepositoryService.ts b/apps/server/src/sourceControl/SourceControlRepositoryService.tsindex 1b46369e25c..b38fe3d5c30 100644--- a/apps/server/src/sourceControl/SourceControlRepositoryService.ts+++ b/apps/server/src/sourceControl/SourceControlRepositoryService.ts@@ -1,4 +1,3 @@-import * as NodeOS from "node:os";import * as Context from "effect/Context";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -20,6 +19,7 @@ import {} from "@t3tools/contracts";import { ServerConfig } from "../config.ts";+import { expandHomePathWith } from "../pathExpansion.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as SourceControlProviderRegistry from "./SourceControlProviderRegistry.ts";const isSourceControlRepositoryError = Schema.is(SourceControlRepositoryError);@@ -77,16 +77,6 @@ function selectRemoteUrl(}}-function expandHomePath(input: string, path: Path.Path): string {- if (input === "~") {- return NodeOS.homedir();- }- if (input.startsWith("~/") || input.startsWith("~\\")) {- return path.join(NodeOS.homedir(), input.slice(2));- }- return input;-}-export const make = Effect.gen(function* () {const config = yield* ServerConfig;const fileSystem = yield* FileSystem.FileSystem;@@ -137,7 +127,7 @@ export const make = Effect.gen(function* () {});}- return path.resolve(expandHomePath(trimmed, path));+ return path.resolve(expandHomePathWith(trimmed, path));},);diff --git a/apps/server/src/telemetry/Services/AnalyticsService.ts b/apps/server/src/telemetry/Services/AnalyticsService.tsdeleted file mode 100644index 879a1de7cdb..00000000000--- a/apps/server/src/telemetry/Services/AnalyticsService.ts+++ /dev/null@@ -1,2 +0,0 @@-// Compatibility shim for the intentionally excluded orchestration harness.-export { AnalyticsService } from "../AnalyticsService.ts";diff --git a/apps/server/src/textGeneration/TextGenerationPresets.ts b/apps/server/src/textGeneration/TextGenerationPresets.tsindex 70955742148..0f5d03480f4 100644--- a/apps/server/src/textGeneration/TextGenerationPresets.ts+++ b/apps/server/src/textGeneration/TextGenerationPresets.ts@@ -1,4 +1,4 @@-import type { TextGenerationPolicy, TextGenerationPolicyKind } from "./TextGenerationPolicy.ts";+import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";export const defaultTextGenerationPolicy: TextGenerationPolicy = {kind: "default",@@ -30,12 +30,3 @@ export const customTextGenerationPolicy = (inferRepositoryConventions: false,...overrides,});--export const textGenerationPresets: Record<- Exclude<TextGenerationPolicyKind, "custom">,- TextGenerationPolicy-> = {- default: defaultTextGenerationPolicy,- conventional_commits: conventionalCommitsTextGenerationPolicy,- repo_conventions: repositoryConventionsTextGenerationPolicy,-};diff --git a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts b/apps/server/src/textGeneration/TextGenerationPrompts.test.tsindex 7614cc9e00f..f382f9af092 100644--- a/apps/server/src/textGeneration/TextGenerationPrompts.test.ts+++ b/apps/server/src/textGeneration/TextGenerationPrompts.test.ts@@ -146,7 +146,7 @@ describe("buildBranchNamePrompt", () => {});describe("buildThreadTitlePrompt", () => {- it("includes the user message in the prompt", () => {+ it("includes the user message and the title guidance rules", () => {const result = buildThreadTitlePrompt({message: "Investigate reconnect regressions after session restore",});diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.tsindex 6cf4400c62e..9cff5345103 100644--- a/apps/server/src/vcs/GitVcsDriver.ts+++ b/apps/server/src/vcs/GitVcsDriver.ts@@ -30,7 +30,7 @@ import {type VcsStatusInput,type VcsStatusResult,} from "@t3tools/contracts";-import { makeGitVcsDriverCore } from "./GitVcsDriverCore.ts";+import { makeGitVcsDriverCore, splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts";import * as VcsDriver from "./VcsDriver.ts";import * as VcsProcess from "./VcsProcess.ts";@@ -347,17 +347,6 @@ const nowFreshness = Effect.fn("GitVcsDriver.nowFreshness")(function* () {};});-function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {- const parts = input.split("\0");- if (parts.length === 0) return [];-- if (truncated && parts[parts.length - 1]?.length) {- parts.pop();- }-- return parts.filter((value) => value.length > 0);-}-function chunkPathsForGitCheckIgnore(relativePaths: ReadonlyArray<string>): string[][] {const chunks: string[][] = [];let chunk: string[] = [];@@ -541,7 +530,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (? Effect.gen(function* () {const freshness = yield* nowFreshness();return {- paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),+ paths: splitNullSeparatedGitStdoutPaths(result),truncated: result.stdoutTruncated,freshness,};@@ -639,7 +628,7 @@ export const makeVcsDriverShape = Effect.fn("makeGitVcsDriverShape")(function* (});}- for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {+ for (const ignoredPath of splitNullSeparatedGitStdoutPaths(result)) {ignoredPaths.add(ignoredPath);}}diff --git a/apps/server/src/workspace/WorkspaceEntries.ts b/apps/server/src/workspace/WorkspaceEntries.tsindex 28a30481b1b..2cf45a1a9cd 100644--- a/apps/server/src/workspace/WorkspaceEntries.ts+++ b/apps/server/src/workspace/WorkspaceEntries.ts@@ -1,6 +1,5 @@// @effect-diagnostics nodeBuiltinImport:offimport * as NodeFSP from "node:fs/promises";-import * as NodeOS from "node:os";import * as Context from "effect/Context";import * as Effect from "effect/Effect";@@ -23,6 +22,7 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";import { isExplicitRelativePath, isWindowsAbsolutePath } from "@t3tools/shared/path";import { normalizeSearchQuery } from "@t3tools/shared/searchRanking";+import { expandHomePathWith } from "../pathExpansion.ts";import * as WorkspacePaths from "./WorkspacePaths.ts";import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts";@@ -103,16 +103,6 @@ export class WorkspaceEntries extends Context.Service<}>()("t3/workspace/WorkspaceEntries") {}-function expandHomePath(input: string, path: Path.Path): string {- if (input === "~") {- return NodeOS.homedir();- }- if (input.startsWith("~/") || input.startsWith("~\\")) {- return path.join(NodeOS.homedir(), input.slice(2));- }- return input;-}-const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(function* (input: FilesystemBrowseInput,path: Path.Path,@@ -127,7 +117,7 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fu}if (!isExplicitRelativePath(input.partialPath)) {- return path.resolve(expandHomePath(input.partialPath, path));+ return path.resolve(expandHomePathWith(input.partialPath, path));}if (!input.cwd) {@@ -135,7 +125,7 @@ const resolveBrowseTarget = Effect.fn("WorkspaceEntries.resolveBrowseTarget")(fupartialPath: input.partialPath,});}- return path.resolve(expandHomePath(input.cwd, path), input.partialPath);+ return path.resolve(expandHomePathWith(input.cwd, path), input.partialPath);});export const make = Effect.gen(function* () {diff --git a/apps/server/src/workspace/WorkspacePaths.ts b/apps/server/src/workspace/WorkspacePaths.tsindex 5acf6677cde..d9eb4cdf274 100644--- a/apps/server/src/workspace/WorkspacePaths.ts+++ b/apps/server/src/workspace/WorkspacePaths.ts@@ -6,7 +6,6 @@** @module WorkspacePaths*/-import * as NodeOS from "node:os";import * as Context from "effect/Context";import * as Effect from "effect/Effect";@@ -15,6 +14,8 @@ import * as Layer from "effect/Layer";import * as Path from "effect/Path";import * as Schema from "effect/Schema";+import { expandHomePathWith } from "../pathExpansion.ts";+export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass<WorkspaceRootNotExistsError>()("WorkspaceRootNotExistsError",{@@ -121,16 +122,6 @@ function toPosixRelativePath(input: string): string {return input.replaceAll("\\", "/");}-function expandHomePath(input: string, path: Path.Path): string {- if (input === "~") {- return NodeOS.homedir();- }- if (input.startsWith("~/") || input.startsWith("~\\")) {- return path.join(NodeOS.homedir(), input.slice(2));- }- return input;-}-export const make = Effect.gen(function* () {const fileSystem = yield* FileSystem.FileSystem;const path = yield* Path.Path;@@ -161,7 +152,7 @@ export const make = Effect.gen(function* () {const normalizeWorkspaceRoot: WorkspacePaths["Service"]["normalizeWorkspaceRoot"] = Effect.fn("WorkspacePaths.normalizeWorkspaceRoot",)(function* (workspaceRoot, options) {- const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path));+ const normalizedWorkspaceRoot = path.resolve(expandHomePathWith(workspaceRoot.trim(), path));let workspaceStat = yield* statWorkspaceRoot(workspaceRoot,normalizedWorkspaceRoot,diff --git a/apps/web/package.json b/apps/web/package.jsonindex 0a9723e1912..283024eca09 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -65,7 +65,6 @@"@vitejs/plugin-react": "^6.0.0","babel-plugin-react-compiler": "1.0.0","compression": "^1.8.1",- "msw": "2.12.11","tailwindcss": "^4.0.0","vite": "catalog:","vite-plus": "catalog:"diff --git a/apps/web/public/mockServiceWorker.js b/apps/web/public/mockServiceWorker.jsdeleted file mode 100644index 8fa9dca80ea..00000000000--- a/apps/web/public/mockServiceWorker.js+++ /dev/null@@ -1,349 +0,0 @@-/* eslint-disable */-/* tslint:disable */--/**- * Mock Service Worker.- * @see https://github.com/mswjs/msw- * - Please do NOT modify this file.- */--const PACKAGE_VERSION = '2.12.11'-const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'-const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')-const activeClientIds = new Set()--addEventListener('install', function () {- self.skipWaiting()-})--addEventListener('activate', function (event) {- event.waitUntil(self.clients.claim())-})--addEventListener('message', async function (event) {- const clientId = Reflect.get(event.source || {}, 'id')-- if (!clientId || !self.clients) {- return- }-- const client = await self.clients.get(clientId)-- if (!client) {- return- }-- const allClients = await self.clients.matchAll({- type: 'window',- })-- switch (event.data) {- case 'KEEPALIVE_REQUEST': {- sendToClient(client, {- type: 'KEEPALIVE_RESPONSE',- })- break- }-- case 'INTEGRITY_CHECK_REQUEST': {- sendToClient(client, {- type: 'INTEGRITY_CHECK_RESPONSE',- payload: {- packageVersion: PACKAGE_VERSION,- checksum: INTEGRITY_CHECKSUM,- },- })- break- }-- case 'MOCK_ACTIVATE': {- activeClientIds.add(clientId)-- sendToClient(client, {- type: 'MOCKING_ENABLED',- payload: {- client: {- id: client.id,- frameType: client.frameType,- },- },- })- break- }-- case 'CLIENT_CLOSED': {- activeClientIds.delete(clientId)-- const remainingClients = allClients.filter((client) => {- return client.id !== clientId- })-- // Unregister itself when there are no more clients- if (remainingClients.length === 0) {- self.registration.unregister()- }-- break- }- }-})--addEventListener('fetch', function (event) {- const requestInterceptedAt = Date.now()-- // Bypass navigation requests.- if (event.request.mode === 'navigate') {- return- }-- // Opening the DevTools triggers the "only-if-cached" request- // that cannot be handled by the worker. Bypass such requests.- if (- event.request.cache === 'only-if-cached' &&- event.request.mode !== 'same-origin'- ) {- return- }-- // Bypass all requests when there are no active clients.- // Prevents the self-unregistered worked from handling requests- // after it's been terminated (still remains active until the next reload).- if (activeClientIds.size === 0) {- return- }-- const requestId = crypto.randomUUID()- event.respondWith(handleRequest(event, requestId, requestInterceptedAt))-})--/**- * @param {FetchEvent} event- * @param {string} requestId- * @param {number} requestInterceptedAt- */-async function handleRequest(event, requestId, requestInterceptedAt) {- const client = await resolveMainClient(event)- const requestCloneForEvents = event.request.clone()- const response = await getResponse(- event,- client,- requestId,- requestInterceptedAt,- )-- // Send back the response clone for the "response:*" life-cycle events.- // Ensure MSW is active and ready to handle the message, otherwise- // this message will pend indefinitely.- if (client && activeClientIds.has(client.id)) {- const serializedRequest = await serializeRequest(requestCloneForEvents)-- // Clone the response so both the client and the library could consume it.- const responseClone = response.clone()-- sendToClient(- client,- {- type: 'RESPONSE',- payload: {- isMockedResponse: IS_MOCKED_RESPONSE in response,- request: {- id: requestId,- ...serializedRequest,- },- response: {- type: responseClone.type,- status: responseClone.status,- statusText: responseClone.statusText,- headers: Object.fromEntries(responseClone.headers.entries()),- body: responseClone.body,- },- },- },- responseClone.body ? [serializedRequest.body, responseClone.body] : [],- )- }-- return response-}--/**- * Resolve the main client for the given event.- * Client that issues a request doesn't necessarily equal the client- * that registered the worker. It's with the latter the worker should- * communicate with during the response resolving phase.- * @param {FetchEvent} event- * @returns {Promise<Client | undefined>}- */-async function resolveMainClient(event) {- const client = await self.clients.get(event.clientId)-- if (activeClientIds.has(event.clientId)) {- return client- }-- if (client?.frameType === 'top-level') {- return client- }-- const allClients = await self.clients.matchAll({- type: 'window',- })-- return allClients- .filter((client) => {- // Get only those clients that are currently visible.- return client.visibilityState === 'visible'- })- .find((client) => {- // Find the client ID that's recorded in the- // set of clients that have registered the worker.- return activeClientIds.has(client.id)- })-}--/**- * @param {FetchEvent} event- * @param {Client | undefined} client- * @param {string} requestId- * @param {number} requestInterceptedAt- * @returns {Promise<Response>}- */-async function getResponse(event, client, requestId, requestInterceptedAt) {- // Clone the request because it might've been already used- // (i.e. its body has been read and sent to the client).- const requestClone = event.request.clone()-- function passthrough() {- // Cast the request headers to a new Headers instance- // so the headers can be manipulated with.- const headers = new Headers(requestClone.headers)-- // Remove the "accept" header value that marked this request as passthrough.- // This prevents request alteration and also keeps it compliant with the- // user-defined CORS policies.- const acceptHeader = headers.get('accept')- if (acceptHeader) {- const values = acceptHeader.split(',').map((value) => value.trim())- const filteredValues = values.filter(- (value) => value !== 'msw/passthrough',- )-- if (filteredValues.length > 0) {- headers.set('accept', filteredValues.join(', '))- } else {- headers.delete('accept')- }- }-- return fetch(requestClone, { headers })- }-- // Bypass mocking when the client is not active.- if (!client) {- return passthrough()- }-- // Bypass initial page load requests (i.e. static assets).- // The absence of the immediate/parent client in the map of the active clients- // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet- // and is not ready to handle requests.- if (!activeClientIds.has(client.id)) {- return passthrough()- }-- // Notify the client that a request has been intercepted.- const serializedRequest = await serializeRequest(event.request)- const clientMessage = await sendToClient(- client,- {- type: 'REQUEST',- payload: {- id: requestId,- interceptedAt: requestInterceptedAt,- ...serializedRequest,- },- },- [serializedRequest.body],- )-- switch (clientMessage.type) {- case 'MOCK_RESPONSE': {- return respondWithMock(clientMessage.data)- }-- case 'PASSTHROUGH': {- return passthrough()- }- }-- return passthrough()-}--/**- * @param {Client} client- * @param {any} message- * @param {Array<Transferable>} transferrables- * @returns {Promise<any>}- */-function sendToClient(client, message, transferrables = []) {- return new Promise((resolve, reject) => {- const channel = new MessageChannel()-- channel.port1.onmessage = (event) => {- if (event.data && event.data.error) {- return reject(event.data.error)- }-- resolve(event.data)- }-- client.postMessage(message, [- channel.port2,- ...transferrables.filter(Boolean),- ])- })-}--/**- * @param {Response} response- * @returns {Response}- */-function respondWithMock(response) {- // Setting response status code to 0 is a no-op.- // However, when responding with a "Response.error()", the produced Response- // instance will have status code set to 0. Since it's not possible to create- // a Response instance with status code 0, handle that use-case separately.- if (response.status === 0) {- return Response.error()- }-- const mockedResponse = new Response(response.body, response)-- Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {- value: true,- enumerable: true,- })-- return mockedResponse-}--/**- * @param {Request} request- */-async function serializeRequest(request) {- return {- url: request.url,- mode: request.mode,- method: request.method,- headers: Object.fromEntries(request.headers.entries()),- cache: request.cache,- credentials: request.credentials,- destination: request.destination,- integrity: request.integrity,- redirect: request.redirect,- referrer: request.referrer,- referrerPolicy: request.referrerPolicy,- body: await request.arrayBuffer(),- keepalive: request.keepalive,- }-}diff --git a/apps/web/src/components/SplashScreen.tsx b/apps/web/src/components/SplashScreen.tsxdeleted file mode 100644index a0b593a9507..00000000000--- a/apps/web/src/components/SplashScreen.tsx+++ /dev/null@@ -1,9 +0,0 @@-export function SplashScreen() {- return (- <div className="flex min-h-screen items-center justify-center bg-background">- <div className="flex size-24 items-center justify-center" aria-label="T3 Code splash screen">- <img alt="T3 Code" className="size-16 object-contain" src="/apple-touch-icon.png" />- </div>- </div>- );-}diff --git a/apps/web/src/components/ui/button.test.tsx b/apps/web/src/components/ui/button.test.tsxdeleted file mode 100644index 3faddf29d04..00000000000--- a/apps/web/src/components/ui/button.test.tsx+++ /dev/null@@ -1,54 +0,0 @@-import { renderToStaticMarkup } from "react-dom/server";-import { describe, expect, it } from "vite-plus/test";-import { FlaskConicalIcon } from "lucide-react";--import { Button } from "./button";--describe("button geometry tokens", () => {- it("uses the shared control radius and an opaque semantic icon color", () => {- const html = renderToStaticMarkup(- <Button size="icon-xs" variant="outline" aria-label="Run tests">- <FlaskConicalIcon />- </Button>,- );-- expect(html).toContain("rounded-[var(--control-radius)]");- expect(html).toContain("[--control-icon-color:var(--contrast-muted-foreground)]");- expect(html).toContain("text-[var(--control-icon-color)]");- expect(html).not.toContain("opacity-80");- });-- it("keeps compact icon buttons square at every breakpoint", () => {- const html = renderToStaticMarkup(- <Button size="icon-xs" aria-label="Add action">- <span>+</span>- </Button>,- );-- expect(html).toContain("size-7");- expect(html).toContain("sm:size-6");- });-- it("owns shared compact and micro control geometry", () => {- const compact = renderToStaticMarkup(<Button size="compact">Condition</Button>);- const microLabel = renderToStaticMarkup(- <Button size="micro">- <FlaskConicalIcon /> Run- </Button>,- );- const micro = renderToStaticMarkup(- <Button size="icon-micro" variant="ghost-muted" aria-label="Add action">- <span>+</span>- </Button>,- );-- expect(compact).toContain("h-7");- expect(compact).toContain("rounded-md");- expect(microLabel).toContain("text-[11px]");- expect(microLabel).toContain("sm:text-[11px]");- expect(microLabel).toContain("sm:[&_svg:not([class*='size-'])]:size-3");- expect(micro).toContain("size-5");- expect(micro).toContain("rounded-sm");- expect(micro).toContain("text-muted-foreground");- });-});diff --git a/apps/web/src/components/ui/card.tsx b/apps/web/src/components/ui/card.tsxdeleted file mode 100644index f1428d13d90..00000000000--- a/apps/web/src/components/ui/card.tsx+++ /dev/null@@ -1,196 +0,0 @@-"use client";--import { mergeProps } from "@base-ui/react/merge-props";-import { useRender } from "@base-ui/react/use-render";--import { cn } from "~/lib/utils";--function Card({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "relative flex flex-col rounded-2xl border bg-card not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)]",- className,- ),- "data-slot": "card",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFrame({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "[--clip-top:-1rem] [--clip-bottom:-1rem] *:data-[slot=card]:first:[--clip-top:1px] *:data-[slot=card]:last:[--clip-bottom:1px] flex flex-col relative rounded-2xl border bg-card before:bg-muted/72 not-dark:bg-clip-padding text-card-foreground shadow-xs/5 before:pointer-events-none before:absolute before:inset-0 before:rounded-[calc(var(--radius-2xl)-1px)] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] *:data-[slot=card]:-m-px *:not-last:data-[slot=card]:rounded-b-xl *:not-last:data-[slot=card]:before:rounded-b-[calc(var(--radius-xl)-1px)] *:not-first:data-[slot=card]:rounded-t-xl *:not-first:data-[slot=card]:before:rounded-t-[calc(var(--radius-xl)-1px)] *:data-[slot=card]:[clip-path:inset(var(--clip-top)_1px_var(--clip-bottom)_1px_round_calc(var(--radius-2xl)-1px))] *:data-[slot=card]:shadow-none *:data-[slot=card]:before:hidden *:data-[slot=card]:bg-clip-padding",- className,- ),- "data-slot": "card-frame",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFrameHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("relative flex flex-col px-6 py-4", className),- "data-slot": "card-frame-header",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFrameTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("font-semibold text-sm", className),- "data-slot": "card-frame-title",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFrameDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("text-muted-foreground text-sm", className),- "data-slot": "card-frame-description",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFrameFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("px-6 py-4", className),- "data-slot": "card-frame-footer",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardHeader({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pb-4 has-data-[slot=card-action]:grid-cols-[1fr_auto]",- className,- ),- "data-slot": "card-header",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardTitle({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("font-semibold text-lg leading-none", className),- "data-slot": "card-title",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardDescription({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn("text-muted-foreground text-sm", className),- "data-slot": "card-description",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardAction({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "col-start-2 row-span-2 row-start-1 self-start justify-self-end inline-flex",- className,- ),- "data-slot": "card-action",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardPanel({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "flex-1 p-6 in-[[data-slot=card]:has(>[data-slot=card-header]:not(.border-b))]:pt-0 in-[[data-slot=card]:has(>[data-slot=card-footer]:not(.border-t))]:pb-0",- className,- ),- "data-slot": "card-panel",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--function CardFooter({ className, render, ...props }: useRender.ComponentProps<"div">) {- const defaultProps = {- className: cn(- "flex items-center p-6 in-[[data-slot=card]:has(>[data-slot=card-panel])]:pt-4",- className,- ),- "data-slot": "card-footer",- };-- return useRender({- defaultTagName: "div",- props: mergeProps<"div">(defaultProps, props),- render,- });-}--export {- Card,- CardFrame,- CardFrameHeader,- CardFrameTitle,- CardFrameDescription,- CardFrameFooter,- CardAction,- CardDescription,- CardFooter,- CardHeader,- CardPanel,- CardPanel as CardContent,- CardTitle,-};diff --git a/apps/web/src/components/ui/field.tsx b/apps/web/src/components/ui/field.tsxdeleted file mode 100644index 1bf65b6c804..00000000000--- a/apps/web/src/components/ui/field.tsx+++ /dev/null@@ -1,59 +0,0 @@-"use client";--import { Field as FieldPrimitive } from "@base-ui/react/field";--import { cn } from "~/lib/utils";--function Field({ className, ...props }: FieldPrimitive.Root.Props) {- return (- <FieldPrimitive.Root- className={cn("flex flex-col items-start gap-2", className)}- data-slot="field"- {...props}- />- );-}--function FieldLabel({ className, ...props }: FieldPrimitive.Label.Props) {- return (- <FieldPrimitive.Label- className={cn(- "inline-flex items-center gap-2 font-medium text-base/4.5 text-foreground sm:text-sm/4",- className,- )}- data-slot="field-label"- {...props}- />- );-}--function FieldItem({ className, ...props }: FieldPrimitive.Item.Props) {- return (- <FieldPrimitive.Item className={cn("flex", className)} data-slot="field-item" {...props} />- );-}--function FieldDescription({ className, ...props }: FieldPrimitive.Description.Props) {- return (- <FieldPrimitive.Description- className={cn("text-muted-foreground text-xs", className)}- data-slot="field-description"- {...props}- />- );-}--function FieldError({ className, ...props }: FieldPrimitive.Error.Props) {- return (- <FieldPrimitive.Error- className={cn("text-destructive-foreground text-xs", className)}- data-slot="field-error"- {...props}- />- );-}--const FieldControl = FieldPrimitive.Control;-const FieldValidity = FieldPrimitive.Validity;--export { Field, FieldLabel, FieldDescription, FieldError, FieldControl, FieldItem, FieldValidity };diff --git a/apps/web/src/components/ui/fieldset.tsx b/apps/web/src/components/ui/fieldset.tsxdeleted file mode 100644index 23763b98242..00000000000--- a/apps/web/src/components/ui/fieldset.tsx+++ /dev/null@@ -1,26 +0,0 @@-"use client";--import { Fieldset as FieldsetPrimitive } from "@base-ui/react/fieldset";--import { cn } from "~/lib/utils";--function Fieldset({ className, ...props }: FieldsetPrimitive.Root.Props) {- return (- <FieldsetPrimitive.Root- className={cn("flex w-full max-w-64 flex-col gap-6", className)}- data-slot="fieldset"- {...props}- />- );-}-function FieldsetLegend({ className, ...props }: FieldsetPrimitive.Legend.Props) {- return (- <FieldsetPrimitive.Legend- className={cn("font-semibold text-foreground", className)}- data-slot="fieldset-legend"- {...props}- />- );-}--export { Fieldset, FieldsetLegend };diff --git a/apps/web/src/components/ui/form.tsx b/apps/web/src/components/ui/form.tsxdeleted file mode 100644index 641fc2ee627..00000000000--- a/apps/web/src/components/ui/form.tsx+++ /dev/null@@ -1,17 +0,0 @@-"use client";--import { Form as FormPrimitive } from "@base-ui/react/form";--import { cn } from "~/lib/utils";--function Form({ className, ...props }: FormPrimitive.Props) {- return (- <FormPrimitive- className={cn("flex w-full flex-col gap-4", className)}- data-slot="form"- {...props}- />- );-}--export { Form };diff --git a/apps/web/src/environments/primary/context.ts b/apps/web/src/environments/primary/context.tsindex e1021a7feb4..48017ac29e3 100644--- a/apps/web/src/environments/primary/context.ts+++ b/apps/web/src/environments/primary/context.ts@@ -95,12 +95,7 @@ export function resolveInitialPrimaryEnvironmentDescriptor(): Promise<ExecutionE});}-export function __resetPrimaryEnvironmentBootstrapForTests(): void {+export function resetPrimaryEnvironmentDescriptorForTests(): void {primaryEnvironmentDescriptorPromise = null;primaryEnvironmentDescriptor = null;}--export const resetPrimaryEnvironmentDescriptorForTests = __resetPrimaryEnvironmentBootstrapForTests;--export const __resetPrimaryEnvironmentDescriptorBootstrapForTests =- __resetPrimaryEnvironmentBootstrapForTests;diff --git a/apps/web/src/environments/primary/index.ts b/apps/web/src/environments/primary/index.tsindex f85c91c1536..e9b15527ea5 100644--- a/apps/web/src/environments/primary/index.ts+++ b/apps/web/src/environments/primary/index.ts@@ -4,8 +4,6 @@ export {resetPrimaryEnvironmentDescriptorForTests,resolveInitialPrimaryEnvironmentDescriptor,writePrimaryEnvironmentDescriptor,- __resetPrimaryEnvironmentBootstrapForTests,- __resetPrimaryEnvironmentDescriptorBootstrapForTests,} from "./context";export {diff --git a/apps/web/src/historyBootstrap.ts b/apps/web/src/historyBootstrap.tsdeleted file mode 100644index b6a2570f0d9..00000000000--- a/apps/web/src/historyBootstrap.ts+++ /dev/null@@ -1,139 +0,0 @@-import type { ChatMessage } from "./types";--export interface BootstrapInputResult {- text: string;- includedCount: number;- omittedCount: number;- truncated: boolean;-}--const BOOTSTRAP_PREAMBLE =- "Continue this conversation using the transcript context below. The final section is the latest user request to answer now.";-const TRANSCRIPT_HEADER = "Transcript context:";-const LATEST_PROMPT_HEADER = "Latest user request (answer this now):";-const OMITTED_SUMMARY = (count: number) =>- `[${count} earlier message(s) omitted to stay within input limits.]`;--function messageRoleLabel(message: ChatMessage): "USER" | "ASSISTANT" {- return message.role === "assistant" ? "ASSISTANT" : "USER";-}--function attachmentSummary(message: ChatMessage): string | null {- const imageAttachments = message.attachments?.filter((attachment) => attachment.type === "image");- const count = imageAttachments?.length ?? 0;- if (count === 0) {- return null;- }-- const names = imageAttachments?.slice(0, 3).map((image) => image.name) ?? [];- const namesSummary = names.join(", ");- const extraCount = count - names.length;- const extraSummary = extraCount > 0 ? ` (+${extraCount} more)` : "";- return `[Attached image${count === 1 ? "" : "s"}: ${namesSummary}${extraSummary}]`;-}--function buildMessageBlock(message: ChatMessage): string {- const text = message.text;- const attachments = attachmentSummary(message);-- if (text && attachments) {- return `${messageRoleLabel(message)}:\n${text}\n${attachments}`;- }- if (text) {- return `${messageRoleLabel(message)}:\n${text}`;- }- if (attachments) {- return `${messageRoleLabel(message)}:\n${attachments}`;- }- return `${messageRoleLabel(message)}:\n(empty message)`;-}--function finalizeWithPrompt(- transcriptBody: string,- latestPrompt: string,- maxChars: number,-): string | null {- const text = `${BOOTSTRAP_PREAMBLE}\n\n${TRANSCRIPT_HEADER}\n${transcriptBody}\n\n${LATEST_PROMPT_HEADER}\n${latestPrompt}`;- return text.length <= maxChars ? text : null;-}--export function buildBootstrapInput(- previousMessages: ChatMessage[],- latestPrompt: string,- maxChars: number,-): BootstrapInputResult {- const budget = Number.isFinite(maxChars) ? Math.max(1, Math.floor(maxChars)) : 1;- const promptOnly = latestPrompt.length <= budget ? latestPrompt : latestPrompt.slice(0, budget);-- if (previousMessages.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: 0,- truncated: promptOnly.length !== latestPrompt.length,- };- }-- const newestFirstBlocks: string[] = [];- for (let index = previousMessages.length - 1; index >= 0; index -= 1) {- const message = previousMessages[index];- if (!message) continue;- newestFirstBlocks.push(buildMessageBlock(message));- }-- if (newestFirstBlocks.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: previousMessages.length,- truncated: true,- };- }-- // Include a contiguous suffix from newest to oldest, then reverse to chronological.- let includedNewestFirst: string[] = [];- for (const block of newestFirstBlocks) {- const nextNewestFirst = [...includedNewestFirst, block];- const nextChronological = nextNewestFirst.toReversed();- const omittedCount = newestFirstBlocks.length - nextChronological.length;- const transcriptBody =- omittedCount > 0- ? `${OMITTED_SUMMARY(omittedCount)}\n\n${nextChronological.join("\n\n")}`- : nextChronological.join("\n\n");- if (!finalizeWithPrompt(transcriptBody, latestPrompt, budget)) {- break;- }- includedNewestFirst = nextNewestFirst;- }-- let includedChronological = includedNewestFirst.toReversed();- while (true) {- const omittedCount = newestFirstBlocks.length - includedChronological.length;- const transcriptBody =- omittedCount > 0- ? includedChronological.length > 0- ? `${OMITTED_SUMMARY(omittedCount)}\n\n${includedChronological.join("\n\n")}`- : OMITTED_SUMMARY(omittedCount)- : includedChronological.join("\n\n");- const finalized = finalizeWithPrompt(transcriptBody, latestPrompt, budget);- if (finalized) {- return {- text: finalized,- includedCount: includedChronological.length,- omittedCount,- truncated: omittedCount > 0 || latestPrompt.length !== promptOnly.length,- };- }-- if (includedChronological.length === 0) {- return {- text: promptOnly,- includedCount: 0,- omittedCount: previousMessages.length,- truncated: true,- };- }-- includedChronological = includedChronological.slice(1);- }-}diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.tsindex 39ec7a70ce4..928b597f41d 100644--- a/apps/web/src/hooks/useSettings.ts+++ b/apps/web/src/hooks/useSettings.ts@@ -359,19 +359,3 @@ export function useUpdateClientSettings() {});}, []);}--export function __resetClientSettingsPersistenceForTests(): void {- clientSettingsHydrationGeneration += 1;- clientSettingsSnapshot = DEFAULT_CLIENT_SETTINGS;- clientSettingsHydrated = false;- clientSettingsHydrationPromise = null;- clientSettingsListeners.clear();- clientSettingsHydrationListeners.clear();-}--export function __setClientSettingsForTests(settings: ClientSettings): void {- clientSettingsHydrationGeneration += 1;- clientSettingsSnapshot = settings;- clientSettingsHydrated = true;- clientSettingsHydrationPromise = null;-}diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex b58584291b4..22396d4f8ae 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -206,7 +206,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil--radius-xl: calc(var(--radius) + 4px);--radius-2xl: calc(var(--radius) + 8px);--radius-3xl: calc(var(--radius) + 12px);- --radius-4xl: calc(var(--radius) + 16px);@keyframes skeleton {/* Transform-only so the highlight sweep stays on the compositor, then along hold with the band parked off-screen instead of a constant shimmer. */diff --git a/apps/web/src/lib/terminalUiStateCleanup.ts b/apps/web/src/lib/terminalUiStateCleanup.tsdeleted file mode 100644index 8535f29f1d0..00000000000--- a/apps/web/src/lib/terminalUiStateCleanup.ts+++ /dev/null@@ -1,33 +0,0 @@-interface TerminalUiRetentionThread {- key: string;- deletedAt: string | null;- archivedAt: string | null;-}--interface CollectActiveTerminalUiThreadKeysInput {- snapshotThreads: readonly TerminalUiRetentionThread[];- draftThreadKeys: Iterable<string>;-}--export function collectActiveTerminalUiThreadKeys(- input: CollectActiveTerminalUiThreadKeysInput,-): Set<string> {- const activeThreadKeys = new Set<string>();- const snapshotThreadById = new Map(input.snapshotThreads.map((thread) => [thread.key, thread]));- for (const thread of input.snapshotThreads) {- if (thread.deletedAt !== null) continue;- if (thread.archivedAt !== null) continue;- activeThreadKeys.add(thread.key);- }- for (const draftThreadKey of input.draftThreadKeys) {- const snapshotThread = snapshotThreadById.get(draftThreadKey);- if (- snapshotThread &&- (snapshotThread.deletedAt !== null || snapshotThread.archivedAt !== null)- ) {- continue;- }- activeThreadKeys.add(draftThreadKey);- }- return activeThreadKeys;-}diff --git a/apps/web/src/localApi.ts b/apps/web/src/localApi.tsindex 863388106a3..8f55f65e40d 100644--- a/apps/web/src/localApi.ts+++ b/apps/web/src/localApi.ts@@ -3,7 +3,6 @@ import type { ConfirmDialogOptions, ContextMenuItem, LocalApi } from "@t3tools/cimport { requestConfirmDialog } from "./confirmDialog";import { dismissContextMenu, showContextMenuFallback } from "./contextMenuFallback";import { readBrowserClientSettings, writeBrowserClientSettings } from "./clientPersistenceStorage";-import { resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";let cachedApi: LocalApi | undefined;@@ -86,10 +85,3 @@ export function ensureLocalApi(): LocalApi {}return api;}--export async function __resetLocalApiForTests() {- cachedApi = undefined;- const { __resetClientSettingsPersistenceForTests } = await import("./hooks/useSettings");- __resetClientSettingsPersistenceForTests();- resetRequestLatencyStateForTests();-}diff --git a/apps/web/src/observability/clientTracing.ts b/apps/web/src/observability/clientTracing.tsindex 2d07e218e85..95d390b9002 100644--- a/apps/web/src/observability/clientTracing.ts+++ b/apps/web/src/observability/clientTracing.ts@@ -131,17 +131,3 @@ async function disposeTracerRuntime(await settleAsyncResult(() => runtime.runPromiseExit(Scope.close(scope, Exit.void)));runtime.dispose();}--export async function __resetClientTracingForTests() {- configurationGeneration++;- activeConfigKey = null;- activeDelegate = null;- pendingConfiguration = Promise.resolve();-- const runtime = activeRuntime;- const scope = activeScope;- activeRuntime = null;- activeScope = null;-- await disposeTracerRuntime(runtime, scope);-}diff --git a/apps/web/src/orchestrationEventEffects.ts b/apps/web/src/orchestrationEventEffects.tsdeleted file mode 100644index 34e33ace831..00000000000--- a/apps/web/src/orchestrationEventEffects.ts+++ /dev/null@@ -1,94 +0,0 @@-import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";--export interface OrchestrationBatchEffects {- promoteDraftThreadIds: ThreadId[];- clearDeletedThreadIds: ThreadId[];- removeTerminalUiStateThreadIds: ThreadId[];- needsProviderInvalidation: boolean;-}--export function deriveOrchestrationBatchEffects(- events: readonly OrchestrationEvent[],-): OrchestrationBatchEffects {- const threadLifecycleEffects = new Map<- ThreadId,- {- clearPromotedDraft: boolean;- clearDeletedThread: boolean;- removeTerminalUiState: boolean;- }- >();- let needsProviderInvalidation = false;-- for (const event of events) {- switch (event.type) {- case "thread.turn-diff-completed":- case "thread.reverted": {- needsProviderInvalidation = true;- break;- }-- case "thread.created": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: true,- clearDeletedThread: false,- removeTerminalUiState: false,- });- break;- }-- case "thread.deleted": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: true,- removeTerminalUiState: true,- });- break;- }-- case "thread.archived": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: false,- removeTerminalUiState: true,- });- break;- }-- case "thread.unarchived": {- threadLifecycleEffects.set(event.payload.threadId, {- clearPromotedDraft: false,- clearDeletedThread: false,- removeTerminalUiState: false,- });- break;- }-- default: {- break;- }- }- }-- const promoteDraftThreadIds: ThreadId[] = [];- const clearDeletedThreadIds: ThreadId[] = [];- const removeTerminalUiStateThreadIds: ThreadId[] = [];- for (const [threadId, effect] of threadLifecycleEffects) {- if (effect.clearPromotedDraft) {- promoteDraftThreadIds.push(threadId);- }- if (effect.clearDeletedThread) {- clearDeletedThreadIds.push(threadId);- }- if (effect.removeTerminalUiState) {- removeTerminalUiStateThreadIds.push(threadId);- }- }-- return {- promoteDraftThreadIds,- clearDeletedThreadIds,- removeTerminalUiStateThreadIds,- needsProviderInvalidation,- };-}diff --git a/apps/web/src/orchestrationRecovery.ts b/apps/web/src/orchestrationRecovery.tsdeleted file mode 100644index c9ccf3a393d..00000000000--- a/apps/web/src/orchestrationRecovery.ts+++ /dev/null@@ -1,211 +0,0 @@-export type OrchestrationRecoveryReason =- | "bootstrap"- | "sequence-gap"- | "resubscribe"- | "replay-failed";--export interface OrchestrationRecoveryPhase {- kind: "snapshot" | "replay";- reason: OrchestrationRecoveryReason;-}--export interface OrchestrationRecoveryState {- latestSequence: number;- highestObservedSequence: number;- bootstrapped: boolean;- pendingReplay: boolean;- inFlight: OrchestrationRecoveryPhase | null;-}--export interface ReplayRecoveryCompletion {- replayMadeProgress: boolean;- shouldReplay: boolean;-}--export interface ReplayRetryTracker {- attempts: number;- latestSequence: number;- highestObservedSequence: number;-}--export interface ReplayRetryDecision {- shouldRetry: boolean;- delayMs: number;- tracker: ReplayRetryTracker | null;-}--type SequencedEvent = Readonly<{ sequence: number }>;--export function deriveReplayRetryDecision(input: {- previousTracker: ReplayRetryTracker | null;- completion: ReplayRecoveryCompletion;- recoveryState: Pick<OrchestrationRecoveryState, "latestSequence" | "highestObservedSequence">;- baseDelayMs: number;- maxNoProgressRetries: number;-}): ReplayRetryDecision {- if (!input.completion.shouldReplay) {- return {- shouldRetry: false,- delayMs: 0,- tracker: null,- };- }-- if (input.completion.replayMadeProgress) {- return {- shouldRetry: true,- delayMs: 0,- tracker: null,- };- }-- const previousTracker = input.previousTracker;- const sameFrontier =- previousTracker !== null &&- previousTracker.latestSequence === input.recoveryState.latestSequence &&- previousTracker.highestObservedSequence === input.recoveryState.highestObservedSequence;-- const attempts = sameFrontier && previousTracker !== null ? previousTracker.attempts + 1 : 1;- if (attempts > input.maxNoProgressRetries) {- return {- shouldRetry: false,- delayMs: 0,- tracker: null,- };- }-- return {- shouldRetry: true,- delayMs: input.baseDelayMs * 2 ** (attempts - 1),- tracker: {- attempts,- latestSequence: input.recoveryState.latestSequence,- highestObservedSequence: input.recoveryState.highestObservedSequence,- },- };-}--export function createOrchestrationRecoveryCoordinator() {- let state: OrchestrationRecoveryState = {- latestSequence: 0,- highestObservedSequence: 0,- bootstrapped: false,- pendingReplay: false,- inFlight: null,- };- let replayStartSequence: number | null = null;-- const snapshotState = (): OrchestrationRecoveryState => ({- ...state,- ...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),- });-- const observeSequence = (sequence: number) => {- state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);- };-- const resolveReplayNeedAfterRecovery = () => {- const pendingReplayBeforeReset = state.pendingReplay;- const observedAhead = state.highestObservedSequence > state.latestSequence;- const shouldReplay = pendingReplayBeforeReset || observedAhead;- state.pendingReplay = false;- return {- shouldReplay,- pendingReplayBeforeReset,- observedAhead,- };- };-- return {- getState(): OrchestrationRecoveryState {- return snapshotState();- },-- classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {- observeSequence(sequence);- if (sequence <= state.latestSequence) {- return "ignore";- }- if (!state.bootstrapped || state.inFlight) {- state.pendingReplay = true;- return "defer";- }- if (sequence !== state.latestSequence + 1) {- state.pendingReplay = true;- return "recover";- }- return "apply";- },-- markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {- const nextEvents = events- .filter((event) => event.sequence > state.latestSequence)- .toSorted((left, right) => left.sequence - right.sequence);- if (nextEvents.length === 0) {- return [];- }-- state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;- state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);- return nextEvents;- },-- beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {- if (state.inFlight?.kind === "snapshot") {- state.pendingReplay = true;- return false;- }- if (state.inFlight?.kind === "replay") {- state.pendingReplay = true;- return false;- }- state.inFlight = { kind: "snapshot", reason };- return true;- },-- completeSnapshotRecovery(snapshotSequence: number): boolean {- state.latestSequence = Math.max(state.latestSequence, snapshotSequence);- state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);- state.bootstrapped = true;- state.inFlight = null;- return resolveReplayNeedAfterRecovery().shouldReplay;- },-- failSnapshotRecovery(): void {- state.inFlight = null;- },-- beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {- if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {- state.pendingReplay = true;- return false;- }- if (state.inFlight?.kind === "replay") {- state.pendingReplay = true;- return false;- }- state.pendingReplay = false;- replayStartSequence = state.latestSequence;- state.inFlight = { kind: "replay", reason };- return true;- },-- completeReplayRecovery(): ReplayRecoveryCompletion {- const replayMadeProgress =- replayStartSequence !== null && state.latestSequence > replayStartSequence;- replayStartSequence = null;- state.inFlight = null;- const replayResolution = resolveReplayNeedAfterRecovery();- return {- replayMadeProgress,- shouldReplay: replayResolution.shouldReplay,- };- },-- failReplayRecovery(): void {- replayStartSequence = null;- state.bootstrapped = false;- state.inFlight = null;- },- };-}diff --git a/apps/web/src/remoteOpen.ts b/apps/web/src/remoteOpen.tsindex c29f8d7389e..7f23d408844 100644--- a/apps/web/src/remoteOpen.ts+++ b/apps/web/src/remoteOpen.ts@@ -130,10 +130,6 @@ const REMOTE_FALLBACK_EDITORS: ReadonlyArray<EditorId> = ["vscode"];let cachedProbedEditors: ReadonlyArray<EditorId> | null = null;-export function __resetRemoteEditorProbeForTests(): void {- cachedProbedEditors = null;-}-export function useRemoteCapableEditors(): ReadonlyArray<EditorId> {const [editors, setEditors] = useState<ReadonlyArray<EditorId>>(() => cachedProbedEditors ?? REMOTE_FALLBACK_EDITORS,diff --git a/apps/web/src/rpc/atomRegistry.ts b/apps/web/src/rpc/atomRegistry.tsindex 3fb12914a2f..c9ac7ef82ba 100644--- a/apps/web/src/rpc/atomRegistry.ts+++ b/apps/web/src/rpc/atomRegistry.ts@@ -2,13 +2,8 @@ import { RegistryContext } from "@effect/atom-react";import { AtomRegistry } from "effect/unstable/reactivity";import { createElement } from "react";-export let appAtomRegistry = AtomRegistry.make();+export const appAtomRegistry = AtomRegistry.make();export function AppAtomRegistryProvider({ children }: React.PropsWithChildren) {return createElement(RegistryContext.Provider, { value: appAtomRegistry }, children);}--export function resetAppAtomRegistryForTests() {- appAtomRegistry.dispose();- appAtomRegistry = AtomRegistry.make();-}diff --git a/apps/web/src/rpc/requestLatencyState.ts b/apps/web/src/rpc/requestLatencyState.tsindex 4ec5b56f9e2..cb68a090775 100644--- a/apps/web/src/rpc/requestLatencyState.ts+++ b/apps/web/src/rpc/requestLatencyState.ts@@ -153,10 +153,6 @@ export function resetRequestLatencyStateForTests(): void {clearAllTrackedRpcRequests();}-export function setSlowRpcAckThresholdMsForTests(thresholdMs: number): void {- slowRpcAckThresholdMs = thresholdMs;-}-export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {return useAtomValue(slowRpcAckRequestsAtom);}diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.tsindex b6653793056..ec1e4c83621 100644--- a/apps/web/src/state/entities.ts+++ b/apps/web/src/state/entities.ts@@ -8,16 +8,8 @@ import {type EnvironmentThreadStatus,mergeEnvironmentThread,} from "@t3tools/client-runtime/state/threads";-import type {- OrchestrationMessage,- OrchestrationProposedPlan,- OrchestrationSession,- OrchestrationThreadActivity,- ScopedProjectRef,- ScopedThreadRef,- ServerConfig,-} from "@t3tools/contracts";-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import type { ScopedProjectRef, ScopedThreadRef, ServerConfig } from "@t3tools/contracts";+import type { EnvironmentId } from "@t3tools/contracts";import { Atom } from "effect/unstable/reactivity";import { useMemo } from "react";import { appAtomRegistry } from "../rpc/atomRegistry";@@ -26,18 +18,11 @@ import { environmentServerConfigsAtom } from "./server";import { allEnvironmentShellsBootstrappedAtom } from "./shell";import { environmentThreadDetails, environmentThreadShells } from "./threads";-const EMPTY_PROJECT_REFS: ReadonlyArray<ScopedProjectRef> = Object.freeze([]);const EMPTY_THREAD_REFS: ReadonlyArray<ScopedThreadRef> = Object.freeze([]);-const EMPTY_MESSAGES: ReadonlyArray<OrchestrationMessage> = Object.freeze([]);-const EMPTY_ACTIVITIES: ReadonlyArray<OrchestrationThreadActivity> = Object.freeze([]);-const EMPTY_PROPOSED_PLANS: ReadonlyArray<OrchestrationProposedPlan> = Object.freeze([]);const EMPTY_PROJECT_ATOM = Atom.make<EnvironmentProject | null>(null).pipe(Atom.withLabel("web-project:empty"),);-const EMPTY_PROJECT_REFS_ATOM = Atom.make(EMPTY_PROJECT_REFS).pipe(- Atom.withLabel("web-project-refs:empty"),-);const EMPTY_THREAD_REFS_ATOM = Atom.make(EMPTY_THREAD_REFS).pipe(Atom.withLabel("web-thread-refs:empty"),);@@ -50,18 +35,6 @@ const EMPTY_THREAD_DETAIL_ATOM = Atom.make<EnvironmentThread | null>(null).pipe(const EMPTY_THREAD_STATUS_ATOM = Atom.make<EnvironmentThreadStatus>("empty").pipe(Atom.withLabel("web-thread-status:empty"),);-const EMPTY_MESSAGES_ATOM = Atom.make(EMPTY_MESSAGES).pipe(- Atom.withLabel("web-thread-messages:empty"),-);-const EMPTY_ACTIVITIES_ATOM = Atom.make(EMPTY_ACTIVITIES).pipe(- Atom.withLabel("web-thread-activities:empty"),-);-const EMPTY_PROPOSED_PLANS_ATOM = Atom.make(EMPTY_PROPOSED_PLANS).pipe(- Atom.withLabel("web-thread-proposed-plans:empty"),-);-const EMPTY_SESSION_ATOM = Atom.make<OrchestrationSession | null>(null).pipe(- Atom.withLabel("web-thread-session:empty"),-);export const activeEnvironmentIdAtom = Atom.make<EnvironmentId | null>(null).pipe(Atom.keepAlive,@@ -72,32 +45,14 @@ export function useActiveEnvironmentId(): EnvironmentId | null {return useAtomValue(activeEnvironmentIdAtom);}-export function readActiveEnvironmentId(): EnvironmentId | null {- return appAtomRegistry.get(activeEnvironmentIdAtom);-}-export function setActiveEnvironmentId(environmentId: EnvironmentId | null): void {appAtomRegistry.set(activeEnvironmentIdAtom, environmentId);}-export function useProjectRefs(): ReadonlyArray<ScopedProjectRef> {- return useAtomValue(environmentProjects.projectRefsAtom);-}-export function useThreadRefs(): ReadonlyArray<ScopedThreadRef> {return useAtomValue(environmentThreadShells.threadRefsAtom);}-export function useEnvironmentProjectRefs(- environmentId: EnvironmentId | null,-): ReadonlyArray<ScopedProjectRef> {- return useAtomValue(- environmentId === null- ? EMPTY_PROJECT_REFS_ATOM- : environmentProjects.environmentProjectRefsAtom(environmentId),- );-}-export function useEnvironmentThreadRefs(environmentId: EnvironmentId | null,): ReadonlyArray<ScopedThreadRef> {@@ -184,36 +139,6 @@ export function useThread(return useMemo(() => mergeEnvironmentThread(detail, shell), [detail, shell]);}-export function useThreadMessages(- ref: ScopedThreadRef | null,-): ReadonlyArray<OrchestrationMessage> {- return useAtomValue(- ref === null ? EMPTY_MESSAGES_ATOM : environmentThreadDetails.messagesAtom(ref),- );-}--export function useThreadActivities(- ref: ScopedThreadRef | null,-): ReadonlyArray<OrchestrationThreadActivity> {- return useAtomValue(- ref === null ? EMPTY_ACTIVITIES_ATOM : environmentThreadDetails.activitiesAtom(ref),- );-}--export function useThreadProposedPlans(- ref: ScopedThreadRef | null,-): ReadonlyArray<OrchestrationProposedPlan> {- return useAtomValue(- ref === null ? EMPTY_PROPOSED_PLANS_ATOM : environmentThreadDetails.proposedPlansAtom(ref),- );-}--export function useThreadSession(ref: ScopedThreadRef | null): OrchestrationSession | null {- return useAtomValue(- ref === null ? EMPTY_SESSION_ATOM : environmentThreadDetails.sessionAtom(ref),- );-}-export function readProject(ref: ScopedProjectRef): EnvironmentProject | null {return appAtomRegistry.get(environmentProjects.projectAtom(ref));}@@ -297,28 +222,12 @@ export function readEnvironmentSupportsPinReorder(environmentId: EnvironmentId):);}-export function readThreadDetail(ref: ScopedThreadRef): EnvironmentThread | null {- return appAtomRegistry.get(environmentThreadDetails.detailAtom(ref));-}-export function readEnvironmentThreadRefs(environmentId: EnvironmentId,): ReadonlyArray<ScopedThreadRef> {return appAtomRegistry.get(environmentThreadShells.environmentThreadRefsAtom(environmentId));}-export function readThreadRefs(): ReadonlyArray<ScopedThreadRef> {- return appAtomRegistry.get(environmentThreadShells.threadRefsAtom);-}-export function readThreadShells(): ReadonlyArray<EnvironmentThreadShell> {return appAtomRegistry.get(environmentThreadShells.threadShellsAtom);}--export function findThreadRef(threadId: ThreadId): ScopedThreadRef | null {- return (- appAtomRegistry- .get(environmentThreadShells.threadRefsAtom)- .find((ref) => ref.threadId === threadId) ?? null- );-}diff --git a/package.json b/package.jsonindex 3fc66d0dd02..46913a435a8 100644--- a/package.json+++ b/package.json@@ -18,7 +18,7 @@"screenshots:mobile": "node scripts/mobile-showcase.ts","icons:export": "node scripts/export-brand-icons.ts","icons:check": "node scripts/export-brand-icons.ts --check",- "build": "vp run --filter './apps/*' --filter './packages/*' --filter './oxlint-plugin-t3code' --filter './scripts' build",+ "build": "vp run --filter './apps/*' build","build:marketing": "vp run --filter @t3tools/marketing build","build:desktop": "vp run --filter @t3tools/desktop --filter t3 build","build:resource-monitor": "cargo build --locked --release --manifest-path native/resource-monitor/Cargo.toml",@@ -31,7 +31,6 @@"test:desktop-smoke": "vp run --filter @t3tools/desktop smoke-test","fmt": "vp fmt","fmt:check": "vp fmt --check",- "build:contracts": "vp run --filter @t3tools/contracts build","dist:desktop:artifact": "node scripts/build-desktop-artifact.ts","dist:desktop:dmg": "node scripts/build-desktop-artifact.ts --platform mac --target dmg","dist:desktop:dmg:arm64": "node scripts/build-desktop-artifact.ts --platform mac --target dmg --arch arm64",@@ -41,7 +40,6 @@"dist:desktop:win:arm64": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch arm64","dist:desktop:win:x64": "node scripts/build-desktop-artifact.ts --platform win --target nsis --arch x64","release:smoke": "node scripts/release-smoke.ts",- "connect:announce-ga": "node scripts/announce-connect-ga.ts","clean": "rm -rf node_modules apps/*/node_modules packages/*/node_modules apps/*/dist apps/*/dist-electron packages/*/dist .vite-plus apps/*/.vite-plus packages/*/.vite-plus","sync:repos": "node scripts/sync-reference-repos.ts"},@@ -56,10 +54,5 @@"engines": {"node": "^24.13.1"},- "packageManager": "[email protected]",- "msw": {- "workerDirectory": [- "apps/web/public"- ]- }+ "packageManager": "[email protected]"}diff --git a/packages/client-runtime/src/connection/catalog.ts b/packages/client-runtime/src/connection/catalog.tsindex 8df3b2541d1..a79307947c5 100644--- a/packages/client-runtime/src/connection/catalog.ts+++ b/packages/client-runtime/src/connection/catalog.ts@@ -104,12 +104,6 @@ export const PlatformConnectionRegistration = Schema.Union([]);export type PlatformConnectionRegistration = typeof PlatformConnectionRegistration.Type;-export function connectionRegistrationTarget(- registration: ConnectionRegistration | PrimaryConnectionRegistration,-): ConnectionTarget {- return registration.target;-}-export function connectionRegistrationCatalogEntry(registration: ConnectionRegistration | PrimaryConnectionRegistration,): ConnectionCatalogEntry {diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex b601b59bfad..9f4c83609ca 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -2,10 +2,8 @@ import type {EnvironmentId,OrchestrationMessage,OrchestrationProjectShell,- OrchestrationShellSnapshot,OrchestrationThread,OrchestrationThreadShell,- ThreadId,} from "@t3tools/contracts";export interface EnvironmentProject extends OrchestrationProjectShell {@@ -42,12 +40,3 @@ export function scopeThread(): EnvironmentThread {return { ...thread, environmentId };}--export function selectEnvironmentThreadShell(- snapshot: OrchestrationShellSnapshot | null,- environmentId: EnvironmentId,- threadId: ThreadId,-): EnvironmentThreadShell | null {- const thread = snapshot?.threads.find((candidate) => candidate.id === threadId) ?? null;- return thread ? scopeThreadShell(environmentId, thread) : null;-}diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.tsindex 80aaa14a2e7..4b0fc330839 100644--- a/packages/client-runtime/src/state/runtime.ts+++ b/packages/client-runtime/src/state/runtime.ts@@ -13,12 +13,10 @@ import {type EnvironmentRpcInput,type EnvironmentRpcStreamFailure,type EnvironmentRpcStreamValue,- type EnvironmentStreamCommandRpcTag,type EnvironmentSubscriptionRpcTag,type EnvironmentUnaryRpcTag,EnvironmentRpcUnavailableError,request,- runStream,subscribe,} from "../rpc/client.ts";import { EnvironmentSupervisor } from "../connection/supervisor.ts";@@ -609,29 +607,6 @@ export function createEnvironmentCommand<R, ER, Input, A, E>(});}-function createEnvironmentStreamCommand<R, ER, Input, A, E>(- runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,- options: {- readonly label: string;- readonly execute: (input: Input) => Stream.Stream<A, E, EnvironmentSupervisor | R>;- readonly scheduler?: AtomCommandScheduler;- readonly concurrency?: AtomCommandConcurrency<{- readonly environmentId: EnvironmentIdType;- readonly input: Input;- }>;- },-) {- return createRuntimeStreamCommand(runtime, {- label: options.label,- ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),- ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),- execute: (target) =>- runStreamInEnvironment(target.environmentId, options.execute(target.input)).pipe(- Stream.withSpan(options.label),- ),- });-}-export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,options: {@@ -727,27 +702,3 @@ export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnary},});}--export function createEnvironmentRpcStreamCommand<- R,- ER,- TTag extends EnvironmentStreamCommandRpcTag,->(- runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,- options: {- readonly label: string;- readonly tag: TTag;- readonly scheduler?: AtomCommandScheduler;- readonly concurrency?: AtomCommandConcurrency<{- readonly environmentId: EnvironmentIdType;- readonly input: EnvironmentRpcInput<TTag>;- }>;- },-) {- return createEnvironmentStreamCommand(runtime, {- label: options.label,- ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),- ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),- execute: (input: EnvironmentRpcInput<TTag>) => runStream(options.tag, input),- });-}diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 176b2631e0c..8ce8b46f058 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -270,14 +270,6 @@ export function resolveServerUpdateProgressResult<E>(return Effect.fail(new ServerUpdateProgressIncompleteError({ targetVersion }));}-export function projectServerConfig(- current: Option.Option<ServerConfigProjection>,- event: ServerConfigStreamEvent,-): readonly [Option.Option<ServerConfigProjection>, ReadonlyArray<ServerConfigProjection>] {- const next = applyServerConfigProjection(current, event);- return [next, Option.toArray(next)];-}-const cachedConfigSnapshotEvent = (config: ServerConfig): ServerConfigStreamEvent => ({version: 1,type: "snapshot",diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.tsindex 547ce5c8e67..88dc2b26b28 100644--- a/packages/contracts/src/ipc.ts+++ b/packages/contracts/src/ipc.ts@@ -198,12 +198,6 @@ export interface DesktopRuntimeInfo {runningUnderArm64Translation: boolean;}-export const DesktopRuntimeInfoSchema = Schema.Struct({- hostArch: DesktopRuntimeArchSchema,- appArch: DesktopRuntimeArchSchema,- runningUnderArm64Translation: Schema.Boolean,-});-export interface DesktopUpdateState {enabled: boolean;status: DesktopUpdateStatus;@@ -351,14 +345,6 @@ export interface DesktopSshPasswordPromptRequest {expiresAt: string;}-export const DesktopSshPasswordPromptRequestSchema = Schema.Struct({- requestId: Schema.String,- destination: Schema.String,- username: Schema.NullOr(Schema.String),- prompt: Schema.String,- expiresAt: Schema.String,-});-export const DesktopSshPasswordPromptCancelledType = "ssh-password-prompt-cancelled" as const;export const DesktopSshPasswordPromptCancelledResultSchema = Schema.Struct({@@ -619,22 +605,6 @@ export const DesktopPreviewNavStatusSchema = Schema.Union([}),]);-export const DesktopPreviewTabStateSchema: Schema.Codec<DesktopPreviewTabState> = Schema.Struct({- tabId: DesktopPreviewTabIdSchema,- webContentsId: Schema.NullOr(Schema.Int),- navStatus: DesktopPreviewNavStatusSchema,- canGoBack: Schema.Boolean,- canGoForward: Schema.Boolean,- zoomFactor: Schema.Number,- pictureInPicture: Schema.Boolean,- colorScheme: DesktopPreviewColorSchemeSchema,- audioMuted: Schema.Boolean,- audible: Schema.Boolean,- controller: Schema.Literals(["human", "agent", "none"]),- favicon: Schema.optionalKey(DesktopPreviewFaviconSchema),- updatedAt: Schema.String,-});-export interface DesktopPreviewPointerEvent {tabId: string;phase: "move" | "click";@@ -644,16 +614,6 @@ export interface DesktopPreviewPointerEvent {createdAt: string;}-export const DesktopPreviewPointerEventSchema: Schema.Codec<DesktopPreviewPointerEvent> =- Schema.Struct({- tabId: DesktopPreviewTabIdSchema,- phase: Schema.Literals(["move", "click"]),- x: Schema.Number,- y: Schema.Number,- sequence: Schema.Int,- createdAt: Schema.String,- });-/*** Static config a renderer needs to mount a preview `<webview>`. Returned* atomically by `DesktopPreviewBridge.getPreviewConfig()` so the renderer@@ -733,15 +693,6 @@ export interface DesktopPreviewRecordingFrame {receivedAt: string;}-export const DesktopPreviewRecordingFrameSchema: Schema.Codec<DesktopPreviewRecordingFrame> =- Schema.Struct({- tabId: DesktopPreviewTabIdSchema,- data: Schema.String,- width: Schema.Number,- height: Schema.Number,- receivedAt: Schema.String,- });-export interface DesktopPreviewRecordingArtifact {id: string;tabId: string;diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex e813c6ce4a3..31ffc6bfc0b 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -1197,23 +1197,5 @@ export type ProviderRuntimeEventV2 = typeof ProviderRuntimeEventV2.Type;export const ProviderRuntimeEvent = ProviderRuntimeEventV2;export type ProviderRuntimeEvent = ProviderRuntimeEventV2;-// Compatibility aliases for call sites still importing legacy names.-const ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;-export type ProviderRuntimeMessageDeltaEvent = ProviderRuntimeContentDeltaEvent;-const ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;-export type ProviderRuntimeMessageCompletedEvent = ProviderRuntimeItemCompletedEvent;-const ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;-export type ProviderRuntimeToolStartedEvent = ProviderRuntimeItemStartedEvent;-const ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;-export type ProviderRuntimeToolCompletedEvent = ProviderRuntimeItemCompletedEvent;-const ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;-export type ProviderRuntimeApprovalRequestedEvent = ProviderRuntimeRequestOpenedEvent;-const ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;-export type ProviderRuntimeApprovalResolvedEvent = ProviderRuntimeRequestResolvedEvent;--// Legacy helper aliases retained for adapters/tests.-const ProviderRuntimeToolKind = Schema.Literals(["command", "file-read", "file-change", "other"]);-export type ProviderRuntimeToolKind = typeof ProviderRuntimeToolKind.Type;-export const ProviderRuntimeTurnStatus = RuntimeTurnState;export type ProviderRuntimeTurnStatus = RuntimeTurnState;diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.tsindex f9a0d2cf9a7..6ec4df5da1f 100644--- a/packages/contracts/src/settings.ts+++ b/packages/contracts/src/settings.ts@@ -298,10 +298,6 @@ export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientS// ── Server Settings (server-authoritative) ────────────────────-// Moved to environment.ts so orchestration contracts can use it without an-// import cycle; re-exported here for compatibility with deep imports.-export { ThreadEnvMode } from "./environment.ts";-const makeBinaryPathSetting = (fallback: string) =>TrimmedString.pipe(Schema.decodeTo(diff --git a/packages/effect-acp/package.json b/packages/effect-acp/package.jsonindex 4455dd460e7..7f1aa3b1078 100644--- a/packages/effect-acp/package.json+++ b/packages/effect-acp/package.json@@ -15,18 +15,10 @@"types": "./src/schema.ts","import": "./src/schema.ts"},- "./rpc": {- "types": "./src/rpc.ts",- "import": "./src/rpc.ts"- },"./protocol": {"types": "./src/protocol.ts","import": "./src/protocol.ts"},- "./terminal": {- "types": "./src/terminal.ts",- "import": "./src/terminal.ts"- },"./errors": {"types": "./src/errors.ts","import": "./src/errors.ts"diff --git a/packages/effect-acp/test/examples/cursor-acp-client.example.ts b/packages/effect-acp/test/examples/cursor-acp-client.example.tsdeleted file mode 100644index b7a146cf5c2..00000000000--- a/packages/effect-acp/test/examples/cursor-acp-client.example.ts+++ /dev/null@@ -1,81 +0,0 @@-import * as Effect from "effect/Effect";-import * as Console from "effect/Console";-import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";--import * as NodeServices from "@effect/platform-node/NodeServices";-import * as NodeRuntime from "@effect/platform-node/NodeRuntime";--import * as AcpClient from "../../src/client.ts";--const program = Effect.gen(function* () {- const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;- const command = ChildProcess.make("cursor-agent", ["acp"], {- cwd: process.cwd(),- shell: false,- });- const handle = yield* spawner.spawn(command);- const acpLayer = AcpClient.layerChildProcess(handle, {- logIncoming: true,- logOutgoing: true,- });-- yield* Effect.gen(function* () {- const acp = yield* AcpClient.AcpClient;-- yield* acp.handleRequestPermission(() =>- Effect.succeed({- outcome: {- outcome: "selected",- optionId: "allow",- },- }),- );- // yield* acp.handleSessionUpdate((notification) =>- // Console.log("session/update", JSON.stringify(notification)),- // );-- const initialized = yield* acp.agent.initialize({- protocolVersion: 1,- clientCapabilities: {- fs: { readTextFile: false, writeTextFile: false },- terminal: false,- _meta: {- parameterizedModelPicker: true,- },- },- clientInfo: {- name: "effect-acp-example",- version: "0.0.0",- },- });- yield* Console.log("initialized", initialized);-- const session = yield* acp.agent.createSession({- cwd: process.cwd(),- mcpServers: [],- });-- const config = yield* acp.agent.setSessionConfigOption({- sessionId: session.sessionId,- configId: "model",- value: "claude-opus-4-6",- });-- yield* Console.log("config", config);-- const result = yield* acp.agent.prompt({- sessionId: session.sessionId,- prompt: [- {- type: "text",- text: "Illustrate your ability to create todo lists and then execute all of them. Do not write the list to disk, illustrate your built in ability!",- },- ],- });-- yield* Console.log("prompt result", result);- yield* acp.agent.cancel({ sessionId: session.sessionId });- }).pipe(Effect.provide(acpLayer));-});--program.pipe(Effect.scoped, Effect.provide(NodeServices.layer), NodeRuntime.runMain);diff --git a/packages/effect-codex-app-server/package.json b/packages/effect-codex-app-server/package.jsonindex a067976c616..d8894a9980f 100644--- a/packages/effect-codex-app-server/package.json+++ b/packages/effect-codex-app-server/package.json@@ -15,10 +15,6 @@"types": "./src/rpc.ts","import": "./src/rpc.ts"},- "./protocol": {- "types": "./src/protocol.ts",- "import": "./src/protocol.ts"- },"./errors": {"types": "./src/errors.ts","import": "./src/errors.ts"diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.tsindex 415ce2a465b..1e47576949e 100644--- a/packages/shared/src/model.ts+++ b/packages/shared/src/model.ts@@ -1,6 +1,4 @@import {- DEFAULT_MODEL,- DEFAULT_MODEL_BY_PROVIDER,MODEL_SLUG_ALIASES_BY_PROVIDER,type ModelCapabilities,type ModelSelection,@@ -57,13 +55,6 @@ export function getProviderOptionBooleanSelectionValue(return typeof value === "boolean" ? value : undefined;}-export function getModelSelectionOptionValue(- modelSelection: ModelSelection | null | undefined,- id: string,-): string | boolean | undefined {- return getProviderOptionSelectionValue(modelSelection?.options, id);-}-export function getModelSelectionStringOptionValue(modelSelection: ModelSelection | null | undefined,id: string,@@ -213,22 +204,6 @@ export function buildProviderOptionSelectionsFromDescriptors(return nextSelections.length > 0 ? nextSelections : undefined;}-export function getModelSelectionOptionDescriptors(- modelSelection: ModelSelection | null | undefined,- caps?: ModelCapabilities | null | undefined,-): ReadonlyArray<ProviderOptionDescriptor> {- if (!modelSelection) {- return [];- }- if (!caps) {- return [];- }- return getProviderOptionDescriptors({- caps,- selections: modelSelection.options,- });-}-export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {return typeof text === "string" && /\bultrathink\b/i.test(text);}@@ -298,21 +273,6 @@ export function resolveSelectableModel(return resolved ? resolved.slug : null;}-function resolveModelSlug(model: string | null | undefined, provider: ProviderDriverKind): string {- const normalized = normalizeModelSlug(model, provider);- if (!normalized) {- return DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;- }- return normalized;-}--export function resolveModelSlugForProvider(- provider: ProviderDriverKind,- model: string | null | undefined,-): string {- return resolveModelSlug(model, provider);-}-/** Trim a string, returning null for empty/missing values. */export function trimOrNull<T extends string>(value: T | null | undefined): T | null {if (typeof value !== "string") return null;diff --git a/packages/shared/src/schemaJson.ts b/packages/shared/src/schemaJson.tsindex 3307eb460f8..e132b7084b7 100644--- a/packages/shared/src/schemaJson.ts+++ b/packages/shared/src/schemaJson.ts@@ -119,19 +119,6 @@ export const decodeJsonResult = <S extends Schema.Codec<unknown, unknown, never,};};-export const decodeUnknownJsonResult = <S extends Schema.Codec<unknown, unknown, never, never>>(- schema: S,-) => {- const decode = Schema.decodeUnknownExit(Schema.fromJsonString(schema));- return (input: unknown) => {- const result = decode(input);- if (Exit.isFailure(result)) {- return Result.fail(result.cause);- }- return Result.succeed(result.value);- };-};-export const formatSchemaError = (cause: Cause.Cause<Schema.SchemaError>) => {const issues: Array<SchemaDiagnosticIssue> = [];let issueCount = 0;diff --git a/packages/shared/src/themePalettes.ts b/packages/shared/src/themePalettes.tsindex 708b89a9d7e..73b73a4de91 100644--- a/packages/shared/src/themePalettes.ts+++ b/packages/shared/src/themePalettes.ts@@ -764,10 +764,6 @@ export const BUILT_IN_THEMES: ReadonlyArray<ThemeDefinition> = [IRIS_THEME,];-export function getBuiltInTheme(id: string): ThemeDefinition | null {- return BUILT_IN_THEMES.find((theme) => theme.id === id) ?? null;-}-export function getThemeColorsForAppearance(theme: ThemeDefinition,appearance: ThemeAppearance,diff --git a/packages/tailscale/package.json b/packages/tailscale/package.jsonindex ce020dc8ef5..306ec104ab5 100644--- a/packages/tailscale/package.json+++ b/packages/tailscale/package.json@@ -13,7 +13,6 @@"test": "vp test run"},"dependencies": {- "@effect/platform-node": "catalog:","@t3tools/shared": "workspace:*","effect": "catalog:"},diff --git a/packages/tailscale/src/tailscale.ts b/packages/tailscale/src/tailscale.tsindex fedde02ee76..d6db5e8bcc5 100644--- a/packages/tailscale/src/tailscale.ts+++ b/packages/tailscale/src/tailscale.ts@@ -382,23 +382,3 @@ export const probeTailscaleHttpsEndpoint = (input: {onSome: (httpResponse) => httpResponse.status >= 200 && httpResponse.status < 300,});}).pipe(Effect.orElseSucceed(() => false));--export const resolveTailscaleHttpsBaseUrl = (- input: {- readonly servePort?: number;- } = {},-): Effect.Effect<- string | null,- TailscaleCommandError | TailscaleStatusParseError,- ChildProcessSpawner.ChildProcessSpawner-> =>- readTailscaleStatus.pipe(- Effect.map((status) =>- status.magicDnsName- ? buildTailscaleHttpsBaseUrl({- magicDnsName: status.magicDnsName,- ...(input.servePort === undefined ? {} : { servePort: input.servePort }),- })- : null,- ),- );diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 02fa8871059..099c8c00681 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -394,9 +394,6 @@ importers:expo-widgets:specifier: ~57.0.15version: 57.0.15(@babel/[email protected])(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected])([email protected]([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected]))([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])- punycode:- specifier: ^2.3.1- version: 2.3.1react:specifier: 19.2.3version: 19.2.3@@ -697,9 +694,6 @@ importers:compression:specifier: ^1.8.1version: 1.8.1- msw:- specifier: 2.12.11- version: 2.12.11(@types/[email protected])([email protected])tailwindcss:specifier: ^4.0.0version: 4.3.0@@ -939,9 +933,6 @@ importers:packages/tailscale:dependencies:- '@effect/platform-node':- specifier: 4.0.0-beta.103- version: 4.0.0-beta.103([email protected])([email protected](patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6))([email protected])([email protected])'@t3tools/shared':specifier: workspace:*version: link:../shared@@ -970,9 +961,6 @@ importers:'@electron/osx-sign':specifier: 2.7.0version: 2.7.0- '@t3tools/contracts':- specifier: workspace:*- version: link:../packages/contracts'@t3tools/shared':specifier: workspace:*version: link:../packages/shared@@ -985,9 +973,6 @@ importers:pngjs:specifier: 7.0.0version: 7.0.0- yaml:- specifier: ^2.9.0- version: 2.9.0devDependencies:'@effect/vitest':specifier: 4.0.0-beta.103@@ -12817,7 +12802,8 @@ snapshots:'@img/[email protected]':optional: true- '@inquirer/[email protected]': {}+ '@inquirer/[email protected]':+ optional: true'@inquirer/[email protected](@types/[email protected])':dependencies:@@ -12825,6 +12811,7 @@ snapshots:'@inquirer/type': 3.0.10(@types/[email protected])optionalDependencies:'@types/node': 24.12.4+ optional: true'@inquirer/[email protected](@types/[email protected])':dependencies:@@ -12838,12 +12825,15 @@ snapshots:yoctocolors-cjs: 2.1.3optionalDependencies:'@types/node': 24.12.4+ optional: true- '@inquirer/[email protected]': {}+ '@inquirer/[email protected]':+ optional: true'@inquirer/[email protected](@types/[email protected])':optionalDependencies:'@types/node': 24.12.4+ optional: true'@ioredis/[email protected]': {}@@ -13191,6 +13181,7 @@ snapshots:is-node-process: 1.2.0outvariant: 1.4.3strict-event-emitter: 0.5.1+ optional: truedependencies:@@ -13305,14 +13296,17 @@ snapshots:'@octokit/request-error': 7.1.0'@octokit/webhooks-methods': 6.0.0- '@open-draft/[email protected]': {}+ '@open-draft/[email protected]':+ optional: true'@open-draft/[email protected]':dependencies:is-node-process: 1.2.0outvariant: 1.4.3+ optional: true- '@open-draft/[email protected]': {}+ '@open-draft/[email protected]':+ optional: true'@opencode-ai/[email protected]':dependencies:@@ -14691,7 +14685,8 @@ snapshots:'@types/http-errors': 2.0.5'@types/node': 24.12.4- '@types/[email protected]': {}+ '@types/[email protected]':+ optional: true'@types/[email protected]': {}@@ -15711,7 +15706,8 @@ snapshots:slice-ansi: 8.0.0string-width: 8.2.1- [email protected]: {}+ optional: truedependencies:@@ -17149,7 +17145,8 @@ snapshots:- [email protected]: {}+ optional: truedependencies:@@ -17297,7 +17294,8 @@ snapshots:property-information: 7.2.0space-separated-tokens: 2.0.2- [email protected]: {}+ optional: true@@ -17502,7 +17500,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -18740,6 +18739,7 @@ snapshots:typescript: 6.0.3transitivePeerDependencies:- '@types/node'+ optional: true@@ -18747,7 +18747,8 @@ snapshots:- [email protected]: {}+ optional: true[email protected](@types/[email protected]):dependencies:@@ -18973,7 +18974,8 @@ snapshots:stdin-discarder: 0.3.2string-width: 8.2.1- [email protected]: {}+ optional: true[email protected]([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])([email protected])([email protected])([email protected])([email protected])):dependencies:@@ -19916,7 +19918,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -20346,7 +20349,8 @@ snapshots:- [email protected]: {}+ optional: true@@ -20522,11 +20526,13 @@ snapshots:- [email protected]: {}+ optional: truedependencies:tldts-core: 7.4.2+ optional: truedependencies:@@ -20551,6 +20557,7 @@ snapshots:dependencies:tldts: 7.4.2+ optional: true@@ -20739,7 +20746,8 @@ snapshots:idb-keyval: 6.2.1ioredis: 5.11.0- [email protected]: {}+ optional: truedependencies:@@ -21095,6 +21103,7 @@ snapshots:ansi-styles: 4.3.0string-width: 4.2.3strip-ansi: 6.0.1+ optional: truedependencies:@@ -21186,7 +21195,8 @@ snapshots:- [email protected]: {}+ optional: truediff --git a/scripts/announce-connect-ga.ts b/scripts/announce-connect-ga.tsdeleted file mode 100644index 88a4db56cc7..00000000000--- a/scripts/announce-connect-ga.ts+++ /dev/null@@ -1,226 +0,0 @@-#!/usr/bin/env node--import * as NodeRuntime from "@effect/platform-node/NodeRuntime";-import * as NodeServices from "@effect/platform-node/NodeServices";-import * as Config from "effect/Config";-import * as Effect from "effect/Effect";-import * as Layer from "effect/Layer";-import * as Logger from "effect/Logger";-import * as Option from "effect/Option";-import * as Schema from "effect/Schema";-import { Command, Flag } from "effect/unstable/cli";-import {- FetchHttpClient,- HttpClient,- HttpClientRequest,- HttpClientResponse,-} from "effect/unstable/http";--const CLERK_API_URL = "https://api.clerk.com/v1";-const PAGE_SIZE = 500;--export class WaitlistEntry extends Schema.Class<WaitlistEntry>("WaitlistEntry")({- id: Schema.String,- email_address: Schema.String,- status: Schema.Literals(["pending", "invited", "completed", "rejected"]),-}) {}--const ClerkWaitlistResponse = Schema.Struct({- data: Schema.Array(WaitlistEntry),- total_count: Schema.Int,-});-const PositiveInteger = Schema.Int.check(Schema.isGreaterThan(0));-const ClerkSecretKey = Config.string("CLERK_SECRET_KEY");--export interface ConnectGaOptions {- readonly invite: boolean;- readonly limit: number | undefined;-}--export class ConnectGaRequestError extends Schema.TaggedErrorClass<ConnectGaRequestError>()(- "ConnectGaRequestError",- {- operation: Schema.String,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Clerk ${this.operation} request failed.`;- }-}--export class ConnectGaResponseError extends Schema.TaggedErrorClass<ConnectGaResponseError>()(- "ConnectGaResponseError",- {- operation: Schema.String,- status: Schema.Int,- cause: Schema.Defect(),- },-) {- override get message(): string {- return `Clerk ${this.operation} returned status ${this.status}.`;- }-}--const executeClerkJsonRequest = Effect.fn("executeClerkJsonRequest")(function* <- S extends Schema.Top,->(request: HttpClientRequest.HttpClientRequest, schema: S, operation: string) {- const client = (yield* HttpClient.HttpClient).pipe(- HttpClient.retryTransient({- retryOn: "errors-and-responses",- times: 3,- }),- );- const response = yield* client- .execute(request)- .pipe(Effect.mapError((cause) => new ConnectGaRequestError({ operation, cause })));- const success = yield* HttpClientResponse.filterStatusOk(response).pipe(- Effect.mapError(- (cause) =>- new ConnectGaResponseError({- operation,- status: response.status,- cause,- }),- ),- );- return yield* HttpClientResponse.schemaBodyJson(schema)(success).pipe(- Effect.mapError(- (cause) =>- new ConnectGaResponseError({- operation,- status: response.status,- cause,- }),- ),- );-});--const fetchWaitlistPage = Effect.fn("fetchWaitlistPage")(function* (- secretKey: string,- offset: number,-) {- const url = new URL(`${CLERK_API_URL}/waitlist_entries`);- url.searchParams.set("status", "pending");- url.searchParams.set("limit", String(PAGE_SIZE));- url.searchParams.set("offset", String(offset));- url.searchParams.set("order_by", "+created_at");- const request = HttpClientRequest.get(url.href).pipe(- HttpClientRequest.bearerToken(secretKey),- HttpClientRequest.setHeader("Clerk-API-Version", "2026-05-12"),- );- return yield* executeClerkJsonRequest(- request,- ClerkWaitlistResponse,- "list pending waitlist entries",- );-});--export const fetchPendingWaitlistEntries = Effect.fn("fetchPendingWaitlistEntries")(function* (- secretKey: string,- limit?: number,-) {- const entries: Array<WaitlistEntry> = [];- while (true) {- if (limit !== undefined && entries.length >= limit) break;- const page = yield* fetchWaitlistPage(secretKey, entries.length);- entries.push(...page.data);- if (entries.length >= page.total_count || page.data.length === 0) break;- }- return limit === undefined ? entries : entries.slice(0, limit);-});--export const inviteWaitlistEntry = Effect.fn("inviteWaitlistEntry")(function* (- secretKey: string,- entry: WaitlistEntry,-) {- const request = HttpClientRequest.post(- `${CLERK_API_URL}/waitlist_entries/${encodeURIComponent(entry.id)}/invite`,- ).pipe(- HttpClientRequest.bearerToken(secretKey),- HttpClientRequest.setHeader("Clerk-API-Version", "2026-05-12"),- );- return yield* executeClerkJsonRequest(- request,- WaitlistEntry,- `invite waitlist entry ${entry.id}`,- );-});--export const announceConnectGa = Effect.fn("announceConnectGa")(function* (- options: ConnectGaOptions,-) {- const clerkSecretKey = yield* ClerkSecretKey;- const entries = yield* fetchPendingWaitlistEntries(clerkSecretKey, options.limit);-- yield* Effect.logInfo(- options.invite ? "Connect GA waitlist invitations starting" : "Connect GA dry run",- ).pipe(- Effect.annotateLogs({- pendingEntries: entries.length,- }),- );-- if (!options.invite) {- for (const entry of entries) {- yield* Effect.logInfo("pending waitlist entry").pipe(- Effect.annotateLogs({- waitlistEntryId: entry.id,- emailAddress: entry.email_address,- }),- );- }- yield* Effect.logInfo("No invitation was sent. Re-run with --invite after reviewing the list.");- return;- }-- for (const [index, entry] of entries.entries()) {- const invited = yield* inviteWaitlistEntry(clerkSecretKey, entry);- yield* Effect.logInfo("Clerk waitlist invitation sent").pipe(- Effect.annotateLogs({- waitlistEntryId: invited.id,- completed: index + 1,- total: entries.length,- }),- );- }-});--export const announceConnectGaCommand = Command.make(- "announce-connect-ga",- {- invite: Flag.boolean("invite").pipe(- Flag.withDefault(false),- Flag.withDescription(- "Invite pending entries through Clerk. Without this flag, only print a dry-run list.",- ),- ),- limit: Flag.integer("limit").pipe(- Flag.withSchema(PositiveInteger),- Flag.optional,- Flag.withDescription("Process at most this many pending waitlist entries."),- ),- },- ({ invite, limit }) =>- announceConnectGa({- invite,- limit: Option.getOrUndefined(limit),- }),-).pipe(- Command.withDescription(- "Invite pending Clerk waitlist members now that T3 Connect is generally available.",- ),-);--if (import.meta.main) {- Command.run(announceConnectGaCommand, { version: "0.0.0" }).pipe(- Effect.provide(- Layer.mergeAll(- Logger.layer([Logger.consolePretty()]),- NodeServices.layer,- FetchHttpClient.layer,- ),- ),- NodeRuntime.runMain,- );-}diff --git a/scripts/package.json b/scripts/package.jsonindex 6e61fb30831..042d69a8d9f 100644--- a/scripts/package.json+++ b/scripts/package.json@@ -10,12 +10,10 @@"@effect/platform-node": "catalog:","@electron/asar": "^3.4.1","@electron/osx-sign": "2.7.0",- "@t3tools/contracts": "workspace:*","@t3tools/shared": "workspace:*","@t3tools/tailscale": "workspace:*","effect": "catalog:",- "pngjs": "7.0.0",- "yaml": "catalog:"+ "pngjs": "7.0.0"},"devDependencies": {"@effect/vitest": "catalog:",