From add5f34619b65c3283317d8c77e1feef6fc63267 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 26 Mar 2026 14:31:35 -0700 Subject: [PATCH 01/66] Add Claude context window selection support (#1422) --- .../src/git/Layers/ClaudeTextGeneration.ts | 3 +- .../src/provider/Layers/ClaudeAdapter.test.ts | 6 +- .../src/provider/Layers/ClaudeAdapter.ts | 31 +++-- .../src/provider/Layers/ClaudeProvider.ts | 27 ++-- .../src/provider/Layers/CodexProvider.ts | 14 +- apps/web/src/components/ChatView.tsx | 3 +- .../CompactComposerControlsMenu.browser.tsx | 4 + .../components/chat/ComposerCommandMenu.tsx | 4 +- .../chat/ProviderModelPicker.browser.tsx | 9 +- .../components/chat/ProviderModelPicker.tsx | 6 +- .../components/chat/TraitsPicker.browser.tsx | 4 + apps/web/src/components/chat/TraitsPicker.tsx | 81 +++++++++-- .../chat/composerProviderRegistry.test.tsx | 26 +++- .../chat/composerProviderRegistry.tsx | 30 +--- apps/web/src/composerDraftStore.ts | 24 ++-- apps/web/src/providerModels.ts | 28 ++-- packages/contracts/src/model.ts | 15 +- packages/shared/src/model.test.ts | 131 +++++++++++++++++- packages/shared/src/model.ts | 107 ++++++++++++-- 19 files changed, 414 insertions(+), 139 deletions(-) diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 6ffedbf7b4..919c3a323d 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -11,6 +11,7 @@ import { Effect, Layer, Option, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { ClaudeModelSelection } from "@t3tools/contracts"; +import { resolveApiModelId } from "@t3tools/shared/model"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git"; import { TextGenerationError } from "../Errors.ts"; @@ -103,7 +104,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () { "--json-schema", jsonSchemaStr, "--model", - modelSelection.model, + resolveApiModelId(modelSelection), ...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []), ...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []), "--dangerously-skip-permissions", diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index 4e8238dbe6..a10a40629c 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -347,7 +347,7 @@ describe("ClaudeAdapterLive", () => { ); }); - it.effect("ignores unsupported max effort for Sonnet 4.6", () => { + it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => { const harness = makeHarness(); return Effect.gen(function* () { const adapter = yield* ClaudeAdapter; @@ -365,7 +365,7 @@ describe("ClaudeAdapterLive", () => { }); const createInput = harness.getLastCreateQueryInput(); - assert.equal(createInput?.options.effort, undefined); + assert.equal(createInput?.options.effort, "high"); }).pipe( Effect.provideService(Random.Random, makeDeterministicRandomService()), Effect.provide(harness.layer), @@ -532,7 +532,7 @@ describe("ClaudeAdapterLive", () => { }); const createInput = harness.getLastCreateQueryInput(); - assert.equal(createInput?.options.effort, undefined); + assert.equal(createInput?.options.effort, "high"); const promptText = yield* Effect.promise(() => readFirstPromptText(createInput)); assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases"); }).pipe( diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 7ab8bc44ab..e7602ea5c4 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -40,7 +40,12 @@ import { type UserInputQuestion, ClaudeCodeEffort, } from "@t3tools/contracts"; -import { hasEffortLevel, applyClaudePromptEffortPrefix, trimOrNull } from "@t3tools/shared/model"; +import { + applyClaudePromptEffortPrefix, + resolveApiModelId, + resolveEffort, + trimOrNull, +} from "@t3tools/shared/model"; import { Cause, DateTime, @@ -506,16 +511,15 @@ const CLAUDE_SETTING_SOURCES = [ function buildPromptText(input: ProviderSendTurnInput): string { const rawEffort = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null; - const requestedEffort = trimOrNull(rawEffort); const claudeModel = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined; const caps = getClaudeModelCapabilities(claudeModel); + + // For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink"). + // resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly. + const trimmedEffort = trimOrNull(rawEffort); const promptEffort = - requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0 - ? "ultrathink" - : requestedEffort && hasEffortLevel(caps, requestedEffort) - ? requestedEffort - : null; + trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null; return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort); } @@ -2727,10 +2731,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { const claudeBinaryPath = claudeSettings.binaryPath; const modelSelection = input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined; - const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null); const caps = getClaudeModelCapabilities(modelSelection?.model); - const effort = - requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null; + const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined; + const effort = (resolveEffort(caps, modelSelection?.options?.effort) ?? + null) as ClaudeCodeEffort | null; const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode; const thinking = typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle @@ -2746,7 +2750,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { const queryOptions: ClaudeQueryOptions = { ...(input.cwd ? { cwd: input.cwd } : {}), - ...(modelSelection?.model ? { model: modelSelection.model } : {}), + ...(apiModelId ? { model: apiModelId } : {}), pathToClaudeCodeExecutable: claudeBinaryPath, settingSources: [...CLAUDE_SETTING_SOURCES], ...(effectiveEffort ? { effort: effectiveEffort } : {}), @@ -2840,7 +2844,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { threadId, payload: { config: { - ...(modelSelection?.model ? { model: modelSelection.model } : {}), + ...(apiModelId ? { model: apiModelId } : {}), ...(input.cwd ? { cwd: input.cwd } : {}), ...(effectiveEffort ? { effort: effectiveEffort } : {}), ...(permissionMode ? { permissionMode } : {}), @@ -2893,8 +2897,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) { } if (modelSelection?.model) { + const apiModelId = resolveApiModelId(modelSelection); yield* Effect.tryPromise({ - try: () => context.query.setModel(modelSelection.model), + try: () => context.query.setModel(apiModelId), catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause), }); } diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index e51f5096db..b67b90e879 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -9,7 +9,7 @@ import type { } from "@t3tools/contracts"; import { Effect, Equal, Layer, Option, Result, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { getDefaultEffort, hasEffortLevel, trimOrNull } from "@t3tools/shared/model"; +import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model"; import { buildServerProvider, @@ -42,6 +42,10 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k" }, + { value: "1m", label: "1M", isDefault: true }, + ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, }, @@ -58,6 +62,10 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k" }, + { value: "1m", label: "1M", isDefault: true }, + ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, }, @@ -69,6 +77,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], } satisfies ModelCapabilities, }, @@ -81,6 +90,7 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], } ); @@ -91,23 +101,16 @@ export function normalizeClaudeModelOptions( modelOptions: ClaudeModelOptions | null | undefined, ): ClaudeModelOptions | undefined { const caps = getClaudeModelCapabilities(model); - const defaultReasoningEffort = getDefaultEffort(caps); - const resolvedEffort = trimOrNull(modelOptions?.effort); - const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? ""); - const effort = - resolvedEffort && - !isPromptInjected && - hasEffortLevel(caps, resolvedEffort) && - resolvedEffort !== defaultReasoningEffort - ? resolvedEffort - : undefined; + const effort = resolveEffort(caps, modelOptions?.effort); const thinking = caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined; const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined; + const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); const nextOptions: ClaudeModelOptions = { ...(thinking === false ? { thinking: false } : {}), - ...(effort ? { effort } : {}), + ...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}), ...(fastMode ? { fastMode: true } : {}), + ...(contextWindow ? { contextWindow } : {}), }; return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; } diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 913fbb58d5..6497469a2a 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -10,7 +10,7 @@ import type { } from "@t3tools/contracts"; import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; -import { getDefaultEffort, trimOrNull } from "@t3tools/shared/model"; +import { resolveEffort } from "@t3tools/shared/model"; import { buildServerProvider, @@ -48,6 +48,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -64,6 +65,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -80,6 +82,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -96,6 +99,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -112,6 +116,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -128,6 +133,7 @@ const BUILT_IN_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -140,6 +146,7 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], } ); @@ -150,11 +157,10 @@ export function normalizeCodexModelOptions( modelOptions: CodexModelOptions | null | undefined, ): CodexModelOptions | undefined { const caps = getCodexModelCapabilities(model); - const defaultReasoningEffort = getDefaultEffort(caps); - const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort; + const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort); const fastModeEnabled = modelOptions?.fastMode === true; const nextOptions: CodexModelOptions = { - ...(reasoningEffort && reasoningEffort !== defaultReasoningEffort + ...(reasoningEffort ? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] } : {}), ...(fastModeEnabled ? { fastMode: true } : {}), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 849f59e088..b0129ab75a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5,7 +5,6 @@ import { type MessageId, type ModelSelection, type ProjectScript, - type ModelSlug, type ProviderKind, type ProjectEntry, type ProjectId, @@ -3105,7 +3104,7 @@ export default function ChatView({ threadId }: ChatViewProps) { ]); const onProviderModelSelect = useCallback( - (provider: ProviderKind, model: ModelSlug) => { + (provider: ProviderKind, model: string) => { if (!activeThread) return; if (lockedProvider !== null && provider !== lockedProvider) { scheduleComposerFocus(); diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx index 8770e58138..aa3550e007 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx @@ -60,6 +60,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -71,6 +72,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -87,6 +89,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -103,6 +106,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, diff --git a/apps/web/src/components/chat/ComposerCommandMenu.tsx b/apps/web/src/components/chat/ComposerCommandMenu.tsx index 818c3c20f8..7af4e6da43 100644 --- a/apps/web/src/components/chat/ComposerCommandMenu.tsx +++ b/apps/web/src/components/chat/ComposerCommandMenu.tsx @@ -1,4 +1,4 @@ -import { type ProjectEntry, type ModelSlug, type ProviderKind } from "@t3tools/contracts"; +import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts"; import { memo } from "react"; import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic"; import { BotIcon } from "lucide-react"; @@ -27,7 +27,7 @@ export type ComposerCommandItem = id: string; type: "model"; provider: ProviderKind; - model: ModelSlug; + model: string; label: string; description: string; }; diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index fe878e7c18..679cbff321 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -1,4 +1,4 @@ -import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts"; +import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; import { page } from "vitest/browser"; import { afterEach, describe, expect, it, vi } from "vitest"; import { render } from "vitest-browser-react"; @@ -33,6 +33,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -44,6 +45,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -71,6 +73,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -87,6 +90,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -98,6 +102,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -107,7 +112,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ async function mountPicker(props: { provider: ProviderKind; - model: ModelSlug; + model: string; lockedProvider: ProviderKind | null; providers?: ReadonlyArray; triggerVariant?: "ghost" | "outline"; diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 5a09defc72..565a9d399d 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -1,4 +1,4 @@ -import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts"; +import { type ProviderKind, type ServerProvider } from "@t3tools/contracts"; import { resolveSelectableModel } from "@t3tools/shared/model"; import { memo, useState } from "react"; import type { VariantProps } from "class-variance-authority"; @@ -52,7 +52,7 @@ function providerIconClassName( export const ProviderModelPicker = memo(function ProviderModelPicker(props: { provider: ProviderKind; - model: ModelSlug; + model: string; lockedProvider: ProviderKind | null; providers?: ReadonlyArray; modelOptionsByProvider: Record>; @@ -61,7 +61,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { disabled?: boolean; triggerVariant?: VariantProps["variant"]; triggerClassName?: string; - onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void; + onProviderModelChange: (provider: ProviderKind, model: string) => void; }) { const [isMenuOpen, setIsMenuOpen] = useState(false); const activeProvider = props.lockedProvider ?? props.provider; diff --git a/apps/web/src/components/chat/TraitsPicker.browser.tsx b/apps/web/src/components/chat/TraitsPicker.browser.tsx index bd8c61ee56..99d09fd634 100644 --- a/apps/web/src/components/chat/TraitsPicker.browser.tsx +++ b/apps/web/src/components/chat/TraitsPicker.browser.tsx @@ -49,6 +49,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -77,6 +78,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -93,6 +95,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -104,6 +107,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index 5fd97b8cde..a3b6cbb48f 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -11,7 +11,9 @@ import { isClaudeUltrathinkPrompt, trimOrNull, getDefaultEffort, - hasEffortLevel, + getDefaultContextWindow, + hasContextWindowOption, + resolveEffort, } from "@t3tools/shared/model"; import { memo, useCallback, useState } from "react"; import type { VariantProps } from "class-variance-authority"; @@ -53,6 +55,16 @@ function getRawEffort( return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort); } +function getRawContextWindow( + provider: ProviderKind, + modelOptions: ProviderOptions | null | undefined, +): string | null { + if (provider === "claudeAgent") { + return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.contextWindow); + } + return null; +} + function buildNextOptions( provider: ProviderKind, modelOptions: ProviderOptions | null | undefined, @@ -78,21 +90,10 @@ function getSelectedTraits( : caps.reasoningEffortLevels.filter( (option) => !caps.promptInjectedEffortLevels.includes(option.value), ); - const defaultEffort = getDefaultEffort(caps); // Resolve effort from options (provider-specific key) - const resolvedEffort = getRawEffort(provider, modelOptions); - - // Filter out prompt-injected efforts from the "current effort" display - const isPromptInjected = resolvedEffort - ? caps.promptInjectedEffortLevels.includes(resolvedEffort) - : false; - const effort = - resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort) - ? resolvedEffort - : defaultEffort && hasEffortLevel(caps, defaultEffort) - ? defaultEffort - : null; + const rawEffort = getRawEffort(provider, modelOptions); + const effort = resolveEffort(caps, rawEffort) ?? null; // Thinking toggle (only for models that support it) const thinkingEnabled = caps.supportsThinkingToggle @@ -104,6 +105,15 @@ function getSelectedTraits( caps.supportsFastMode && (modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true; + // Context window + const contextWindowOptions = caps.contextWindowOptions; + const rawContextWindow = getRawContextWindow(provider, modelOptions); + const defaultContextWindow = getDefaultContextWindow(caps); + const contextWindow = + rawContextWindow && hasContextWindowOption(caps, rawContextWindow) + ? rawContextWindow + : defaultContextWindow; + // Prompt-controlled effort (e.g. ultrathink in prompt text) const ultrathinkPromptControlled = allowPromptInjectedEffort && @@ -116,6 +126,9 @@ function getSelectedTraits( effortLevels, thinkingEnabled, fastModeEnabled, + contextWindowOptions, + contextWindow, + defaultContextWindow, ultrathinkPromptControlled, }; } @@ -159,6 +172,9 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ effortLevels, thinkingEnabled, fastModeEnabled, + contextWindowOptions, + contextWindow, + defaultContextWindow, ultrathinkPromptControlled, } = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort); const defaultEffort = getDefaultEffort(caps); @@ -194,7 +210,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ ], ); - if (effort === null && thinkingEnabled === null) { + if (effort === null && thinkingEnabled === null && contextWindowOptions.length <= 1) { return null; } @@ -258,6 +274,33 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ ) : null} + {contextWindowOptions.length > 1 ? ( + <> + + +
+ Context Window +
+ { + updateModelOptions( + buildNextOptions(provider, modelOptions, { + contextWindow: value, + }), + ); + }} + > + {contextWindowOptions.map((option) => ( + + {option.label} + {option.value === defaultContextWindow ? " (default)" : ""} + + ))} + +
+ + ) : null} ); }); @@ -281,12 +324,19 @@ export const TraitsPicker = memo(function TraitsPicker({ effortLevels, thinkingEnabled, fastModeEnabled, + contextWindowOptions, + contextWindow, + defaultContextWindow, ultrathinkPromptControlled, } = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort); const effortLabel = effort ? (effortLevels.find((l) => l.value === effort)?.label ?? effort) : null; + const contextWindowLabel = + contextWindowOptions.length > 1 && contextWindow !== defaultContextWindow + ? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null) + : null; const triggerLabel = [ ultrathinkPromptControlled ? "Ultrathink" @@ -296,6 +346,7 @@ export const TraitsPicker = memo(function TraitsPicker({ ? null : `Thinking ${thinkingEnabled ? "On" : "Off"}`, ...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []), + ...(contextWindowLabel ? [contextWindowLabel] : []), ] .filter(Boolean) .join(" · "); diff --git a/apps/web/src/components/chat/composerProviderRegistry.test.tsx b/apps/web/src/components/chat/composerProviderRegistry.test.tsx index d5fbb1333a..cc17335cd5 100644 --- a/apps/web/src/components/chat/composerProviderRegistry.test.tsx +++ b/apps/web/src/components/chat/composerProviderRegistry.test.tsx @@ -16,6 +16,7 @@ const CODEX_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -35,6 +36,7 @@ const CLAUDE_MODELS: ReadonlyArray = [ ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -51,6 +53,7 @@ const CLAUDE_MODELS: ReadonlyArray = [ ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: ["ultrathink"], }, }, @@ -62,6 +65,7 @@ const CLAUDE_MODELS: ReadonlyArray = [ reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: true, + contextWindowOptions: [], promptInjectedEffortLevels: [], }, }, @@ -80,7 +84,9 @@ describe("getComposerProviderState", () => { expect(state).toEqual({ provider: "codex", promptEffort: "high", - modelOptionsForDispatch: undefined, + modelOptionsForDispatch: { + reasoningEffort: "high", + }, }); }); @@ -125,12 +131,13 @@ describe("getComposerProviderState", () => { provider: "codex", promptEffort: "high", modelOptionsForDispatch: { + reasoningEffort: "high", fastMode: true, }, }); }); - it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => { + it("preserves codex default effort explicitly in dispatch options", () => { const state = getComposerProviderState({ provider: "codex", model: "gpt-5.4", @@ -147,7 +154,9 @@ describe("getComposerProviderState", () => { expect(state).toEqual({ provider: "codex", promptEffort: "high", - modelOptionsForDispatch: undefined, + modelOptionsForDispatch: { + reasoningEffort: "high", + }, }); }); @@ -163,7 +172,9 @@ describe("getComposerProviderState", () => { expect(state).toEqual({ provider: "claudeAgent", promptEffort: "high", - modelOptionsForDispatch: undefined, + modelOptionsForDispatch: { + effort: "high", + }, }); }); @@ -232,12 +243,13 @@ describe("getComposerProviderState", () => { provider: "claudeAgent", promptEffort: "high", modelOptionsForDispatch: { + effort: "high", fastMode: true, }, }); }); - it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => { + it("preserves Claude default effort explicitly in dispatch options", () => { const state = getComposerProviderState({ provider: "claudeAgent", model: "claude-opus-4-6", @@ -254,7 +266,9 @@ describe("getComposerProviderState", () => { expect(state).toEqual({ provider: "claudeAgent", promptEffort: "high", - modelOptionsForDispatch: undefined, + modelOptionsForDispatch: { + effort: "high", + }, }); }); }); diff --git a/apps/web/src/components/chat/composerProviderRegistry.tsx b/apps/web/src/components/chat/composerProviderRegistry.tsx index 2cebd8d4f4..1a2080d441 100644 --- a/apps/web/src/components/chat/composerProviderRegistry.tsx +++ b/apps/web/src/components/chat/composerProviderRegistry.tsx @@ -1,16 +1,10 @@ import { - type ModelSlug, type ProviderKind, type ProviderModelOptions, type ServerProviderModel, type ThreadId, } from "@t3tools/contracts"; -import { - isClaudeUltrathinkPrompt, - trimOrNull, - getDefaultEffort, - hasEffortLevel, -} from "@t3tools/shared/model"; +import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model"; import type { ReactNode } from "react"; import { getProviderModelCapabilities, @@ -21,7 +15,7 @@ import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker"; export type ComposerProviderStateInput = { provider: ProviderKind; - model: ModelSlug; + model: string; models: ReadonlyArray; prompt: string; modelOptions: ProviderModelOptions | null | undefined; @@ -40,7 +34,7 @@ type ProviderRegistryEntry = { getState: (input: ComposerProviderStateInput) => ComposerProviderState; renderTraitsMenuContent: (input: { threadId: ThreadId; - model: ModelSlug; + model: string; models: ReadonlyArray; modelOptions: ProviderModelOptions[ProviderKind] | undefined; prompt: string; @@ -48,7 +42,7 @@ type ProviderRegistryEntry = { }) => ReactNode; renderTraitsPicker: (input: { threadId: ThreadId; - model: ModelSlug; + model: string; models: ReadonlyArray; modelOptions: ProviderModelOptions[ProviderKind] | undefined; prompt: string; @@ -72,17 +66,7 @@ function getProviderStateFromCapabilities( : null : null; - const draftEffort = trimOrNull(rawEffort); - const defaultEffort = getDefaultEffort(caps); - const isPromptInjected = draftEffort - ? caps.promptInjectedEffortLevels.includes(draftEffort) - : false; - const promptEffort = - draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort) - ? draftEffort - : defaultEffort && hasEffortLevel(caps, defaultEffort) - ? defaultEffort - : null; + const promptEffort = resolveEffort(caps, rawEffort) ?? null; // Normalize options for dispatch const normalizedOptions = @@ -180,7 +164,7 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com export function renderProviderTraitsMenuContent(input: { provider: ProviderKind; threadId: ThreadId; - model: ModelSlug; + model: string; models: ReadonlyArray; modelOptions: ProviderModelOptions[ProviderKind] | undefined; prompt: string; @@ -199,7 +183,7 @@ export function renderProviderTraitsMenuContent(input: { export function renderProviderTraitsPicker(input: { provider: ProviderKind; threadId: ThreadId; - model: ModelSlug; + model: string; models: ReadonlyArray; modelOptions: ProviderModelOptions[ProviderKind] | undefined; prompt: string; diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 3d54c526f1..17b06e7bd1 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -2,7 +2,7 @@ import { CODEX_REASONING_EFFORT_OPTIONS, type ClaudeCodeEffort, type CodexReasoningEffort, - type ModelSlug, + DEFAULT_MODEL_BY_PROVIDER, ModelSelection, ProjectId, ProviderInteractionMode, @@ -15,7 +15,7 @@ import { import * as Schema from "effect/Schema"; import * as Equal from "effect/Equal"; import { DeepMutable } from "effect/Types"; -import { getDefaultModel, normalizeModelSlug } from "@t3tools/shared/model"; +import { normalizeModelSlug } from "@t3tools/shared/model"; import { useMemo } from "react"; import { getLocalStorageItem } from "./hooks/useLocalStorage"; import { resolveAppModelSelection } from "./modelSelection"; @@ -263,7 +263,7 @@ interface ComposerDraftStoreState { } export interface EffectiveComposerModelState { - selectedModel: ModelSlug; + selectedModel: string; modelOptions: ProviderModelOptions | null; } @@ -475,12 +475,20 @@ function normalizeProviderModelOptions( : claudeCandidate?.fastMode === false ? false : undefined; + const claudeContextWindow = + typeof claudeCandidate?.contextWindow === "string" && claudeCandidate.contextWindow.length > 0 + ? claudeCandidate.contextWindow + : undefined; const claude = - claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined + claudeThinking !== undefined || + claudeEffort !== undefined || + claudeFastMode !== undefined || + claudeContextWindow !== undefined ? { ...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}), ...(claudeEffort !== undefined ? { effort: claudeEffort } : {}), ...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}), + ...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}), } : undefined; @@ -594,7 +602,7 @@ function legacyToModelSelectionByProvider( model: modelSelection?.provider === provider ? modelSelection.model - : getDefaultModel(provider), + : DEFAULT_MODEL_BY_PROVIDER[provider], options, }; } @@ -1676,7 +1684,7 @@ export const useComposerDraftStore = create()( if (opts) { nextMap[provider] = { provider, - model: current?.model ?? getDefaultModel(provider), + model: current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider], options: opts, }; } else if (current?.options) { @@ -1726,7 +1734,7 @@ export const useComposerDraftStore = create()( if (providerOpts) { nextMap[normalizedProvider] = { provider: normalizedProvider, - model: currentForProvider?.model ?? getDefaultModel(normalizedProvider), + model: currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider], options: providerOpts, }; } else if (currentForProvider?.options) { @@ -1744,7 +1752,7 @@ export const useComposerDraftStore = create()( base.modelSelectionByProvider[normalizedProvider] ?? ({ provider: normalizedProvider, - model: getDefaultModel(normalizedProvider), + model: DEFAULT_MODEL_BY_PROVIDER[normalizedProvider], } as ModelSelection); if (providerOpts) { nextStickyMap[normalizedProvider] = { diff --git a/apps/web/src/providerModels.ts b/apps/web/src/providerModels.ts index a925ed690f..f2e8692eff 100644 --- a/apps/web/src/providerModels.ts +++ b/apps/web/src/providerModels.ts @@ -7,17 +7,13 @@ import { type ServerProvider, type ServerProviderModel, } from "@t3tools/contracts"; -import { - getDefaultEffort, - hasEffortLevel, - normalizeModelSlug, - trimOrNull, -} from "@t3tools/shared/model"; +import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model"; const EMPTY_CAPABILITIES: ModelCapabilities = { reasoningEffortLevels: [], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }; @@ -78,11 +74,10 @@ export function normalizeCodexModelOptionsWithCapabilities( caps: ModelCapabilities, modelOptions: CodexModelOptions | null | undefined, ): CodexModelOptions | undefined { - const defaultReasoningEffort = getDefaultEffort(caps); - const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort; + const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort); const fastModeEnabled = modelOptions?.fastMode === true; const nextOptions: CodexModelOptions = { - ...(reasoningEffort && reasoningEffort !== defaultReasoningEffort + ...(reasoningEffort ? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] } : {}), ...(fastModeEnabled ? { fastMode: true } : {}), @@ -94,23 +89,16 @@ export function normalizeClaudeModelOptionsWithCapabilities( caps: ModelCapabilities, modelOptions: ClaudeModelOptions | null | undefined, ): ClaudeModelOptions | undefined { - const defaultReasoningEffort = getDefaultEffort(caps); - const resolvedEffort = trimOrNull(modelOptions?.effort); - const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? ""); - const effort = - resolvedEffort && - !isPromptInjected && - hasEffortLevel(caps, resolvedEffort) && - resolvedEffort !== defaultReasoningEffort - ? resolvedEffort - : undefined; + const effort = resolveEffort(caps, modelOptions?.effort); const thinking = caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined; const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined; + const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow); const nextOptions: ClaudeModelOptions = { ...(thinking === false ? { thinking: false } : {}), - ...(effort ? { effort } : {}), + ...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}), ...(fastMode ? { fastMode: true } : {}), + ...(contextWindow ? { contextWindow } : {}), }; return Object.keys(nextOptions).length > 0 ? nextOptions : undefined; } diff --git a/packages/contracts/src/model.ts b/packages/contracts/src/model.ts index 68ca110473..e62a957e05 100644 --- a/packages/contracts/src/model.ts +++ b/packages/contracts/src/model.ts @@ -18,6 +18,7 @@ export const ClaudeModelOptions = Schema.Struct({ thinking: Schema.optional(Schema.Boolean), effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)), fastMode: Schema.optional(Schema.Boolean), + contextWindow: Schema.optional(Schema.String), }); export type ClaudeModelOptions = typeof ClaudeModelOptions.Type; @@ -34,17 +35,23 @@ export const EffortOption = Schema.Struct({ }); export type EffortOption = typeof EffortOption.Type; +export const ContextWindowOption = Schema.Struct({ + value: TrimmedNonEmptyString, + label: TrimmedNonEmptyString, + isDefault: Schema.optional(Schema.Boolean), +}); +export type ContextWindowOption = typeof ContextWindowOption.Type; + export const ModelCapabilities = Schema.Struct({ reasoningEffortLevels: Schema.Array(EffortOption), supportsFastMode: Schema.Boolean, supportsThinkingToggle: Schema.Boolean, + contextWindowOptions: Schema.Array(ContextWindowOption), promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString), }); export type ModelCapabilities = typeof ModelCapabilities.Type; -export type ModelSlug = string & {}; - -export const DEFAULT_MODEL_BY_PROVIDER: Record = { +export const DEFAULT_MODEL_BY_PROVIDER: Record = { codex: "gpt-5.4", claudeAgent: "claude-sonnet-4-6", }; @@ -57,7 +64,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record> = { +export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record> = { codex: { "5.4": "gpt-5.4", "5.3": "gpt-5.3-codex", diff --git a/packages/shared/src/model.test.ts b/packages/shared/src/model.test.ts index 31f0d0a112..535601762d 100644 --- a/packages/shared/src/model.test.ts +++ b/packages/shared/src/model.test.ts @@ -1,16 +1,17 @@ import { describe, expect, it } from "vitest"; -import { - DEFAULT_MODEL, - DEFAULT_MODEL_BY_PROVIDER, - type ModelCapabilities, -} from "@t3tools/contracts"; +import { DEFAULT_MODEL_BY_PROVIDER, type ModelCapabilities } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, + getDefaultContextWindow, getDefaultEffort, + hasContextWindowOption, hasEffortLevel, isClaudeUltrathinkPrompt, normalizeModelSlug, + resolveApiModelId, + resolveContextWindow, + resolveEffort, resolveModelSlug, resolveModelSlugForProvider, resolveSelectableModel, @@ -24,6 +25,7 @@ const codexCaps: ModelCapabilities = { ], supportsFastMode: true, supportsThinkingToggle: false, + contextWindowOptions: [], promptInjectedEffortLevels: [], }; @@ -35,6 +37,10 @@ const claudeCaps: ModelCapabilities = { ], supportsFastMode: false, supportsThinkingToggle: false, + contextWindowOptions: [ + { value: "200k", label: "200k" }, + { value: "1m", label: "1M", isDefault: true }, + ], promptInjectedEffortLevels: ["ultrathink"], }; @@ -54,14 +60,15 @@ describe("normalizeModelSlug", () => { describe("resolveModelSlug", () => { it("returns defaults when the model is missing", () => { - expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL); + expect(resolveModelSlug(undefined, "codex")).toBe(DEFAULT_MODEL_BY_PROVIDER.codex); + expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe( DEFAULT_MODEL_BY_PROVIDER.claudeAgent, ); }); it("preserves normalized unknown models", () => { - expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model"); + expect(resolveModelSlug("custom/internal-model", "codex")).toBe("custom/internal-model"); }); }); @@ -89,6 +96,42 @@ describe("capability helpers", () => { }); }); +describe("resolveEffort", () => { + it("returns the explicit value when supported and not prompt-injected", () => { + expect(resolveEffort(codexCaps, "xhigh")).toBe("xhigh"); + expect(resolveEffort(codexCaps, "high")).toBe("high"); + expect(resolveEffort(claudeCaps, "medium")).toBe("medium"); + }); + + it("falls back to default when value is unsupported", () => { + expect(resolveEffort(codexCaps, "bogus")).toBe("high"); + expect(resolveEffort(claudeCaps, "bogus")).toBe("high"); + }); + + it("returns the default when no value is provided", () => { + expect(resolveEffort(codexCaps, undefined)).toBe("high"); + expect(resolveEffort(codexCaps, null)).toBe("high"); + expect(resolveEffort(codexCaps, "")).toBe("high"); + expect(resolveEffort(codexCaps, " ")).toBe("high"); + }); + + it("excludes prompt-injected efforts and falls back to default", () => { + expect(resolveEffort(claudeCaps, "ultrathink")).toBe("high"); + }); + + it("returns undefined for models with no effort levels", () => { + const noCaps: ModelCapabilities = { + reasoningEffortLevels: [], + supportsFastMode: false, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }; + expect(resolveEffort(noCaps, undefined)).toBeUndefined(); + expect(resolveEffort(noCaps, "high")).toBeUndefined(); + }); +}); + describe("misc helpers", () => { it("detects ultrathink prompts", () => { expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true); @@ -109,3 +152,77 @@ describe("misc helpers", () => { expect(trimOrNull(" ")).toBeNull(); }); }); + +describe("context window helpers", () => { + it("reads default context window", () => { + expect(getDefaultContextWindow(claudeCaps)).toBe("1m"); + }); + + it("returns null for models without context window options", () => { + expect(getDefaultContextWindow(codexCaps)).toBeNull(); + }); + + it("checks context window support", () => { + expect(hasContextWindowOption(claudeCaps, "1m")).toBe(true); + expect(hasContextWindowOption(claudeCaps, "200k")).toBe(true); + expect(hasContextWindowOption(claudeCaps, "bogus")).toBe(false); + expect(hasContextWindowOption(codexCaps, "1m")).toBe(false); + }); +}); + +describe("resolveContextWindow", () => { + it("returns the explicit value when supported", () => { + expect(resolveContextWindow(claudeCaps, "200k")).toBe("200k"); + expect(resolveContextWindow(claudeCaps, "1m")).toBe("1m"); + }); + + it("falls back to default when value is unsupported", () => { + expect(resolveContextWindow(claudeCaps, "bogus")).toBe("1m"); + }); + + it("returns the default when no value is provided", () => { + expect(resolveContextWindow(claudeCaps, undefined)).toBe("1m"); + expect(resolveContextWindow(claudeCaps, null)).toBe("1m"); + expect(resolveContextWindow(claudeCaps, "")).toBe("1m"); + }); + + it("returns undefined for models with no context window options", () => { + expect(resolveContextWindow(codexCaps, undefined)).toBeUndefined(); + expect(resolveContextWindow(codexCaps, "1m")).toBeUndefined(); + }); +}); + +describe("resolveApiModelId", () => { + it("appends [1m] suffix for 1m context window", () => { + expect( + resolveApiModelId({ + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { contextWindow: "1m" }, + }), + ).toBe("claude-opus-4-6[1m]"); + }); + + it("returns the model as-is for 200k context window", () => { + expect( + resolveApiModelId({ + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { contextWindow: "200k" }, + }), + ).toBe("claude-opus-4-6"); + }); + + it("returns the model as-is when no context window is set", () => { + expect(resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6" })).toBe( + "claude-opus-4-6", + ); + expect( + resolveApiModelId({ provider: "claudeAgent", model: "claude-opus-4-6", options: {} }), + ).toBe("claude-opus-4-6"); + }); + + it("returns the model as-is for Codex selections", () => { + expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4"); + }); +}); diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index e633aeb293..1598b0407d 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -3,7 +3,7 @@ import { MODEL_SLUG_ALIASES_BY_PROVIDER, type ClaudeCodeEffort, type ModelCapabilities, - type ModelSlug, + type ModelSelection, type ProviderKind, } from "@t3tools/contracts"; @@ -12,10 +12,6 @@ export interface SelectableModelOption { name: string; } -export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug { - return DEFAULT_MODEL_BY_PROVIDER[provider]; -} - // ── Effort helpers ──────────────────────────────────────────────────── /** Check whether a capabilities object includes a given effort value. */ @@ -28,6 +24,65 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null { return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null; } +/** + * Resolve a raw effort option against capabilities. + * + * Returns the effective effort value — the explicit value if supported and not + * prompt-injected, otherwise the model's default. Returns `undefined` only + * when the model has no effort levels at all. + * + * Prompt-injected efforts (e.g. "ultrathink") are excluded because they are + * applied via prompt text, not the effort API parameter. + */ +export function resolveEffort( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const defaultValue = getDefaultEffort(caps); + const trimmed = typeof raw === "string" ? raw.trim() : null; + if ( + trimmed && + !caps.promptInjectedEffortLevels.includes(trimmed) && + hasEffortLevel(caps, trimmed) + ) { + return trimmed; + } + return defaultValue ?? undefined; +} + +// ── Context window helpers ─────────────────────────────────────────── + +/** Check whether a capabilities object includes a given context window value. */ +export function hasContextWindowOption(caps: ModelCapabilities, value: string): boolean { + return caps.contextWindowOptions.some((o) => o.value === value); +} + +/** Return the default context window value, or `null` if none is defined. */ +export function getDefaultContextWindow(caps: ModelCapabilities): string | null { + return caps.contextWindowOptions.find((o) => o.isDefault)?.value ?? null; +} + +/** + * Resolve a raw `contextWindow` option against capabilities. + * + * Returns the effective context window value — the explicit value if supported, + * otherwise the model's default. Returns `undefined` only when the model has + * no context window options at all. + * + * Unlike effort levels (where the API has matching defaults), the context + * window requires an explicit API suffix (e.g. `[1m]`), so we always preserve + * the resolved value to avoid ambiguity between "user chose the default" and + * "not specified". + */ +export function resolveContextWindow( + caps: ModelCapabilities, + raw: string | null | undefined, +): string | undefined { + const defaultValue = getDefaultContextWindow(caps); + if (!raw) return defaultValue ?? undefined; + return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined); +} + export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean { return typeof text === "string" && /\bultrathink\b/i.test(text); } @@ -35,7 +90,7 @@ export function isClaudeUltrathinkPrompt(text: string | null | undefined): boole export function normalizeModelSlug( model: string | null | undefined, provider: ProviderKind = "codex", -): ModelSlug | null { +): string | null { if (typeof model !== "string") { return null; } @@ -45,18 +100,18 @@ export function normalizeModelSlug( return null; } - const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record; + const aliases = MODEL_SLUG_ALIASES_BY_PROVIDER[provider] as Record; const aliased = Object.prototype.hasOwnProperty.call(aliases, trimmed) ? aliases[trimmed] : undefined; - return typeof aliased === "string" ? aliased : (trimmed as ModelSlug); + return typeof aliased === "string" ? aliased : trimmed; } export function resolveSelectableModel( provider: ProviderKind, value: string | null | undefined, options: ReadonlyArray, -): ModelSlug | null { +): string | null { if (typeof value !== "string") { return null; } @@ -85,10 +140,7 @@ export function resolveSelectableModel( return resolved ? resolved.slug : null; } -export function resolveModelSlug( - model: string | null | undefined, - provider: ProviderKind = "codex", -): ModelSlug { +export function resolveModelSlug(model: string | null | undefined, provider: ProviderKind): string { const normalized = normalizeModelSlug(model, provider); if (!normalized) { return DEFAULT_MODEL_BY_PROVIDER[provider]; @@ -99,7 +151,7 @@ export function resolveModelSlug( export function resolveModelSlugForProvider( provider: ProviderKind, model: string | null | undefined, -): ModelSlug { +): string { return resolveModelSlug(model, provider); } @@ -110,6 +162,33 @@ export function trimOrNull(value: T | null | undefined): T | n return trimmed || null; } +/** + * Resolve the actual API model identifier from a model selection. + * + * Provider-aware: each provider can map `contextWindow` (or other options) + * to whatever the API requires — a model-id suffix, a separate parameter, etc. + * The canonical slug stored in the selection stays unchanged so the + * capabilities system keeps working. + * + * Expects `contextWindow` to already be resolved (via `resolveContextWindow`) + * to the effective value, not stripped to `undefined` for defaults. + */ +export function resolveApiModelId(modelSelection: ModelSelection): string { + switch (modelSelection.provider) { + case "claudeAgent": { + switch (modelSelection.options?.contextWindow) { + case "1m": + return `${modelSelection.model}[1m]`; + default: + return modelSelection.model; + } + } + default: { + return modelSelection.model; + } + } +} + export function applyClaudePromptEffortPrefix( text: string, effort: ClaudeCodeEffort | null | undefined, From 648f0676bde993ae64e57d2e2ccd2e797803de32 Mon Sep 17 00:00:00 2001 From: Nassim Najjar Date: Fri, 27 Mar 2026 05:46:43 +0100 Subject: [PATCH 02/66] Add VS Code Insiders and VSCodium to Open In editor picker (#1392) --- apps/server/src/open.test.ts | 41 +++- apps/server/src/open.ts | 8 +- apps/web/src/components/ChatView.browser.tsx | 183 ++++++++++++++++-- apps/web/src/components/chat/OpenInPicker.tsx | 10 + packages/contracts/src/editor.ts | 17 +- 5 files changed, 231 insertions(+), 28 deletions(-) diff --git a/apps/server/src/open.test.ts b/apps/server/src/open.test.ts index 649e88462c..947a60ac2a 100644 --- a/apps/server/src/open.test.ts +++ b/apps/server/src/open.test.ts @@ -40,6 +40,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { args: ["/tmp/workspace"], }); + const vscodeInsidersLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLaunch, { + command: "code-insiders", + args: ["/tmp/workspace"], + }); + + const vscodiumLaunch = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLaunch, { + command: "codium", + args: ["/tmp/workspace"], + }); + const zedLaunch = yield* resolveEditorLaunch( { cwd: "/tmp/workspace", editor: "zed" }, "darwin", @@ -80,6 +98,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => { args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], }); + const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" }, + "darwin", + ); + assert.deepEqual(vscodeInsidersLineAndColumn, { + command: "code-insiders", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + + const vscodiumLineAndColumn = yield* resolveEditorLaunch( + { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" }, + "darwin", + ); + assert.deepEqual(vscodiumLineAndColumn, { + command: "codium", + args: ["--goto", "/tmp/workspace/src/open.ts:71:5"], + }); + const zedLineAndColumn = yield* resolveEditorLaunch( { cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" }, "darwin", @@ -220,13 +256,14 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => { const path = yield* Path.Path; const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" }); - yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n"); + yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n"); yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ"); const editors = resolveAvailableEditors("win32", { PATH: dir, PATHEXT: ".COM;.EXE;.BAT;.CMD", }); - assert.deepEqual(editors, ["cursor", "file-manager"]); + assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]); }), ); }); diff --git a/apps/server/src/open.ts b/apps/server/src/open.ts index e7238c04b2..3fbfd1653d 100644 --- a/apps/server/src/open.ts +++ b/apps/server/src/open.ts @@ -39,10 +39,8 @@ interface CommandAvailabilityOptions { const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/; -function shouldUseGotoFlag(editorId: EditorId, target: string): boolean { - return ( - (editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target) - ); +function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean { + return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target); } function fileManagerCommandForPlatform(platform: NodeJS.Platform): string { @@ -213,7 +211,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* ( } if (editorDef.command) { - return shouldUseGotoFlag(editorDef.id, input.cwd) + return shouldUseGotoFlag(editorDef, input.cwd) ? { command: editorDef.command, args: ["--goto", input.cwd] } : { command: editorDef.command, args: [input.cwd] }; } diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 0995ae1ccc..8abe8c60c2 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -356,6 +356,25 @@ function withProjectScripts( }; } +function setDraftThreadWithoutWorktree(): void { + useComposerDraftStore.setState({ + draftThreadsByThreadId: { + [THREAD_ID]: { + projectId: PROJECT_ID, + createdAt: NOW_ISO, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + envMode: "local", + }, + }, + projectDraftThreadIdByProjectId: { + [PROJECT_ID]: THREAD_ID, + }, + }); +} + function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ targetMessageId: "msg-user-plan-target" as MessageId, @@ -1011,22 +1030,7 @@ describe("ChatView timeline estimator parity (full app)", () => { ); it("opens the project cwd for draft threads without a worktree path", async () => { - useComposerDraftStore.setState({ - draftThreadsByThreadId: { - [THREAD_ID]: { - projectId: PROJECT_ID, - createdAt: NOW_ISO, - runtimeMode: "full-access", - interactionMode: "default", - branch: null, - worktreePath: null, - envMode: "local", - }, - }, - projectDraftThreadIdByProjectId: { - [PROJECT_ID]: THREAD_ID, - }, - }); + setDraftThreadWithoutWorktree(); const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, @@ -1067,6 +1071,153 @@ describe("ChatView timeline estimator parity (full app)", () => { } }); + it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + openButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscode-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("filters the open picker menu and opens VSCodium from the menu", async () => { + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders", "vscodium"], + }; + }, + }); + + try { + const menuButton = await waitForElement( + () => document.querySelector('button[aria-label="Copy options"]'), + "Unable to find Open picker button.", + ); + (menuButton as HTMLButtonElement).click(); + + await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VS Code Insiders"), + ) ?? null, + "Unable to find VS Code Insiders menu item.", + ); + + expect( + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) => + item.textContent?.includes("Zed"), + ), + ).toBe(false); + + const vscodiumItem = await waitForElement( + () => + Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) => + item.textContent?.includes("VSCodium"), + ) ?? null, + "Unable to find VSCodium menu item.", + ); + (vscodiumItem as HTMLElement).click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscodium", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("falls back to the first installed editor when the stored favorite is unavailable", async () => { + localStorage.setItem("t3code:last-editor", "vscodium"); + setDraftThreadWithoutWorktree(); + + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + availableEditors: ["vscode-insiders"], + }; + }, + }); + + try { + const openButton = await waitForElement( + () => + Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === "Open", + ) as HTMLButtonElement | null, + "Unable to find Open button.", + ); + openButton.click(); + + await vi.waitFor( + () => { + const openRequest = wsRequests.find( + (request) => request._tag === WS_METHODS.shellOpenInEditor, + ); + expect(openRequest).toMatchObject({ + _tag: WS_METHODS.shellOpenInEditor, + cwd: "/repo/project", + editor: "vscode-insiders", + }); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + it("runs project scripts from local draft threads at the project cwd", async () => { useComposerDraftStore.setState({ draftThreadsByThreadId: { diff --git a/apps/web/src/components/chat/OpenInPicker.tsx b/apps/web/src/components/chat/OpenInPicker.tsx index 9f62f7121e..bbe527c28b 100644 --- a/apps/web/src/components/chat/OpenInPicker.tsx +++ b/apps/web/src/components/chat/OpenInPicker.tsx @@ -22,6 +22,16 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray e.id)); From 02989fe600c2aff728b09c5600f75a3a073b3468 Mon Sep 17 00:00:00 2001 From: Guilherme Vieira <46866023+GuilhermeVieiraDev@users.noreply.github.com> Date: Fri, 27 Mar 2026 04:47:57 +0000 Subject: [PATCH 03/66] fix(web): improve chat header badge and title flex distribution (#1309) --- apps/web/src/components/GitActionsControl.tsx | 6 +++--- apps/web/src/components/ProjectScriptsControl.tsx | 6 +++--- apps/web/src/components/chat/ChatHeader.tsx | 8 ++++---- apps/web/src/components/chat/OpenInPicker.tsx | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 09b84444e2..1593a151da 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -765,7 +765,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions } > - + {quickAction.label} @@ -781,12 +781,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions onClick={runQuickAction} > - + {quickAction.label} )} - + { if (open) void invalidateGitQueries(queryClient); diff --git a/apps/web/src/components/ProjectScriptsControl.tsx b/apps/web/src/components/ProjectScriptsControl.tsx index 4d6c5eef78..11b08cc2cf 100644 --- a/apps/web/src/components/ProjectScriptsControl.tsx +++ b/apps/web/src/components/ProjectScriptsControl.tsx @@ -277,11 +277,11 @@ export default function ProjectScriptsControl({ title={`Run ${primaryScript.name}`} > - + {primaryScript.name} - + } @@ -342,7 +342,7 @@ export default function ProjectScriptsControl({ ) : ( diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 39a4f6eedc..f04c9879fa 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -62,7 +62,7 @@ export const ChatHeader = memo(function ChatHeader({ onToggleDiff, }: ChatHeaderProps) { return ( -
+

{activeProjectName && ( - - {activeProjectName} + + {activeProjectName} )} {activeProjectName && !isGitRepo && ( @@ -82,7 +82,7 @@ export const ChatHeader = memo(function ChatHeader({ )}

-
+
{activeProjectScripts && ( openInEditor(preferredEditor)} > {primaryOption?.Icon &&
@@ -1349,7 +1280,7 @@ export default function Sidebar() { /> } showOnHover - className="top-1 right-1 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" + className="top-1 right-1.5 size-5 rounded-md p-0 text-muted-foreground/70 hover:bg-secondary hover:text-foreground" onClick={(event) => { event.preventDefault(); event.stopPropagation(); @@ -1658,202 +1589,199 @@ export default function Sidebar() { )} - - {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( - - - - Intel build on Apple Silicon - {arm64IntelBuildWarningDescription} - {desktopUpdateButtonAction !== "none" ? ( - - - - ) : null} - - - ) : null} - -
- - Projects - -
- { - updateSettings({ sidebarProjectSortOrder: sortOrder }); - }} - onThreadSortOrderChange={(sortOrder) => { - updateSettings({ sidebarThreadSortOrder: sortOrder }); - }} - /> - - + ) : ( + <> + + {showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? ( + + + + Intel build on Apple Silicon + {arm64IntelBuildWarningDescription} + {desktopUpdateButtonAction !== "none" ? ( + + + + ) : null} + + + ) : null} + +
+ + Projects + +
+ { + updateSettings({ sidebarProjectSortOrder: sortOrder }); + }} + onThreadSortOrderChange={(sortOrder) => { + updateSettings({ sidebarThreadSortOrder: sortOrder }); + }} + /> + + + } + > + + + + {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"} + + +
+
+ + {shouldShowProjectPathEntry && ( +
+ {isElectron && ( + )} +
+ { + setNewCwd(event.target.value); + setAddProjectError(null); + }} + onKeyDown={(event) => { + if (event.key === "Enter") handleAddProject(); + if (event.key === "Escape") { + setAddingProject(false); + setAddProjectError(null); + } + }} + autoFocus /> - } - > - - - - {shouldShowProjectPathEntry ? "Cancel add project" : "Add project"} - - -
-
- - {shouldShowProjectPathEntry && ( -
- {isElectron && ( - + +
+ {addProjectError && ( +

+ {addProjectError} +

+ )} +
+ +
+
)} -
- { - setNewCwd(event.target.value); - setAddProjectError(null); - }} - onKeyDown={(event) => { - if (event.key === "Enter") handleAddProject(); - if (event.key === "Escape") { - setAddingProject(false); - setAddProjectError(null); - } - }} - autoFocus - /> - -
- {addProjectError && ( -

- {addProjectError} -

- )} -
- -
-
- )} - {isManualProjectSorting ? ( - - - project.id)} - strategy={verticalListSortingStrategy} + {isManualProjectSorting ? ( + + + project.id)} + strategy={verticalListSortingStrategy} + > + {sortedProjects.map((project) => ( + + {(dragHandleProps) => renderProjectItem(project, dragHandleProps)} + + ))} + + + + ) : ( + {sortedProjects.map((project) => ( - - {(dragHandleProps) => renderProjectItem(project, dragHandleProps)} - + + {renderProjectItem(project, null)} + ))} - - - - ) : ( - - {sortedProjects.map((project) => ( - - {renderProjectItem(project, null)} - - ))} + + )} + + {projects.length === 0 && !shouldShowProjectPathEntry && ( +
+ No projects yet +
+ )} +
+
+ + + + + + void navigate({ to: "/settings" })} + > + + Settings + + - )} - - {projects.length === 0 && !shouldShowProjectPathEntry && ( -
- No projects yet -
- )} - - - - - - - - {isOnSettings ? ( - window.history.back()} - > - - Back - - ) : ( - void navigate({ to: "/settings" })} - > - - Settings - - )} - - - +
+ + )} ); } diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx new file mode 100644 index 0000000000..bb149c00a4 --- /dev/null +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -0,0 +1,1390 @@ +import { + ArchiveIcon, + ArchiveX, + ChevronDownIcon, + InfoIcon, + LoaderIcon, + PlusIcon, + RefreshCwIcon, + Undo2Icon, + XIcon, +} from "lucide-react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { + PROVIDER_DISPLAY_NAMES, + type ProviderKind, + type ServerProvider, + type ServerProviderModel, + ThreadId, +} from "@t3tools/contracts"; +import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; +import { normalizeModelSlug } from "@t3tools/shared/model"; +import { Equal } from "effect"; +import { APP_VERSION } from "../../branding"; +import { ProviderModelPicker } from "../chat/ProviderModelPicker"; +import { TraitsPicker } from "../chat/TraitsPicker"; +import { resolveAndPersistPreferredEditor } from "../../editorPreferences"; +import { useTheme } from "../../hooks/useTheme"; +import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; +import { useThreadActions } from "../../hooks/useThreadActions"; +import { serverConfigQueryOptions, serverQueryKeys } from "../../lib/serverReactQuery"; +import { + MAX_CUSTOM_MODEL_LENGTH, + getCustomModelOptionsByProvider, + resolveAppModelSelectionState, +} from "../../modelSelection"; +import { ensureNativeApi, readNativeApi } from "../../nativeApi"; +import { useStore } from "../../store"; +import { formatRelativeTime, formatRelativeTimeLabel } from "../../timestampFormat"; +import { cn } from "../../lib/utils"; +import { Button } from "../ui/button"; +import { Collapsible, CollapsibleContent } from "../ui/collapsible"; +import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "../ui/empty"; +import { Input } from "../ui/input"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { Switch } from "../ui/switch"; +import { toastManager } from "../ui/toast"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { ProjectFavicon } from "../ProjectFavicon"; + +const THEME_OPTIONS = [ + { + value: "system", + label: "System", + }, + { + value: "light", + label: "Light", + }, + { + value: "dark", + label: "Dark", + }, +] as const; + +const TIMESTAMP_FORMAT_LABELS = { + locale: "System default", + "12-hour": "12-hour", + "24-hour": "24-hour", +} as const; + +const EMPTY_SERVER_PROVIDERS: ReadonlyArray = []; + +type InstallProviderSettings = { + provider: ProviderKind; + title: string; + binaryPlaceholder: string; + binaryDescription: ReactNode; + homePathKey?: "codexHomePath"; + homePlaceholder?: string; + homeDescription?: ReactNode; +}; + +const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [ + { + provider: "codex", + title: "Codex", + binaryPlaceholder: "Codex binary path", + binaryDescription: "Path to the Codex binary", + homePathKey: "codexHomePath", + homePlaceholder: "CODEX_HOME", + homeDescription: "Optional custom Codex home and config directory.", + }, + { + provider: "claudeAgent", + title: "Claude", + binaryPlaceholder: "Claude binary path", + binaryDescription: "Path to the Claude binary", + }, +] as const; + +const PROVIDER_STATUS_STYLES = { + disabled: { + dot: "bg-amber-400", + }, + error: { + dot: "bg-destructive", + }, + ready: { + dot: "bg-success", + }, + warning: { + dot: "bg-warning", + }, +} as const; + +function getProviderSummary(provider: ServerProvider | undefined) { + if (!provider) { + return { + headline: "Checking provider status", + detail: "Waiting for the server to report installation and authentication details.", + }; + } + if (!provider.enabled) { + return { + headline: "Disabled", + detail: + provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.", + }; + } + if (!provider.installed) { + return { + headline: "Not found", + detail: provider.message ?? "CLI not detected on PATH.", + }; + } + if (provider.authStatus === "authenticated") { + return { + headline: "Authenticated", + detail: provider.message ?? null, + }; + } + if (provider.authStatus === "unauthenticated") { + return { + headline: "Not authenticated", + detail: provider.message ?? null, + }; + } + if (provider.status === "warning") { + return { + headline: "Needs attention", + detail: + provider.message ?? "The provider is installed, but the server could not fully verify it.", + }; + } + if (provider.status === "error") { + return { + headline: "Unavailable", + detail: provider.message ?? "The provider failed its startup checks.", + }; + } + return { + headline: "Available", + detail: provider.message ?? "Installed and ready, but authentication could not be verified.", + }; +} + +function getProviderVersionLabel(version: string | null | undefined) { + if (!version) return null; + return version.startsWith("v") ? version : `v${version}`; +} + +function useRelativeTimeTick(intervalMs = 1_000) { + const [tick, setTick] = useState(() => Date.now()); + useEffect(() => { + const id = setInterval(() => setTick(Date.now()), intervalMs); + return () => clearInterval(id); + }, [intervalMs]); + return tick; +} + +function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) { + useRelativeTimeTick(); + const lastCheckedRelative = lastCheckedAt ? formatRelativeTime(lastCheckedAt) : null; + + if (!lastCheckedRelative) { + return null; + } + + return ( + + {lastCheckedRelative.suffix ? ( + <> + Checked {lastCheckedRelative.value}{" "} + {lastCheckedRelative.suffix} + + ) : ( + <>Checked {lastCheckedRelative.value} + )} + + ); +} + +function SettingsSection({ + title, + icon, + headerAction, + children, +}: { + title: string; + icon?: ReactNode; + headerAction?: ReactNode; + children: ReactNode; +}) { + return ( +
+
+

+ {icon} + {title} +

+ {headerAction} +
+
+ {children} +
+
+ ); +} + +function SettingsRow({ + title, + description, + status, + resetAction, + control, + children, +}: { + title: string; + description: string; + status?: ReactNode; + resetAction?: ReactNode; + control?: ReactNode; + children?: ReactNode; +}) { + return ( +
+
+
+
+

{title}

+ + {resetAction} + +
+

{description}

+ {status ?
{status}
: null} +
+ {control ? ( +
+ {control} +
+ ) : null} +
+ {children} +
+ ); +} + +function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) { + return ( + + { + event.stopPropagation(); + onClick(); + }} + > + + + } + /> + Reset to default + + ); +} + +function SettingsPageContainer({ children }: { children: ReactNode }) { + return ( +
+
{children}
+
+ ); +} + +export function useSettingsRestore(onRestored?: () => void) { + const { theme, setTheme } = useTheme(); + const settings = useSettings(); + const { resetSettings } = useUpdateSettings(); + + const isGitWritingModelDirty = !Equal.equals( + settings.textGenerationModelSelection ?? null, + DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null, + ); + const areProviderSettingsDirty = PROVIDER_SETTINGS.some((providerSettings) => { + const currentSettings = settings.providers[providerSettings.provider]; + const defaultSettings = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider]; + return !Equal.equals(currentSettings, defaultSettings); + }); + + const changedSettingLabels = useMemo( + () => [ + ...(theme !== "system" ? ["Theme"] : []), + ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat + ? ["Time format"] + : []), + ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap + ? ["Diff line wrapping"] + : []), + ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming + ? ["Assistant output"] + : []), + ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode + ? ["New thread mode"] + : []), + ...(settings.confirmThreadArchive !== DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive + ? ["Archive confirmation"] + : []), + ...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete + ? ["Delete confirmation"] + : []), + ...(isGitWritingModelDirty ? ["Git writing model"] : []), + ...(areProviderSettingsDirty ? ["Providers"] : []), + ], + [ + areProviderSettingsDirty, + isGitWritingModelDirty, + settings.confirmThreadArchive, + settings.confirmThreadDelete, + settings.defaultThreadEnvMode, + settings.diffWordWrap, + settings.enableAssistantStreaming, + settings.timestampFormat, + theme, + ], + ); + + const restoreDefaults = useCallback(async () => { + if (changedSettingLabels.length === 0) return; + const api = readNativeApi(); + const confirmed = await (api ?? ensureNativeApi()).dialogs.confirm( + ["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join( + "\n", + ), + ); + if (!confirmed) return; + + setTheme("system"); + resetSettings(); + onRestored?.(); + }, [changedSettingLabels, onRestored, resetSettings, setTheme]); + + return { + changedSettingLabels, + restoreDefaults, + }; +} + +export function GeneralSettingsPanel() { + const { theme, setTheme } = useTheme(); + const settings = useSettings(); + const { updateSettings } = useUpdateSettings(); + const serverConfigQuery = useQuery(serverConfigQueryOptions()); + const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false); + const [openKeybindingsError, setOpenKeybindingsError] = useState(null); + const [openProviderDetails, setOpenProviderDetails] = useState>({ + codex: Boolean( + settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath || + settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath || + settings.providers.codex.customModels.length > 0, + ), + claudeAgent: Boolean( + settings.providers.claudeAgent.binaryPath !== + DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath || + settings.providers.claudeAgent.customModels.length > 0, + ), + }); + const [customModelInputByProvider, setCustomModelInputByProvider] = useState< + Record + >({ + codex: "", + claudeAgent: "", + }); + const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState< + Partial> + >({}); + const [isRefreshingProviders, setIsRefreshingProviders] = useState(false); + const refreshingRef = useRef(false); + const queryClient = useQueryClient(); + const modelListRefs = useRef>>({}); + const refreshProviders = useCallback(() => { + if (refreshingRef.current) return; + refreshingRef.current = true; + setIsRefreshingProviders(true); + void ensureNativeApi() + .server.refreshProviders() + .then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() })) + .catch((error: unknown) => { + console.warn("Failed to refresh providers", error); + }) + .finally(() => { + refreshingRef.current = false; + setIsRefreshingProviders(false); + }); + }, [queryClient]); + + const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null; + const availableEditors = serverConfigQuery.data?.availableEditors; + const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS; + const codexHomePath = settings.providers.codex.homePath; + + const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders); + const textGenProvider = textGenerationModelSelection.provider; + const textGenModel = textGenerationModelSelection.model; + const textGenModelOptions = textGenerationModelSelection.options; + const gitModelOptionsByProvider = getCustomModelOptionsByProvider( + settings, + serverProviders, + textGenProvider, + textGenModel, + ); + const isGitWritingModelDirty = !Equal.equals( + settings.textGenerationModelSelection ?? null, + DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null, + ); + + const openKeybindingsFile = useCallback(() => { + if (!keybindingsConfigPath) return; + setOpenKeybindingsError(null); + setIsOpeningKeybindings(true); + const editor = resolveAndPersistPreferredEditor(availableEditors ?? []); + if (!editor) { + setOpenKeybindingsError("No available editors found."); + setIsOpeningKeybindings(false); + return; + } + void ensureNativeApi() + .shell.openInEditor(keybindingsConfigPath, editor) + .catch((error) => { + setOpenKeybindingsError( + error instanceof Error ? error.message : "Unable to open keybindings file.", + ); + }) + .finally(() => { + setIsOpeningKeybindings(false); + }); + }, [availableEditors, keybindingsConfigPath]); + + const addCustomModel = useCallback( + (provider: ProviderKind) => { + const customModelInput = customModelInputByProvider[provider]; + const customModels = settings.providers[provider].customModels; + const normalized = normalizeModelSlug(customModelInput, provider); + if (!normalized) { + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: "Enter a model slug.", + })); + return; + } + if ( + serverProviders + .find((candidate) => candidate.provider === provider) + ?.models.some((option) => !option.isCustom && option.slug === normalized) + ) { + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: "That model is already built in.", + })); + return; + } + if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) { + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`, + })); + return; + } + if (customModels.includes(normalized)) { + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: "That custom model is already saved.", + })); + return; + } + + updateSettings({ + providers: { + ...settings.providers, + [provider]: { + ...settings.providers[provider], + customModels: [...customModels, normalized], + }, + }, + }); + setCustomModelInputByProvider((existing) => ({ + ...existing, + [provider]: "", + })); + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: null, + })); + + const el = modelListRefs.current[provider]; + if (!el) return; + const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); + requestAnimationFrame(scrollToEnd); + const observer = new MutationObserver(() => { + scrollToEnd(); + observer.disconnect(); + }); + observer.observe(el, { childList: true, subtree: true }); + setTimeout(() => observer.disconnect(), 2_000); + }, + [customModelInputByProvider, serverProviders, settings, updateSettings], + ); + + const removeCustomModel = useCallback( + (provider: ProviderKind, slug: string) => { + updateSettings({ + providers: { + ...settings.providers, + [provider]: { + ...settings.providers[provider], + customModels: settings.providers[provider].customModels.filter( + (model) => model !== slug, + ), + }, + }, + }); + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [provider]: null, + })); + }, + [settings, updateSettings], + ); + + const providerCards = PROVIDER_SETTINGS.map((providerSettings) => { + const liveProvider = serverProviders.find( + (candidate) => candidate.provider === providerSettings.provider, + ); + const providerConfig = settings.providers[providerSettings.provider]; + const defaultProviderConfig = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider]; + const statusKey = liveProvider?.status ?? (providerConfig.enabled ? "warning" : "disabled"); + const summary = getProviderSummary(liveProvider); + const models: ReadonlyArray = + liveProvider?.models ?? + providerConfig.customModels.map((slug) => ({ + slug, + name: slug, + isCustom: true, + capabilities: null, + })); + + return { + provider: providerSettings.provider, + title: providerSettings.title, + binaryPlaceholder: providerSettings.binaryPlaceholder, + binaryDescription: providerSettings.binaryDescription, + homePathKey: providerSettings.homePathKey, + homePlaceholder: providerSettings.homePlaceholder, + homeDescription: providerSettings.homeDescription, + binaryPathValue: providerConfig.binaryPath, + isDirty: !Equal.equals(providerConfig, defaultProviderConfig), + liveProvider, + models, + providerConfig, + statusStyle: PROVIDER_STATUS_STYLES[statusKey], + summary, + versionLabel: getProviderVersionLabel(liveProvider?.version), + }; + }); + + const lastCheckedAt = + serverProviders.length > 0 + ? serverProviders.reduce( + (latest, provider) => (provider.checkedAt > latest ? provider.checkedAt : latest), + serverProviders[0]!.checkedAt, + ) + : null; + return ( + + + setTheme("system")} /> + ) : null + } + control={ + + } + /> + + + updateSettings({ + timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, + }) + } + /> + ) : null + } + control={ + + } + /> + + + updateSettings({ + diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap, + }) + } + /> + ) : null + } + control={ + updateSettings({ diffWordWrap: Boolean(checked) })} + aria-label="Wrap diff lines by default" + /> + } + /> + + + updateSettings({ + enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming, + }) + } + /> + ) : null + } + control={ + + updateSettings({ enableAssistantStreaming: Boolean(checked) }) + } + aria-label="Stream assistant messages" + /> + } + /> + + + updateSettings({ + defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode, + }) + } + /> + ) : null + } + control={ + + } + /> + + + updateSettings({ + confirmThreadArchive: DEFAULT_UNIFIED_SETTINGS.confirmThreadArchive, + }) + } + /> + ) : null + } + control={ + + updateSettings({ confirmThreadArchive: Boolean(checked) }) + } + aria-label="Confirm thread archiving" + /> + } + /> + + + updateSettings({ + confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete, + }) + } + /> + ) : null + } + control={ + + updateSettings({ confirmThreadDelete: Boolean(checked) }) + } + aria-label="Confirm thread deletion" + /> + } + /> + + + updateSettings({ + textGenerationModelSelection: + DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, + }) + } + /> + ) : null + } + control={ +
+ { + updateSettings({ + textGenerationModelSelection: resolveAppModelSelectionState( + { + ...settings, + textGenerationModelSelection: { provider, model }, + }, + serverProviders, + ), + }); + }} + /> + provider.provider === textGenProvider) + ?.models ?? [] + } + model={textGenModel} + prompt="" + onPromptChange={() => {}} + modelOptions={textGenModelOptions} + allowPromptInjectedEffort={false} + triggerVariant="outline" + triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground" + onModelOptionsChange={(nextOptions) => { + updateSettings({ + textGenerationModelSelection: resolveAppModelSelectionState( + { + ...settings, + textGenerationModelSelection: { + provider: textGenProvider, + model: textGenModel, + ...(nextOptions ? { options: nextOptions } : {}), + }, + }, + serverProviders, + ), + }); + }} + /> +
+ } + /> +
+ + + + + void refreshProviders()} + aria-label="Refresh provider status" + > + {isRefreshingProviders ? ( + + ) : ( + + )} + + } + /> + Refresh provider status + +
+ } + > + {providerCards.map((providerCard) => { + const customModelInput = customModelInputByProvider[providerCard.provider]; + const customModelError = customModelErrorByProvider[providerCard.provider] ?? null; + const providerDisplayName = + PROVIDER_DISPLAY_NAMES[providerCard.provider] ?? providerCard.title; + + return ( +
+
+
+
+
+ +

{providerDisplayName}

+ {providerCard.versionLabel ? ( + + {providerCard.versionLabel} + + ) : null} + + {providerCard.isDirty ? ( + { + updateSettings({ + providers: { + ...settings.providers, + [providerCard.provider]: + DEFAULT_UNIFIED_SETTINGS.providers[providerCard.provider], + }, + }); + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [providerCard.provider]: null, + })); + }} + /> + ) : null} + +
+

+ {providerCard.summary.headline} + {providerCard.summary.detail ? ` - ${providerCard.summary.detail}` : null} +

+
+
+ + { + const isDisabling = !checked; + const shouldClearModelSelection = + isDisabling && textGenProvider === providerCard.provider; + updateSettings({ + providers: { + ...settings.providers, + [providerCard.provider]: { + ...settings.providers[providerCard.provider], + enabled: Boolean(checked), + }, + }, + ...(shouldClearModelSelection + ? { + textGenerationModelSelection: + DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, + } + : {}), + }); + }} + aria-label={`Enable ${providerDisplayName}`} + /> +
+
+
+ + + setOpenProviderDetails((existing) => ({ + ...existing, + [providerCard.provider]: open, + })) + } + > + +
+
+ +
+ + {providerCard.homePathKey ? ( +
+ +
+ ) : null} + +
+
Models
+
+ {providerCard.models.length} model + {providerCard.models.length === 1 ? "" : "s"} available. +
+
{ + modelListRefs.current[providerCard.provider] = el; + }} + className="mt-2 max-h-40 overflow-y-auto pb-1" + > + {providerCard.models.map((model) => { + const caps = model.capabilities; + const capLabels: string[] = []; + if (caps?.supportsFastMode) capLabels.push("Fast mode"); + if (caps?.supportsThinkingToggle) capLabels.push("Thinking"); + if ( + caps?.reasoningEffortLevels && + caps.reasoningEffortLevels.length > 0 + ) { + capLabels.push("Reasoning"); + } + const hasDetails = capLabels.length > 0 || model.name !== model.slug; + + return ( +
+ + {model.name} + + {hasDetails ? ( + + + } + > + + + +
+ + {model.slug} + + {capLabels.length > 0 ? ( +
+ {capLabels.map((label) => ( + + {label} + + ))} +
+ ) : null} +
+
+
+ ) : null} + {model.isCustom ? ( +
+ custom + +
+ ) : null} +
+ ); + })} +
+ +
+ { + const value = event.target.value; + setCustomModelInputByProvider((existing) => ({ + ...existing, + [providerCard.provider]: value, + })); + if (customModelError) { + setCustomModelErrorByProvider((existing) => ({ + ...existing, + [providerCard.provider]: null, + })); + } + }} + onKeyDown={(event) => { + if (event.key !== "Enter") return; + event.preventDefault(); + addCustomModel(providerCard.provider); + }} + placeholder={ + providerCard.provider === "codex" + ? "gpt-6.7-codex-ultra-preview" + : "claude-sonnet-5-0" + } + spellCheck={false} + /> + +
+ + {customModelError ? ( +

{customModelError}

+ ) : null} +
+
+
+
+
+ ); + })} + + + + + + {keybindingsConfigPath ?? "Resolving keybindings path..."} + + {openKeybindingsError ? ( + {openKeybindingsError} + ) : ( + Opens in your preferred editor. + )} + + } + control={ + + } + /> + + {APP_VERSION}} + /> + + + ); +} + +export function ArchivedThreadsPanel() { + const projects = useStore((store) => store.projects); + const threads = useStore((store) => store.threads); + const { unarchiveThread, confirmAndDeleteThread } = useThreadActions(); + const archivedGroups = useMemo(() => { + const projectById = new Map(projects.map((project) => [project.id, project] as const)); + return [...projectById.values()] + .map((project) => ({ + project, + threads: threads + .filter((thread) => thread.projectId === project.id && thread.archivedAt !== null) + .toSorted((left, right) => { + const leftKey = left.archivedAt ?? left.createdAt; + const rightKey = right.archivedAt ?? right.createdAt; + return rightKey.localeCompare(leftKey) || right.id.localeCompare(left.id); + }), + })) + .filter((group) => group.threads.length > 0); + }, [projects, threads]); + + const handleArchivedThreadContextMenu = useCallback( + async (threadId: ThreadId, position: { x: number; y: number }) => { + const api = readNativeApi(); + if (!api) return; + const clicked = await api.contextMenu.show( + [ + { id: "unarchive", label: "Unarchive" }, + { id: "delete", label: "Delete", destructive: true }, + ], + position, + ); + + if (clicked === "unarchive") { + try { + await unarchiveThread(threadId); + } catch (error) { + toastManager.add({ + type: "error", + title: "Failed to unarchive thread", + description: error instanceof Error ? error.message : "An error occurred.", + }); + } + return; + } + + if (clicked === "delete") { + await confirmAndDeleteThread(threadId); + } + }, + [confirmAndDeleteThread, unarchiveThread], + ); + + return ( + + {archivedGroups.length === 0 ? ( + + + + + + + No archived threads + Archived threads will appear here. + + + + ) : ( + archivedGroups.map(({ project, threads: projectThreads }) => ( + } + > + {projectThreads.map((thread) => ( +
{ + event.preventDefault(); + void handleArchivedThreadContextMenu(thread.id, { + x: event.clientX, + y: event.clientY, + }); + }} + > +
+

{thread.title}

+

+ Archived {formatRelativeTimeLabel(thread.archivedAt ?? thread.createdAt)} + {" \u00b7 Created "} + {formatRelativeTimeLabel(thread.createdAt)} +

+
+ +
+ ))} +
+ )) + )} +
+ ); +} diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx new file mode 100644 index 0000000000..ffca1e2092 --- /dev/null +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -0,0 +1,82 @@ +import type { ComponentType } from "react"; +import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react"; +import { useNavigate } from "@tanstack/react-router"; + +import { + SidebarContent, + SidebarFooter, + SidebarGroup, + SidebarMenu, + SidebarMenuButton, + SidebarMenuItem, + SidebarSeparator, +} from "../ui/sidebar"; + +export type SettingsSectionPath = "/settings/general" | "/settings/archived"; + +export const SETTINGS_NAV_ITEMS: ReadonlyArray<{ + label: string; + to: SettingsSectionPath; + icon: ComponentType<{ className?: string }>; +}> = [ + { label: "General", to: "/settings/general", icon: Settings2Icon }, + { label: "Archived threads", to: "/settings/archived", icon: ArchiveIcon }, +]; + +export function SettingsSidebarNav({ pathname }: { pathname: string }) { + const navigate = useNavigate(); + + return ( + <> + + + + {SETTINGS_NAV_ITEMS.map((item) => { + const Icon = item.icon; + const isActive = pathname === item.to; + return ( + + void navigate({ to: item.to, replace: true })} + > + + {item.label} + + + ); + })} + + + + + + + + + window.history.back()} + > + + Back + + + + + + ); +} diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts index 63cdef8481..9fd1a12956 100644 --- a/apps/web/src/contextMenuFallback.ts +++ b/apps/web/src/contextMenuFallback.ts @@ -44,10 +44,16 @@ export function showContextMenuFallback( btn.type = "button"; btn.textContent = item.label; const isDestructiveAction = item.destructive === true || item.id === "delete"; - btn.className = isDestructiveAction - ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default" - : "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default"; - btn.addEventListener("click", () => cleanup(item.id)); + const isDisabled = item.disabled === true; + btn.disabled = isDisabled; + btn.className = isDisabled + ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-muted-foreground/60 cursor-not-allowed" + : isDestructiveAction + ? "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-destructive hover:bg-accent cursor-default" + : "flex w-full items-center gap-2 px-3 py-1.5 text-left text-[11px] text-popover-foreground hover:bg-accent cursor-default"; + if (!isDisabled) { + btn.addEventListener("click", () => cleanup(item.id)); + } menu.appendChild(btn); } diff --git a/apps/web/src/hooks/useSettings.test.ts b/apps/web/src/hooks/useSettings.test.ts new file mode 100644 index 0000000000..832ee17f7f --- /dev/null +++ b/apps/web/src/hooks/useSettings.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; +import { buildLegacyClientSettingsMigrationPatch } from "./useSettings"; + +describe("buildLegacyClientSettingsMigrationPatch", () => { + it("migrates archive confirmation from legacy local settings", () => { + expect( + buildLegacyClientSettingsMigrationPatch({ + confirmThreadArchive: true, + confirmThreadDelete: false, + }), + ).toEqual({ + confirmThreadArchive: true, + confirmThreadDelete: false, + }); + }); +}); diff --git a/apps/web/src/hooks/useSettings.ts b/apps/web/src/hooks/useSettings.ts index addf550e38..3f804bc48b 100644 --- a/apps/web/src/hooks/useSettings.ts +++ b/apps/web/src/hooks/useSettings.ts @@ -202,6 +202,10 @@ export function buildLegacyClientSettingsMigrationPatch( ): Partial> { const patch: Partial> = {}; + if (Predicate.isBoolean(legacySettings.confirmThreadArchive)) { + patch.confirmThreadArchive = legacySettings.confirmThreadArchive; + } + if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) { patch.confirmThreadDelete = legacySettings.confirmThreadDelete; } diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts new file mode 100644 index 0000000000..83cfe911fc --- /dev/null +++ b/apps/web/src/hooks/useThreadActions.ts @@ -0,0 +1,211 @@ +import { ThreadId } from "@t3tools/contracts"; +import { useMutation, useQueryClient } from "@tanstack/react-query"; +import { useNavigate, useParams } from "@tanstack/react-router"; +import { useCallback } from "react"; + +import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic"; +import { useComposerDraftStore } from "../composerDraftStore"; +import { useHandleNewThread } from "./useHandleNewThread"; +import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery"; +import { newCommandId } from "../lib/utils"; +import { readNativeApi } from "../nativeApi"; +import { useStore } from "../store"; +import { useTerminalStateStore } from "../terminalStateStore"; +import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup"; +import { toastManager } from "../components/ui/toast"; +import { useSettings } from "./useSettings"; + +export function useThreadActions() { + const threads = useStore((store) => store.threads); + const projects = useStore((store) => store.projects); + const appSettings = useSettings(); + const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); + const clearProjectDraftThreadById = useComposerDraftStore( + (store) => store.clearProjectDraftThreadById, + ); + const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState); + const routeThreadId = useParams({ + strict: false, + select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), + }); + const navigate = useNavigate(); + const { handleNewThread } = useHandleNewThread(); + const queryClient = useQueryClient(); + const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient })); + + const archiveThread = useCallback( + async (threadId: ThreadId) => { + const api = readNativeApi(); + if (!api) return; + const thread = threads.find((entry) => entry.id === threadId); + if (!thread) return; + if (thread.session?.status === "running" && thread.session.activeTurnId != null) { + throw new Error("Cannot archive a running thread."); + } + + await api.orchestration.dispatchCommand({ + type: "thread.archive", + commandId: newCommandId(), + threadId, + }); + + if (routeThreadId === threadId) { + await handleNewThread(thread.projectId); + } + }, + [handleNewThread, routeThreadId, threads], + ); + + const unarchiveThread = useCallback(async (threadId: ThreadId) => { + const api = readNativeApi(); + if (!api) return; + await api.orchestration.dispatchCommand({ + type: "thread.unarchive", + commandId: newCommandId(), + threadId, + }); + }, []); + + const deleteThread = useCallback( + async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet } = {}) => { + const api = readNativeApi(); + if (!api) return; + const thread = threads.find((entry) => entry.id === threadId); + if (!thread) return; + const threadProject = projects.find((project) => project.id === thread.projectId); + const deletedIds = opts.deletedThreadIds; + const survivingThreads = + deletedIds && deletedIds.size > 0 + ? threads.filter((entry) => entry.id === threadId || !deletedIds.has(entry.id)) + : threads; + const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId); + const displayWorktreePath = orphanedWorktreePath + ? formatWorktreePathForDisplay(orphanedWorktreePath) + : null; + const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined; + const shouldDeleteWorktree = + canDeleteWorktree && + (await api.dialogs.confirm( + [ + "This thread is the only one linked to this worktree:", + displayWorktreePath ?? orphanedWorktreePath, + "", + "Delete the worktree too?", + ].join("\n"), + )); + + if (thread.session && thread.session.status !== "closed") { + await api.orchestration + .dispatchCommand({ + type: "thread.session.stop", + commandId: newCommandId(), + threadId, + createdAt: new Date().toISOString(), + }) + .catch(() => undefined); + } + + try { + await api.terminal.close({ threadId, deleteHistory: true }); + } catch { + // Terminal may already be closed. + } + + const deletedThreadIds = opts.deletedThreadIds ?? new Set(); + const shouldNavigateToFallback = routeThreadId === threadId; + const fallbackThreadId = getFallbackThreadIdAfterDelete({ + threads, + deletedThreadId: threadId, + deletedThreadIds, + sortOrder: appSettings.sidebarThreadSortOrder, + }); + await api.orchestration.dispatchCommand({ + type: "thread.delete", + commandId: newCommandId(), + threadId, + }); + clearComposerDraftForThread(threadId); + clearProjectDraftThreadById(thread.projectId, thread.id); + clearTerminalState(threadId); + + if (shouldNavigateToFallback) { + if (fallbackThreadId) { + await navigate({ + to: "/$threadId", + params: { threadId: fallbackThreadId }, + replace: true, + }); + } else { + await navigate({ to: "/", replace: true }); + } + } + + if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) { + return; + } + + try { + await removeWorktreeMutation.mutateAsync({ + cwd: threadProject.cwd, + path: orphanedWorktreePath, + force: true, + }); + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error removing worktree."; + console.error("Failed to remove orphaned worktree after thread deletion", { + threadId, + projectCwd: threadProject.cwd, + worktreePath: orphanedWorktreePath, + error, + }); + toastManager.add({ + type: "error", + title: "Thread deleted, but worktree removal failed", + description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`, + }); + } + }, + [ + clearComposerDraftForThread, + clearProjectDraftThreadById, + clearTerminalState, + appSettings.sidebarThreadSortOrder, + navigate, + projects, + removeWorktreeMutation, + routeThreadId, + threads, + ], + ); + + const confirmAndDeleteThread = useCallback( + async (threadId: ThreadId) => { + const api = readNativeApi(); + if (!api) return; + const thread = threads.find((entry) => entry.id === threadId); + if (!thread) return; + + if (appSettings.confirmThreadDelete) { + const confirmed = await api.dialogs.confirm( + [ + `Delete thread "${thread.title}"?`, + "This permanently clears conversation history for this thread.", + ].join("\n"), + ); + if (!confirmed) { + return; + } + } + + await deleteThread(threadId); + }, + [appSettings.confirmThreadDelete, deleteThread, threads], + ); + + return { + archiveThread, + unarchiveThread, + deleteThread, + confirmAndDeleteThread, + }; +} diff --git a/apps/web/src/lib/storage.ts b/apps/web/src/lib/storage.ts index eeb3a03a82..a37c67064a 100644 --- a/apps/web/src/lib/storage.ts +++ b/apps/web/src/lib/storage.ts @@ -23,25 +23,42 @@ export function createMemoryStorage(): StateStorage { }; } +export function isStateStorage( + storage: Partial | null | undefined, +): storage is StateStorage { + return ( + storage !== null && + storage !== undefined && + typeof storage.getItem === "function" && + typeof storage.setItem === "function" && + typeof storage.removeItem === "function" + ); +} + +export function resolveStorage(storage: Partial | null | undefined): StateStorage { + return isStateStorage(storage) ? storage : createMemoryStorage(); +} + export function createDebouncedStorage( - baseStorage: StateStorage, + baseStorage: Partial | null | undefined, debounceMs: number = 300, ): DebouncedStorage { + const resolvedStorage = resolveStorage(baseStorage); const debouncedSetItem = new Debouncer( (name: string, value: string) => { - baseStorage.setItem(name, value); + resolvedStorage.setItem(name, value); }, { wait: debounceMs }, ); return { - getItem: (name) => baseStorage.getItem(name), + getItem: (name) => resolvedStorage.getItem(name), setItem: (name, value) => { debouncedSetItem.maybeExecute(name, value); }, removeItem: (name) => { debouncedSetItem.cancel(); - baseStorage.removeItem(name); + resolvedStorage.removeItem(name); }, flush: () => { debouncedSetItem.flush(); diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.ts index 880d5ef64b..77b1b15842 100644 --- a/apps/web/src/routeTree.gen.ts +++ b/apps/web/src/routeTree.gen.ts @@ -9,11 +9,18 @@ // Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified. import { Route as rootRouteImport } from './routes/__root' +import { Route as SettingsRouteImport } from './routes/settings' import { Route as ChatRouteImport } from './routes/_chat' import { Route as ChatIndexRouteImport } from './routes/_chat.index' -import { Route as ChatSettingsRouteImport } from './routes/_chat.settings' +import { Route as SettingsGeneralRouteImport } from './routes/settings.general' +import { Route as SettingsArchivedRouteImport } from './routes/settings.archived' import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId' +const SettingsRoute = SettingsRouteImport.update({ + id: '/settings', + path: '/settings', + getParentRoute: () => rootRouteImport, +} as any) const ChatRoute = ChatRouteImport.update({ id: '/_chat', getParentRoute: () => rootRouteImport, @@ -23,10 +30,15 @@ const ChatIndexRoute = ChatIndexRouteImport.update({ path: '/', getParentRoute: () => ChatRoute, } as any) -const ChatSettingsRoute = ChatSettingsRouteImport.update({ - id: '/settings', - path: '/settings', - getParentRoute: () => ChatRoute, +const SettingsGeneralRoute = SettingsGeneralRouteImport.update({ + id: '/general', + path: '/general', + getParentRoute: () => SettingsRoute, +} as any) +const SettingsArchivedRoute = SettingsArchivedRouteImport.update({ + id: '/archived', + path: '/archived', + getParentRoute: () => SettingsRoute, } as any) const ChatThreadIdRoute = ChatThreadIdRouteImport.update({ id: '/$threadId', @@ -36,35 +48,66 @@ const ChatThreadIdRoute = ChatThreadIdRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof ChatIndexRoute + '/settings': typeof SettingsRouteWithChildren '/$threadId': typeof ChatThreadIdRoute - '/settings': typeof ChatSettingsRoute + '/settings/archived': typeof SettingsArchivedRoute + '/settings/general': typeof SettingsGeneralRoute } export interface FileRoutesByTo { + '/settings': typeof SettingsRouteWithChildren '/$threadId': typeof ChatThreadIdRoute - '/settings': typeof ChatSettingsRoute + '/settings/archived': typeof SettingsArchivedRoute + '/settings/general': typeof SettingsGeneralRoute '/': typeof ChatIndexRoute } export interface FileRoutesById { __root__: typeof rootRouteImport '/_chat': typeof ChatRouteWithChildren + '/settings': typeof SettingsRouteWithChildren '/_chat/$threadId': typeof ChatThreadIdRoute - '/_chat/settings': typeof ChatSettingsRoute + '/settings/archived': typeof SettingsArchivedRoute + '/settings/general': typeof SettingsGeneralRoute '/_chat/': typeof ChatIndexRoute } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: '/' | '/$threadId' | '/settings' + fullPaths: + | '/' + | '/settings' + | '/$threadId' + | '/settings/archived' + | '/settings/general' fileRoutesByTo: FileRoutesByTo - to: '/$threadId' | '/settings' | '/' - id: '__root__' | '/_chat' | '/_chat/$threadId' | '/_chat/settings' | '/_chat/' + to: + | '/settings' + | '/$threadId' + | '/settings/archived' + | '/settings/general' + | '/' + id: + | '__root__' + | '/_chat' + | '/settings' + | '/_chat/$threadId' + | '/settings/archived' + | '/settings/general' + | '/_chat/' fileRoutesById: FileRoutesById } export interface RootRouteChildren { ChatRoute: typeof ChatRouteWithChildren + SettingsRoute: typeof SettingsRouteWithChildren } declare module '@tanstack/react-router' { interface FileRoutesByPath { + '/settings': { + id: '/settings' + path: '/settings' + fullPath: '/settings' + preLoaderRoute: typeof SettingsRouteImport + parentRoute: typeof rootRouteImport + } '/_chat': { id: '/_chat' path: '' @@ -79,12 +122,19 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof ChatIndexRouteImport parentRoute: typeof ChatRoute } - '/_chat/settings': { - id: '/_chat/settings' - path: '/settings' - fullPath: '/settings' - preLoaderRoute: typeof ChatSettingsRouteImport - parentRoute: typeof ChatRoute + '/settings/general': { + id: '/settings/general' + path: '/general' + fullPath: '/settings/general' + preLoaderRoute: typeof SettingsGeneralRouteImport + parentRoute: typeof SettingsRoute + } + '/settings/archived': { + id: '/settings/archived' + path: '/archived' + fullPath: '/settings/archived' + preLoaderRoute: typeof SettingsArchivedRouteImport + parentRoute: typeof SettingsRoute } '/_chat/$threadId': { id: '/_chat/$threadId' @@ -98,20 +148,33 @@ declare module '@tanstack/react-router' { interface ChatRouteChildren { ChatThreadIdRoute: typeof ChatThreadIdRoute - ChatSettingsRoute: typeof ChatSettingsRoute ChatIndexRoute: typeof ChatIndexRoute } const ChatRouteChildren: ChatRouteChildren = { ChatThreadIdRoute: ChatThreadIdRoute, - ChatSettingsRoute: ChatSettingsRoute, ChatIndexRoute: ChatIndexRoute, } const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren) +interface SettingsRouteChildren { + SettingsArchivedRoute: typeof SettingsArchivedRoute + SettingsGeneralRoute: typeof SettingsGeneralRoute +} + +const SettingsRouteChildren: SettingsRouteChildren = { + SettingsArchivedRoute: SettingsArchivedRoute, + SettingsGeneralRoute: SettingsGeneralRoute, +} + +const SettingsRouteWithChildren = SettingsRoute._addFileChildren( + SettingsRouteChildren, +) + const rootRouteChildren: RootRouteChildren = { ChatRoute: ChatRouteWithChildren, + SettingsRoute: SettingsRouteWithChildren, } export const routeTree = rootRouteImport ._addFileChildren(rootRouteChildren) diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 5ebed20fba..e99ec50226 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -11,6 +11,7 @@ import { QueryClient, useQueryClient } from "@tanstack/react-query"; import { Throttler } from "@tanstack/react-pacer"; import { APP_DISPLAY_NAME } from "../branding"; +import { AppSidebarLayout } from "../components/AppSidebarLayout"; import { Button } from "../components/ui/button"; import { AnchoredToastProvider, ToastProvider, toastManager } from "../components/ui/toast"; import { resolveAndPersistPreferredEditor } from "../editorPreferences"; @@ -54,7 +55,9 @@ function RootRouteView() { - + + + ); diff --git a/apps/web/src/routes/_chat.settings.tsx b/apps/web/src/routes/_chat.settings.tsx deleted file mode 100644 index 3e92891a54..0000000000 --- a/apps/web/src/routes/_chat.settings.tsx +++ /dev/null @@ -1,1313 +0,0 @@ -import { createFileRoute } from "@tanstack/react-router"; -import { useQuery, useQueryClient } from "@tanstack/react-query"; -import { - ChevronDownIcon, - InfoIcon, - LoaderIcon, - PlusIcon, - RefreshCwIcon, - RotateCcwIcon, - Undo2Icon, - XIcon, -} from "lucide-react"; -import { type ReactNode, useCallback, useEffect, useRef, useState } from "react"; -import { - PROVIDER_DISPLAY_NAMES, - type ProviderKind, - type ServerProvider, - type ServerProviderModel, -} from "@t3tools/contracts"; -import { normalizeModelSlug } from "@t3tools/shared/model"; -import { useSettings, useUpdateSettings } from "../hooks/useSettings"; -import { - getCustomModelOptionsByProvider, - MAX_CUSTOM_MODEL_LENGTH, - resolveAppModelSelectionState, -} from "../modelSelection"; -import { APP_VERSION } from "../branding"; -import { Button } from "../components/ui/button"; -import { Collapsible, CollapsibleContent } from "../components/ui/collapsible"; -import { Input } from "../components/ui/input"; -import { - Select, - SelectItem, - SelectPopup, - SelectTrigger, - SelectValue, -} from "../components/ui/select"; -import { SidebarTrigger } from "../components/ui/sidebar"; -import { Switch } from "../components/ui/switch"; -import { ProviderModelPicker } from "../components/chat/ProviderModelPicker"; -import { TraitsPicker } from "../components/chat/TraitsPicker"; -import { SidebarInset } from "../components/ui/sidebar"; -import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip"; -import { resolveAndPersistPreferredEditor } from "../editorPreferences"; -import { isElectron } from "../env"; -import { useTheme } from "../hooks/useTheme"; -import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery"; -import { cn } from "../lib/utils"; -import { formatRelativeTime } from "../timestampFormat"; -import { ensureNativeApi, readNativeApi } from "../nativeApi"; -import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; -import { Equal } from "effect"; - -const THEME_OPTIONS = [ - { - value: "system", - label: "System", - description: "Match your OS appearance setting.", - }, - { - value: "light", - label: "Light", - description: "Always use the light theme.", - }, - { - value: "dark", - label: "Dark", - description: "Always use the dark theme.", - }, -] as const; - -const TIMESTAMP_FORMAT_LABELS = { - locale: "System default", - "12-hour": "12-hour", - "24-hour": "24-hour", -} as const; - -const EMPTY_SERVER_PROVIDERS: ReadonlyArray = []; - -type InstallProviderSettings = { - provider: ProviderKind; - title: string; - binaryPlaceholder: string; - binaryDescription: ReactNode; - homePathKey?: "codexHomePath"; - homePlaceholder?: string; - homeDescription?: ReactNode; -}; - -const PROVIDER_SETTINGS: readonly InstallProviderSettings[] = [ - { - provider: "codex", - title: "Codex", - binaryPlaceholder: "Codex binary path", - binaryDescription: "Path to the Codex binary", - homePathKey: "codexHomePath", - homePlaceholder: "CODEX_HOME", - homeDescription: "Optional custom Codex home and config directory.", - }, - { - provider: "claudeAgent", - title: "Claude", - binaryPlaceholder: "Claude binary path", - binaryDescription: "Path to the Claude binary", - }, -]; - -const PROVIDER_STATUS_STYLES = { - disabled: { - dot: "bg-amber-400", - badge: "warning" as const, - }, - error: { - dot: "bg-destructive", - badge: "error" as const, - }, - ready: { - dot: "bg-success", - badge: "success" as const, - }, - warning: { - dot: "bg-warning", - badge: "warning" as const, - }, -} as const; - -function getProviderSummary(provider: ServerProvider | undefined): { - readonly headline: string; - readonly detail: string | null; -} { - if (!provider) { - return { - headline: "Checking provider status", - detail: "Waiting for the server to report installation and authentication details.", - }; - } - if (!provider.enabled) { - return { - headline: "Disabled", - detail: - provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.", - }; - } - if (!provider.installed) { - return { - headline: "Not found", - detail: provider.message ?? "CLI not detected on PATH.", - }; - } - if (provider.authStatus === "authenticated") { - return { - headline: "Authenticated", - detail: provider.message ?? null, - }; - } - if (provider.authStatus === "unauthenticated") { - return { - headline: "Not authenticated", - detail: provider.message ?? null, - }; - } - if (provider.status === "warning") { - return { - headline: "Needs attention", - detail: - provider.message ?? "The provider is installed, but the server could not fully verify it.", - }; - } - if (provider.status === "error") { - return { - headline: "Unavailable", - detail: provider.message ?? "The provider failed its startup checks.", - }; - } - return { - headline: "Available", - detail: provider.message ?? "Installed and ready, but authentication could not be verified.", - }; -} - -function getProviderVersionLabel(version: string | null | undefined): string | null { - if (!version) return null; - return version.startsWith("v") ? version : `v${version}`; -} - -/** Returns a timestamp that updates on an interval, forcing re-renders to keep relative times fresh. */ -function useRelativeTimeTick(intervalMs = 1_000): number { - const [tick, setTick] = useState(() => Date.now()); - useEffect(() => { - const id = setInterval(() => setTick(Date.now()), intervalMs); - return () => clearInterval(id); - }, [intervalMs]); - return tick; -} - -function SettingsSection({ - title, - headerAction, - children, -}: { - title: string; - headerAction?: ReactNode; - children: ReactNode; -}) { - return ( -
-
-

- {title} -

- {headerAction} -
-
- {children} -
-
- ); -} - -function SettingsRow({ - title, - description, - status, - resetAction, - control, - children, -}: { - title: string; - description: string; - status?: ReactNode; - resetAction?: ReactNode; - control?: ReactNode; - children?: ReactNode; -}) { - return ( -
-
-
-
-

{title}

- - {resetAction} - -
-

{description}

- {status ?
{status}
: null} -
- {control ? ( -
- {control} -
- ) : null} -
- {children} -
- ); -} - -function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) { - return ( - - { - event.stopPropagation(); - onClick(); - }} - > - - - } - /> - Reset to default - - ); -} - -function SettingsRouteView() { - const { theme, setTheme } = useTheme(); - const settings = useSettings(); - const { updateSettings, resetSettings } = useUpdateSettings(); - const serverConfigQuery = useQuery(serverConfigQueryOptions()); - const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false); - const [openKeybindingsError, setOpenKeybindingsError] = useState(null); - const [openProviderDetails, setOpenProviderDetails] = useState>({ - codex: Boolean( - settings.providers.codex.binaryPath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.binaryPath || - settings.providers.codex.homePath !== DEFAULT_UNIFIED_SETTINGS.providers.codex.homePath || - settings.providers.codex.customModels.length > 0, - ), - claudeAgent: Boolean( - settings.providers.claudeAgent.binaryPath !== - DEFAULT_UNIFIED_SETTINGS.providers.claudeAgent.binaryPath || - settings.providers.claudeAgent.customModels.length > 0, - ), - }); - const [customModelInputByProvider, setCustomModelInputByProvider] = useState< - Record - >({ - codex: "", - claudeAgent: "", - }); - const [customModelErrorByProvider, setCustomModelErrorByProvider] = useState< - Partial> - >({}); - const [isRefreshingProviders, setIsRefreshingProviders] = useState(false); - const refreshingRef = useRef(false); - const queryClient = useQueryClient(); - useRelativeTimeTick(); - - const refreshProviders = useCallback(() => { - if (refreshingRef.current) return; - refreshingRef.current = true; - setIsRefreshingProviders(true); - const api = ensureNativeApi(); - api.server - .refreshProviders() - .then(() => queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() })) - .catch((error: unknown) => { - console.warn("Failed to refresh providers", error); - }) - .finally(() => { - refreshingRef.current = false; - setIsRefreshingProviders(false); - }); - }, [queryClient]); - - const modelListRefs = useRef>>({}); - - const codexHomePath = settings.providers.codex.homePath; - const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null; - const availableEditors = serverConfigQuery.data?.availableEditors; - const serverProviders = serverConfigQuery.data?.providers ?? EMPTY_SERVER_PROVIDERS; - - const textGenerationModelSelection = resolveAppModelSelectionState(settings, serverProviders); - const textGenProvider = textGenerationModelSelection.provider; - const textGenModel = textGenerationModelSelection.model; - const textGenModelOptions = textGenerationModelSelection.options; - const gitModelOptionsByProvider = getCustomModelOptionsByProvider( - settings, - serverProviders, - textGenProvider, - textGenModel, - ); - const areProviderSettingsDirty = PROVIDER_SETTINGS.some((providerSettings) => { - const currentSettings = settings.providers[providerSettings.provider]; - const defaultSettings = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider]; - return !Equal.equals(currentSettings, defaultSettings); - }); - const isGitWritingModelDirty = !Equal.equals( - settings.textGenerationModelSelection ?? null, - DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null, - ); - const changedSettingLabels = [ - ...(theme !== "system" ? ["Theme"] : []), - ...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat - ? ["Time format"] - : []), - ...(settings.diffWordWrap !== DEFAULT_UNIFIED_SETTINGS.diffWordWrap - ? ["Diff line wrapping"] - : []), - ...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming - ? ["Assistant output"] - : []), - ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode - ? ["New thread mode"] - : []), - ...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete - ? ["Delete confirmation"] - : []), - ...(isGitWritingModelDirty ? ["Git writing model"] : []), - ...(areProviderSettingsDirty ? ["Providers"] : []), - ]; - - const openKeybindingsFile = useCallback(() => { - if (!keybindingsConfigPath) return; - setOpenKeybindingsError(null); - setIsOpeningKeybindings(true); - const api = ensureNativeApi(); - const editor = resolveAndPersistPreferredEditor(availableEditors ?? []); - if (!editor) { - setOpenKeybindingsError("No available editors found."); - setIsOpeningKeybindings(false); - return; - } - void api.shell - .openInEditor(keybindingsConfigPath, editor) - .catch((error) => { - setOpenKeybindingsError( - error instanceof Error ? error.message : "Unable to open keybindings file.", - ); - }) - .finally(() => { - setIsOpeningKeybindings(false); - }); - }, [availableEditors, keybindingsConfigPath]); - - const addCustomModel = useCallback( - (provider: ProviderKind) => { - const customModelInput = customModelInputByProvider[provider]; - const customModels = settings.providers[provider].customModels; - const normalized = normalizeModelSlug(customModelInput, provider); - if (!normalized) { - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: "Enter a model slug.", - })); - return; - } - if ( - serverProviders - .find((candidate) => candidate.provider === provider) - ?.models.some((option) => !option.isCustom && option.slug === normalized) - ) { - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: "That model is already built in.", - })); - return; - } - if (normalized.length > MAX_CUSTOM_MODEL_LENGTH) { - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: `Model slugs must be ${MAX_CUSTOM_MODEL_LENGTH} characters or less.`, - })); - return; - } - if (customModels.includes(normalized)) { - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: "That custom model is already saved.", - })); - return; - } - - updateSettings({ - providers: { - ...settings.providers, - [provider]: { - ...settings.providers[provider], - customModels: [...customModels, normalized], - }, - }, - }); - setCustomModelInputByProvider((existing) => ({ - ...existing, - [provider]: "", - })); - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: null, - })); - // Watch for DOM changes (server may push updated model list) and scroll to bottom - const el = modelListRefs.current[provider]; - if (el) { - const scrollToEnd = () => el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); - // Immediate scroll for the optimistic update - requestAnimationFrame(scrollToEnd); - // Also observe mutations for when the server pushes an updated list - const observer = new MutationObserver(() => { - scrollToEnd(); - observer.disconnect(); - }); - observer.observe(el, { childList: true, subtree: true }); - // Clean up observer after a reasonable window - setTimeout(() => observer.disconnect(), 2000); - } - }, - [customModelInputByProvider, serverProviders, settings, updateSettings], - ); - - const removeCustomModel = useCallback( - (provider: ProviderKind, slug: string) => { - const customModels = settings.providers[provider].customModels; - updateSettings({ - providers: { - ...settings.providers, - [provider]: { - ...settings.providers[provider], - customModels: customModels.filter((model) => model !== slug), - }, - }, - }); - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [provider]: null, - })); - }, - [settings, updateSettings], - ); - - const providerCards = PROVIDER_SETTINGS.map((providerSettings) => { - const liveProvider = serverProviders.find( - (candidate) => candidate.provider === providerSettings.provider, - ); - const providerConfig = settings.providers[providerSettings.provider]; - const defaultProviderConfig = DEFAULT_UNIFIED_SETTINGS.providers[providerSettings.provider]; - const statusKey = liveProvider?.status ?? (providerConfig.enabled ? "warning" : "disabled"); - const statusStyle = PROVIDER_STATUS_STYLES[statusKey]; - const summary = getProviderSummary(liveProvider); - const models: ReadonlyArray = - liveProvider?.models ?? - providerConfig.customModels.map((slug) => ({ - slug, - name: slug, - isCustom: true, - capabilities: null, - })); - const binaryPathValue = providerConfig.binaryPath; - const isDirty = !Equal.equals(providerConfig, defaultProviderConfig); - - return { - provider: providerSettings.provider, - title: providerSettings.title, - binaryPlaceholder: providerSettings.binaryPlaceholder, - binaryDescription: providerSettings.binaryDescription, - homePathKey: providerSettings.homePathKey, - homePlaceholder: providerSettings.homePlaceholder, - homeDescription: providerSettings.homeDescription, - binaryPathValue, - isDirty, - liveProvider, - models, - providerConfig, - statusKey, - statusStyle, - summary, - versionLabel: getProviderVersionLabel(liveProvider?.version), - }; - }); - - async function restoreDefaults() { - if (changedSettingLabels.length === 0) return; - - const api = readNativeApi(); - const confirmed = await (api ?? ensureNativeApi()).dialogs.confirm( - ["Restore default settings?", `This will reset: ${changedSettingLabels.join(", ")}.`].join( - "\n", - ), - ); - if (!confirmed) return; - - setTheme("system"); - resetSettings(); - setOpenProviderDetails({ - codex: false, - claudeAgent: false, - }); - setCustomModelInputByProvider({ - codex: "", - claudeAgent: "", - }); - setCustomModelErrorByProvider({}); - } - - return ( - -
- {!isElectron && ( -
-
- - Settings -
- -
-
-
- )} - - {isElectron && ( -
- - Settings - -
- -
-
- )} - -
-
- - setTheme("system")} /> - ) : null - } - control={ - - } - /> - - - updateSettings({ - timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat, - }) - } - /> - ) : null - } - control={ - - } - /> - - - updateSettings({ - diffWordWrap: DEFAULT_UNIFIED_SETTINGS.diffWordWrap, - }) - } - /> - ) : null - } - control={ - - updateSettings({ - diffWordWrap: Boolean(checked), - }) - } - aria-label="Wrap diff lines by default" - /> - } - /> - - - updateSettings({ - enableAssistantStreaming: - DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming, - }) - } - /> - ) : null - } - control={ - - updateSettings({ - enableAssistantStreaming: Boolean(checked), - }) - } - aria-label="Stream assistant messages" - /> - } - /> - - - updateSettings({ - defaultThreadEnvMode: DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode, - }) - } - /> - ) : null - } - control={ - - } - /> - - - updateSettings({ - confirmThreadDelete: DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete, - }) - } - /> - ) : null - } - control={ - - updateSettings({ - confirmThreadDelete: Boolean(checked), - }) - } - aria-label="Confirm thread deletion" - /> - } - /> - { - updateSettings({ - textGenerationModelSelection: - DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, - }); - }} - /> - ) : null - } - control={ -
- { - updateSettings({ - textGenerationModelSelection: resolveAppModelSelectionState( - { - ...settings, - textGenerationModelSelection: { provider, model }, - }, - serverProviders, - ), - }); - }} - /> - provider.provider === textGenProvider) - ?.models ?? [] - } - model={textGenModel} - prompt="" - onPromptChange={() => {}} - modelOptions={textGenModelOptions} - allowPromptInjectedEffort={false} - triggerVariant="outline" - triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground" - onModelOptionsChange={(nextOptions) => { - updateSettings({ - textGenerationModelSelection: resolveAppModelSelectionState( - { - ...settings, - textGenerationModelSelection: { - provider: textGenProvider, - model: textGenModel, - ...(nextOptions ? { options: nextOptions } : {}), - }, - }, - serverProviders, - ), - }); - }} - /> -
- } - /> -
- - - {serverProviders.length > 0 ? ( - - {(() => { - const rel = formatRelativeTime( - serverProviders.reduce( - (latest, provider) => - provider.checkedAt > latest ? provider.checkedAt : latest, - serverProviders[0]!.checkedAt, - ), - ); - return rel.suffix ? ( - <> - Checked {rel.value}{" "} - {rel.suffix} - - ) : ( - <>Checked {rel.value} - ); - })()} - - ) : null} - - void refreshProviders()} - aria-label="Refresh provider status" - > - {isRefreshingProviders ? ( - - ) : ( - - )} - - } - /> - Refresh provider status - -
- } - > - {providerCards.map((providerCard) => { - const customModelInput = customModelInputByProvider[providerCard.provider]; - const customModelError = customModelErrorByProvider[providerCard.provider] ?? null; - const providerDisplayName = - PROVIDER_DISPLAY_NAMES[providerCard.provider] ?? providerCard.title; - - return ( -
-
-
-
-
- -

- {providerDisplayName} -

- {providerCard.versionLabel ? ( - - {providerCard.versionLabel} - - ) : null} - - {providerCard.isDirty ? ( - { - updateSettings({ - providers: { - ...settings.providers, - [providerCard.provider]: - DEFAULT_UNIFIED_SETTINGS.providers[providerCard.provider], - }, - }); - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [providerCard.provider]: null, - })); - }} - /> - ) : null} - -
-

- {providerCard.summary.headline} - {providerCard.summary.detail - ? ` — ${providerCard.summary.detail}` - : null} -

-
-
- - { - const isDisabling = !checked; - // The resolved provider accounts for both explicit - // selection and the implicit default (codex). - const resolvedProvider = textGenProvider; - // When disabling the provider that's currently used for - // text generation, clear the selection so it falls back to - // the next available provider's default model. - const shouldClearModelSelection = - isDisabling && resolvedProvider === providerCard.provider; - updateSettings({ - providers: { - ...settings.providers, - [providerCard.provider]: { - ...settings.providers[providerCard.provider], - enabled: Boolean(checked), - }, - }, - ...(shouldClearModelSelection - ? { - textGenerationModelSelection: - DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection, - } - : {}), - }); - }} - aria-label={`Enable ${providerDisplayName}`} - /> -
-
-
- - - setOpenProviderDetails((existing) => ({ - ...existing, - [providerCard.provider]: open, - })) - } - > - -
- {/* Binary path */} -
- -
- - {/* Home path (Codex only) */} - {providerCard.homePathKey ? ( -
- -
- ) : null} - - {/* Models */} -
-
Models
-
- {providerCard.models.length} model - {providerCard.models.length === 1 ? "" : "s"} available. -
-
{ - modelListRefs.current[providerCard.provider] = el; - }} - className="mt-2 max-h-40 overflow-y-auto pb-1" - > - {providerCard.models.map((model) => { - const caps = model.capabilities; - const capLabels: string[] = []; - if (caps?.supportsFastMode) capLabels.push("Fast mode"); - if (caps?.supportsThinkingToggle) capLabels.push("Thinking"); - if ( - caps?.reasoningEffortLevels && - caps.reasoningEffortLevels.length > 0 - ) - capLabels.push("Reasoning"); - const hasDetails = - capLabels.length > 0 || model.name !== model.slug; - - return ( -
- - {model.name} - - {hasDetails ? ( - - - } - > - - - -
- - {model.slug} - - {capLabels.length > 0 ? ( -
- {capLabels.map((label) => ( - - {label} - - ))} -
- ) : null} -
-
-
- ) : null} - {model.isCustom ? ( -
- - custom - - -
- ) : null} -
- ); - })} -
-
- { - const value = event.target.value; - setCustomModelInputByProvider((existing) => ({ - ...existing, - [providerCard.provider]: value, - })); - if (customModelError) { - setCustomModelErrorByProvider((existing) => ({ - ...existing, - [providerCard.provider]: null, - })); - } - }} - onKeyDown={(event) => { - if (event.key !== "Enter") return; - event.preventDefault(); - addCustomModel(providerCard.provider); - }} - placeholder={ - providerCard.provider === "codex" - ? "gpt-6.7-codex-ultra-preview" - : "claude-sonnet-5-0" - } - spellCheck={false} - /> - -
- {customModelError ? ( -

{customModelError}

- ) : null} -
-
-
-
-
- ); - })} - - - - - - {keybindingsConfigPath ?? "Resolving keybindings path..."} - - {openKeybindingsError ? ( - {openKeybindingsError} - ) : ( - Opens in your preferred editor. - )} - - } - control={ - - } - /> - - {APP_VERSION} - } - /> - -
-
-
- - ); -} - -export const Route = createFileRoute("/_chat/settings")({ - component: SettingsRouteView, -}); diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 80525f556e..3c86ab42f3 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -1,9 +1,8 @@ import { type ResolvedKeybindingsConfig } from "@t3tools/contracts"; import { useQuery } from "@tanstack/react-query"; -import { Outlet, createFileRoute, useNavigate } from "@tanstack/react-router"; +import { Outlet, createFileRoute } from "@tanstack/react-router"; import { useEffect } from "react"; -import ThreadSidebar from "../components/Sidebar"; import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { isTerminalFocused } from "../lib/terminalFocus"; import { serverConfigQueryOptions } from "../lib/serverReactQuery"; @@ -12,12 +11,8 @@ import { selectThreadTerminalState, useTerminalStateStore } from "../terminalSta import { useThreadSelectionStore } from "../threadSelectionStore"; import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic"; import { useSettings } from "~/hooks/useSettings"; -import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar"; const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; -const THREAD_SIDEBAR_WIDTH_STORAGE_KEY = "chat_thread_sidebar_width"; -const THREAD_SIDEBAR_MIN_WIDTH = 13 * 16; -const THREAD_MAIN_CONTENT_MIN_WIDTH = 40 * 16; function ChatRouteGlobalShortcuts() { const clearSelection = useThreadSelectionStore((state) => state.clearSelection); @@ -94,43 +89,11 @@ function ChatRouteGlobalShortcuts() { } function ChatRouteLayout() { - const navigate = useNavigate(); - - useEffect(() => { - const onMenuAction = window.desktopBridge?.onMenuAction; - if (typeof onMenuAction !== "function") { - return; - } - - const unsubscribe = onMenuAction((action) => { - if (action !== "open-settings") return; - void navigate({ to: "/settings" }); - }); - - return () => { - unsubscribe?.(); - }; - }, [navigate]); - return ( - + <> - - wrapper.clientWidth - nextWidth >= THREAD_MAIN_CONTENT_MIN_WIDTH, - storageKey: THREAD_SIDEBAR_WIDTH_STORAGE_KEY, - }} - > - - - - + ); } diff --git a/apps/web/src/routes/settings.archived.tsx b/apps/web/src/routes/settings.archived.tsx new file mode 100644 index 0000000000..3ad690afc0 --- /dev/null +++ b/apps/web/src/routes/settings.archived.tsx @@ -0,0 +1,7 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { ArchivedThreadsPanel } from "../components/settings/SettingsPanels"; + +export const Route = createFileRoute("/settings/archived")({ + component: ArchivedThreadsPanel, +}); diff --git a/apps/web/src/routes/settings.general.tsx b/apps/web/src/routes/settings.general.tsx new file mode 100644 index 0000000000..7fb503e0a2 --- /dev/null +++ b/apps/web/src/routes/settings.general.tsx @@ -0,0 +1,7 @@ +import { createFileRoute } from "@tanstack/react-router"; + +import { GeneralSettingsPanel } from "../components/settings/SettingsPanels"; + +export const Route = createFileRoute("/settings/general")({ + component: GeneralSettingsPanel, +}); diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx new file mode 100644 index 0000000000..edee426732 --- /dev/null +++ b/apps/web/src/routes/settings.tsx @@ -0,0 +1,77 @@ +import { RotateCcwIcon } from "lucide-react"; +import { Outlet, createFileRoute, redirect } from "@tanstack/react-router"; +import { useState } from "react"; + +import { useSettingsRestore } from "../components/settings/SettingsPanels"; +import { Button } from "../components/ui/button"; +import { SidebarInset, SidebarTrigger } from "../components/ui/sidebar"; +import { isElectron } from "../env"; + +function SettingsContentLayout() { + const [restoreSignal, setRestoreSignal] = useState(0); + const { changedSettingLabels, restoreDefaults } = useSettingsRestore(() => + setRestoreSignal((value) => value + 1), + ); + + return ( + +
+ {!isElectron && ( +
+
+ + Settings +
+ +
+
+
+ )} + + {isElectron && ( +
+ + Settings + +
+ +
+
+ )} + +
+ +
+
+
+ ); +} + +function SettingsRouteLayout() { + return ; +} + +export const Route = createFileRoute("/settings")({ + beforeLoad: ({ location }) => { + if (location.pathname === "/settings") { + throw redirect({ to: "/settings/general", replace: true }); + } + }, + component: SettingsRouteLayout, +}); diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index 4da4f23c8c..db62bad523 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -29,6 +29,7 @@ function makeThread(overrides: Partial = {}): Thread { proposedPlans: [], error: null, createdAt: "2026-02-13T00:00:00.000Z", + archivedAt: null, latestTurn: null, branch: null, worktreePath: null, @@ -72,6 +73,7 @@ function makeReadModelThread(overrides: Partial { expect(next.threads[0]?.updatedAt).toBe("2026-02-27T00:05:00.000Z"); }); + it("maps archivedAt from the read model", () => { + const initialState = makeState(makeThread()); + const archivedAt = "2026-02-28T00:00:00.000Z"; + const next = syncServerReadModel( + initialState, + makeReadModel( + makeReadModelThread({ + archivedAt, + }), + ), + ); + + expect(next.threads[0]?.archivedAt).toBe(archivedAt); + }); + it("preserves the current project order when syncing incoming read model updates", () => { const project1 = ProjectId.makeUnsafe("project-1"); const project2 = ProjectId.makeUnsafe("project-2"); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 4590b2886d..a5beb5b1bf 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -299,6 +299,7 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea })), error: thread.session?.lastError ?? null, createdAt: thread.createdAt, + archivedAt: thread.archivedAt, updatedAt: thread.updatedAt, latestTurn: thread.latestTurn, lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt, diff --git a/apps/web/src/terminalStateStore.test.ts b/apps/web/src/terminalStateStore.test.ts index e7e240cf25..d618275682 100644 --- a/apps/web/src/terminalStateStore.test.ts +++ b/apps/web/src/terminalStateStore.test.ts @@ -7,9 +7,7 @@ const THREAD_ID = ThreadId.makeUnsafe("thread-1"); describe("terminalStateStore actions", () => { beforeEach(() => { - if (typeof localStorage !== "undefined") { - localStorage.clear(); - } + useTerminalStateStore.persist.clearStorage(); useTerminalStateStore.setState({ terminalStateByThreadId: {} }); }); diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.ts index b2cea6d560..4f51e2ed8d 100644 --- a/apps/web/src/terminalStateStore.ts +++ b/apps/web/src/terminalStateStore.ts @@ -8,6 +8,7 @@ import type { ThreadId } from "@t3tools/contracts"; import { create } from "zustand"; import { createJSONStorage, persist } from "zustand/middleware"; +import { resolveStorage } from "./lib/storage"; import { DEFAULT_THREAD_TERMINAL_HEIGHT, DEFAULT_THREAD_TERMINAL_ID, @@ -27,6 +28,10 @@ interface ThreadTerminalState { const TERMINAL_STATE_STORAGE_KEY = "t3code:terminal-state:v1"; +function createTerminalStateStorage() { + return resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined); +} + function normalizeTerminalIds(terminalIds: string[]): string[] { const ids = [...new Set(terminalIds.map((id) => id.trim()).filter((id) => id.length > 0))]; return ids.length > 0 ? ids : [DEFAULT_THREAD_TERMINAL_ID]; @@ -542,7 +547,7 @@ export const useTerminalStateStore = create()( { name: TERMINAL_STATE_STORAGE_KEY, version: 1, - storage: createJSONStorage(() => localStorage), + storage: createJSONStorage(createTerminalStateStorage), partialize: (state) => ({ terminalStateByThreadId: state.terminalStateByThreadId, }), diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts index a75ab21019..453c070166 100644 --- a/apps/web/src/timestampFormat.ts +++ b/apps/web/src/timestampFormat.ts @@ -66,3 +66,8 @@ export function formatRelativeTime(isoDate: string): { value: string; suffix: st const days = Math.floor(hours / 24); return { value: `${days}d`, suffix: "ago" }; } + +export function formatRelativeTimeLabel(isoDate: string) { + const relative = formatRelativeTime(isoDate); + return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value; +} diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index de06f95538..e6cb1efea6 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -101,6 +101,7 @@ export interface Thread { proposedPlans: ProposedPlan[]; error: string | null; createdAt: string; + archivedAt: string | null; updatedAt?: string | undefined; latestTurn: OrchestrationLatestTurn | null; lastVisitedAt?: string | undefined; diff --git a/apps/web/src/worktreeCleanup.test.ts b/apps/web/src/worktreeCleanup.test.ts index 574675ae11..723661ccbb 100644 --- a/apps/web/src/worktreeCleanup.test.ts +++ b/apps/web/src/worktreeCleanup.test.ts @@ -23,6 +23,7 @@ function makeThread(overrides: Partial = {}): Thread { proposedPlans: [], error: null, createdAt: "2026-02-13T00:00:00.000Z", + archivedAt: null, latestTurn: null, branch: null, worktreePath: null, diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 1d282ae721..0443128dd5 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -57,6 +57,7 @@ export interface ContextMenuItem { id: T; label: string; destructive?: boolean; + disabled?: boolean; } export type DesktopUpdateStatus = diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 19cef5a392..59c023e62a 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -5,6 +5,8 @@ import { Effect, Schema } from "effect"; import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, + OrchestrationCommand, + OrchestrationEvent, OrchestrationGetTurnDiffInput, OrchestrationLatestTurn, ProjectCreatedPayload, @@ -32,6 +34,8 @@ const decodeOrchestrationLatestTurn = Schema.decodeUnknownEffect(OrchestrationLa const decodeOrchestrationProposedPlan = Schema.decodeUnknownEffect(OrchestrationProposedPlan); const decodeOrchestrationSession = Schema.decodeUnknownEffect(OrchestrationSession); const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload); +const decodeOrchestrationCommand = Schema.decodeUnknownEffect(OrchestrationCommand); +const decodeOrchestrationEvent = Schema.decodeUnknownEffect(OrchestrationEvent); const decodeThreadMetaUpdatedPayload = Schema.decodeUnknownEffect(ThreadMetaUpdatedPayload); it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () => @@ -227,6 +231,66 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () => }), ); +it.effect("decodes thread archive and unarchive commands", () => + Effect.gen(function* () { + const archive = yield* decodeOrchestrationCommand({ + type: "thread.archive", + commandId: "cmd-archive-1", + threadId: "thread-1", + }); + const unarchive = yield* decodeOrchestrationCommand({ + type: "thread.unarchive", + commandId: "cmd-unarchive-1", + threadId: "thread-1", + }); + + assert.strictEqual(archive.type, "thread.archive"); + assert.strictEqual(unarchive.type, "thread.unarchive"); + }), +); + +it.effect("decodes thread archived and unarchived events", () => + Effect.gen(function* () { + const archived = yield* decodeOrchestrationEvent({ + sequence: 1, + eventId: "event-archive-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.archived", + occurredAt: "2026-01-01T00:00:00.000Z", + commandId: "cmd-archive-1", + causationEventId: null, + correlationId: "cmd-archive-1", + metadata: {}, + payload: { + threadId: "thread-1", + archivedAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }, + }); + const unarchived = yield* decodeOrchestrationEvent({ + sequence: 2, + eventId: "event-unarchive-1", + aggregateKind: "thread", + aggregateId: "thread-1", + type: "thread.unarchived", + occurredAt: "2026-01-02T00:00:00.000Z", + commandId: "cmd-unarchive-1", + causationEventId: null, + correlationId: "cmd-unarchive-1", + metadata: {}, + payload: { + threadId: "thread-1", + updatedAt: "2026-01-02T00:00:00.000Z", + }, + }); + + assert.strictEqual(archived.type, "thread.archived"); + assert.strictEqual(archived.payload.archivedAt, "2026-01-01T00:00:00.000Z"); + assert.strictEqual(unarchived.type, "thread.unarchived"); + }), +); + it.effect("accepts provider-scoped model options in thread.turn.start", () => Effect.gen(function* () { const parsed = yield* decodeThreadTurnStartCommand({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 0b40bb6fdf..31631666e2 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -283,6 +283,7 @@ export const OrchestrationThread = Schema.Struct({ latestTurn: Schema.NullOr(OrchestrationLatestTurn), createdAt: IsoDateTime, updatedAt: IsoDateTime, + archivedAt: Schema.NullOr(IsoDateTime).pipe(Schema.withDecodingDefault(() => null)), deletedAt: Schema.NullOr(IsoDateTime), messages: Schema.Array(OrchestrationMessage), proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(Schema.withDecodingDefault(() => [])), @@ -348,6 +349,18 @@ const ThreadDeleteCommand = Schema.Struct({ threadId: ThreadId, }); +const ThreadArchiveCommand = Schema.Struct({ + type: Schema.Literal("thread.archive"), + commandId: CommandId, + threadId: ThreadId, +}); + +const ThreadUnarchiveCommand = Schema.Struct({ + type: Schema.Literal("thread.unarchive"), + commandId: CommandId, + threadId: ThreadId, +}); + const ThreadMetaUpdateCommand = Schema.Struct({ type: Schema.Literal("thread.meta.update"), commandId: CommandId, @@ -457,6 +470,8 @@ const DispatchableClientOrchestrationCommand = Schema.Union([ ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, + ThreadArchiveCommand, + ThreadUnarchiveCommand, ThreadMetaUpdateCommand, ThreadRuntimeModeSetCommand, ThreadInteractionModeSetCommand, @@ -476,6 +491,8 @@ export const ClientOrchestrationCommand = Schema.Union([ ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, + ThreadArchiveCommand, + ThreadUnarchiveCommand, ThreadMetaUpdateCommand, ThreadRuntimeModeSetCommand, ThreadInteractionModeSetCommand, @@ -576,6 +593,8 @@ export const OrchestrationEventType = Schema.Literals([ "project.deleted", "thread.created", "thread.deleted", + "thread.archived", + "thread.unarchived", "thread.meta-updated", "thread.runtime-mode-set", "thread.interaction-mode-set", @@ -642,6 +661,17 @@ export const ThreadDeletedPayload = Schema.Struct({ deletedAt: IsoDateTime, }); +export const ThreadArchivedPayload = Schema.Struct({ + threadId: ThreadId, + archivedAt: IsoDateTime, + updatedAt: IsoDateTime, +}); + +export const ThreadUnarchivedPayload = Schema.Struct({ + threadId: ThreadId, + updatedAt: IsoDateTime, +}); + export const ThreadMetaUpdatedPayload = Schema.Struct({ threadId: ThreadId, title: Schema.optional(TrimmedNonEmptyString), @@ -799,6 +829,16 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.deleted"), payload: ThreadDeletedPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.archived"), + payload: ThreadArchivedPayload, + }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.unarchived"), + payload: ThreadUnarchivedPayload, + }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.meta-updated"), diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts new file mode 100644 index 0000000000..e7f638c7f3 --- /dev/null +++ b/packages/contracts/src/settings.test.ts @@ -0,0 +1,8 @@ +import { describe, expect, it } from "vitest"; +import { DEFAULT_CLIENT_SETTINGS } from "./settings"; + +describe("DEFAULT_CLIENT_SETTINGS", () => { + it("includes archive confirmation with a false default", () => { + expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false); + }); +}); diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 8ce01f630c..9cd8a5f251 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -24,6 +24,7 @@ export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type; export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at"; export const ClientSettingsSchema = Schema.Struct({ + confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)), confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)), diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)), sidebarProjectSortOrder: SidebarProjectSortOrder.pipe( From 3e2df5a7823d180f634370998d58497993b94ee7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 10:51:01 -0700 Subject: [PATCH 15/66] Normalize typed provider runtime ingestion (#1475) --- .../Layers/ProviderRuntimeIngestion.test.ts | 68 ++++++++++++++++++- .../Layers/ProviderRuntimeIngestion.ts | 46 +++---------- 2 files changed, 73 insertions(+), 41 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 8d205bbe2f..3eaeb2cd1d 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -4,7 +4,6 @@ import path from "node:path"; import type { OrchestrationReadModel, - ProviderKind, ProviderRuntimeEvent, ProviderSession, } from "@t3tools/contracts"; @@ -56,7 +55,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); type LegacyProviderRuntimeEvent = { readonly type: string; readonly eventId: EventId; - readonly provider: ProviderKind; + readonly provider: ProviderRuntimeEvent["provider"]; readonly createdAt: string; readonly threadId: ThreadId; readonly turnId?: string | undefined; @@ -66,6 +65,23 @@ type LegacyProviderRuntimeEvent = { readonly [key: string]: unknown; }; +type LegacyTurnCompletedEvent = LegacyProviderRuntimeEvent & { + readonly type: "turn.completed"; + readonly payload?: undefined; + readonly status: "completed" | "failed" | "interrupted" | "cancelled"; + readonly errorMessage?: string | undefined; +}; + +function isLegacyTurnCompletedEvent( + event: LegacyProviderRuntimeEvent, +): event is LegacyTurnCompletedEvent { + return ( + event.type === "turn.completed" && + event.payload === undefined && + typeof event.status === "string" + ); +} + function createProviderServiceHarness() { const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const runtimeSessions: ProviderSession[] = []; @@ -93,8 +109,23 @@ function createProviderServiceHarness() { runtimeSessions.push(session); }; + const normalizeLegacyEvent = (event: LegacyProviderRuntimeEvent): ProviderRuntimeEvent => { + if (isLegacyTurnCompletedEvent(event)) { + const normalized: Extract = { + ...(event as Omit, "payload">), + payload: { + state: event.status, + ...(typeof event.errorMessage === "string" ? { errorMessage: event.errorMessage } : {}), + }, + }; + return normalized; + } + + return event as ProviderRuntimeEvent; + }; + const emit = (event: LegacyProviderRuntimeEvent): void => { - Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent)); + Effect.runSync(PubSub.publish(runtimeEventPubSub, normalizeLegacyEvent(event))); }; return { @@ -1695,6 +1726,37 @@ describe("ProviderRuntimeIngestion", () => { expect(thread.session?.lastError).toBe("runtime exploded"); }); + it("records runtime.error activities from the typed payload message", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + harness.emit({ + type: "runtime.error", + eventId: asEventId("evt-runtime-error-activity"), + provider: "codex", + createdAt: now, + threadId: asThreadId("thread-1"), + turnId: asTurnId("turn-runtime-error-activity"), + payload: { + message: "runtime activity exploded", + }, + }); + + const thread = await waitForThread(harness.engine, (entry) => + entry.activities.some((activity) => activity.id === "evt-runtime-error-activity"), + ); + const activity = thread.activities.find( + (entry: ProviderRuntimeTestActivity) => entry.id === "evt-runtime-error-activity", + ); + const activityPayload = + activity?.payload && typeof activity.payload === "object" + ? (activity.payload as Record) + : undefined; + + expect(activity?.kind).toBe("runtime.error"); + expect(activityPayload?.message).toBe("runtime activity exploded"); + }); + it("keeps the session running when a runtime.warning arrives during an active turn", async () => { const harness = await createHarness(); const now = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index f9a662b84f..b42e5f1566 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -98,10 +98,6 @@ function proposedPlanIdFromEvent(event: ProviderRuntimeEvent, threadId: ThreadId return `plan:${threadId}:event:${event.eventId}`; } -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - function buildContextWindowActivityPayload( event: ProviderRuntimeEvent, ): ThreadTokenUsageSnapshot | undefined { @@ -111,14 +107,6 @@ function buildContextWindowActivityPayload( return event.payload.usage; } -function runtimePayloadRecord(event: ProviderRuntimeEvent): Record | undefined { - const payload = (event as { payload?: unknown }).payload; - if (!payload || typeof payload !== "object") { - return undefined; - } - return payload as Record; -} - function normalizeRuntimeTurnState( value: string | undefined, ): "completed" | "failed" | "interrupted" | "cancelled" { @@ -133,23 +121,6 @@ function normalizeRuntimeTurnState( } } -function runtimeTurnState( - event: ProviderRuntimeEvent, -): "completed" | "failed" | "interrupted" | "cancelled" { - const payloadState = asString(runtimePayloadRecord(event)?.state); - return normalizeRuntimeTurnState(payloadState); -} - -function runtimeTurnErrorMessage(event: ProviderRuntimeEvent): string | undefined { - const payloadErrorMessage = asString(runtimePayloadRecord(event)?.errorMessage); - return payloadErrorMessage; -} - -function runtimeErrorMessageFromEvent(event: ProviderRuntimeEvent): string | undefined { - const payloadMessage = asString(runtimePayloadRecord(event)?.message); - return payloadMessage; -} - function orchestrationSessionStatusFromRuntimeState( state: "starting" | "running" | "waiting" | "ready" | "interrupted" | "stopped" | "error", ): "starting" | "running" | "ready" | "interrupted" | "stopped" | "error" { @@ -253,10 +224,6 @@ function runtimeEventToActivities( } case "runtime.error": { - const message = runtimeErrorMessageFromEvent(event); - if (!message) { - return []; - } return [ { id: event.eventId, @@ -265,7 +232,7 @@ function runtimeEventToActivities( kind: "runtime.error", summary: "Runtime error", payload: { - message: truncateDetail(message), + message: truncateDetail(event.payload.message), }, turnId: toTurnId(event.turnId) ?? null, ...maybeSequence, @@ -973,7 +940,9 @@ const make = Effect.gen(function* () { case "session.exited": return "stopped"; case "turn.completed": - return runtimeTurnState(event) === "failed" ? "error" : "ready"; + return normalizeRuntimeTurnState(event.payload.state) === "failed" + ? "error" + : "ready"; case "session.started": case "thread.started": // Provider thread/session start notifications can arrive during an @@ -984,8 +953,9 @@ const make = Effect.gen(function* () { const lastError = event.type === "session.state.changed" && event.payload.state === "error" ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") - : event.type === "turn.completed" && runtimeTurnState(event) === "failed" - ? (runtimeTurnErrorMessage(event) ?? thread.session?.lastError ?? "Turn failed") + : event.type === "turn.completed" && + normalizeRuntimeTurnState(event.payload.state) === "failed" + ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") : status === "ready" ? null : (thread.session?.lastError ?? null); @@ -1176,7 +1146,7 @@ const make = Effect.gen(function* () { } if (event.type === "runtime.error") { - const runtimeErrorMessage = runtimeErrorMessageFromEvent(event) ?? "Provider runtime error"; + const runtimeErrorMessage = event.payload.message; const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD ? true From 5851b8aca4a13e1a5c6db644a93c20b779e0e04d Mon Sep 17 00:00:00 2001 From: smalitobules Date: Sat, 28 Mar 2026 19:53:29 +0200 Subject: [PATCH 16/66] fix: trust node-pty install scripts on linux (#1451) Co-authored-by: smalitobules <207318034+smalitobules@users.noreply.github.com> --- bun.lock | 3 +++ package.json | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/bun.lock b/bun.lock index 4c640ba3c8..fa083cdc53 100644 --- a/bun.lock +++ b/bun.lock @@ -169,6 +169,9 @@ }, }, }, + "trustedDependencies": [ + "node-pty", + ], "overrides": { "vite": "^8.0.0", }, diff --git a/package.json b/package.json index a906779961..33e65e90e9 100644 --- a/package.json +++ b/package.json @@ -69,5 +69,8 @@ "workerDirectory": [ "apps/web/public" ] - } + }, + "trustedDependencies": [ + "node-pty" + ] } From 32c1f98a02d5cf8e42d70dbd65822f9b08151024 Mon Sep 17 00:00:00 2001 From: Ryan Gast <148826144+Ryan-D-Gast@users.noreply.github.com> Date: Sat, 28 Mar 2026 13:21:56 -0500 Subject: [PATCH 17/66] Fix Linux desktop Codex CLI detection at startup (#1100) Co-authored-by: Julius Marminge --- apps/desktop/src/syncShellEnvironment.test.ts | 28 +++++++++++-- apps/desktop/src/syncShellEnvironment.ts | 13 +++++-- apps/server/src/main.test.ts | 19 ++++++++- apps/server/src/os-jank.test.ts | 39 +++++++++++++++++++ apps/server/src/os-jank.ts | 22 ++++++++--- packages/shared/src/shell.ts | 20 ++++++++++ 6 files changed, 127 insertions(+), 14 deletions(-) create mode 100644 apps/server/src/os-jank.test.ts diff --git a/apps/desktop/src/syncShellEnvironment.test.ts b/apps/desktop/src/syncShellEnvironment.test.ts index 69e73da0aa..cda78a20b2 100644 --- a/apps/desktop/src/syncShellEnvironment.test.ts +++ b/apps/desktop/src/syncShellEnvironment.test.ts @@ -62,14 +62,13 @@ describe("syncShellEnvironment", () => { expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); }); - it("does nothing outside macOS", () => { + it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => { const env: NodeJS.ProcessEnv = { SHELL: "/bin/zsh", PATH: "/usr/bin", - SSH_AUTH_SOCK: "/tmp/inherited.sock", }; const readEnvironment = vi.fn(() => ({ - PATH: "/opt/homebrew/bin:/usr/bin", + PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin", SSH_AUTH_SOCK: "/tmp/secretive.sock", })); @@ -78,8 +77,29 @@ describe("syncShellEnvironment", () => { readEnvironment, }); + expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]); + expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin"); + expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock"); + }); + + it("does nothing outside macOS and linux", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + SSH_AUTH_SOCK: "/tmp/inherited.sock", + }; + const readEnvironment = vi.fn(() => ({ + PATH: "/usr/local/bin:/usr/bin", + SSH_AUTH_SOCK: "/tmp/secretive.sock", + })); + + syncShellEnvironment(env, { + platform: "win32", + readEnvironment, + }); + expect(readEnvironment).not.toHaveBeenCalled(); - expect(env.PATH).toBe("/usr/bin"); + expect(env.PATH).toBe("C:\\Windows\\System32"); expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock"); }); }); diff --git a/apps/desktop/src/syncShellEnvironment.ts b/apps/desktop/src/syncShellEnvironment.ts index 2181bea0ca..13036149b8 100644 --- a/apps/desktop/src/syncShellEnvironment.ts +++ b/apps/desktop/src/syncShellEnvironment.ts @@ -1,4 +1,8 @@ -import { readEnvironmentFromLoginShell, ShellEnvironmentReader } from "@t3tools/shared/shell"; +import { + readEnvironmentFromLoginShell, + resolveLoginShell, + ShellEnvironmentReader, +} from "@t3tools/shared/shell"; export function syncShellEnvironment( env: NodeJS.ProcessEnv = process.env, @@ -7,10 +11,13 @@ export function syncShellEnvironment( readEnvironment?: ShellEnvironmentReader; } = {}, ): void { - if ((options.platform ?? process.platform) !== "darwin") return; + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; try { - const shell = env.SHELL ?? "/bin/zsh"; + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [ "PATH", "SSH_AUTH_SOCK", diff --git a/apps/server/src/main.test.ts b/apps/server/src/main.test.ts index 0279e78f7c..0d990a81c8 100644 --- a/apps/server/src/main.test.ts +++ b/apps/server/src/main.test.ts @@ -21,6 +21,7 @@ import { ServerSettingsService } from "./serverSettings"; const start = vi.fn(() => undefined); const stop = vi.fn(() => undefined); +const fixPath = vi.fn(() => undefined); let resolvedConfig: ServerConfigShape | null = null; const serverStart = Effect.acquireRelease( Effect.gen(function* () { @@ -36,7 +37,7 @@ const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred) const testLayer = Layer.mergeAll( Layer.succeed(CliConfig, { cwd: "/tmp/t3-test-workspace", - fixPath: Effect.void, + fixPath: Effect.sync(fixPath), resolveStaticDir: Effect.undefined, } satisfies CliConfigShape), Layer.succeed(NetService, { @@ -81,6 +82,7 @@ beforeEach(() => { resolvedConfig = null; start.mockImplementation(() => undefined); stop.mockImplementation(() => undefined); + fixPath.mockImplementation(() => undefined); findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred)); }); @@ -329,6 +331,21 @@ it.layer(testLayer)("server CLI command", (it) => { }), ); + it.effect("hydrates PATH before server startup", () => + Effect.gen(function* () { + yield* runCli([]); + + assert.equal(fixPath.mock.calls.length, 1); + assert.equal(start.mock.calls.length, 1); + const fixPathOrder = fixPath.mock.invocationCallOrder[0]; + const startOrder = start.mock.invocationCallOrder[0]; + if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") { + assert.fail("Expected fixPath and start to be called"); + } + assert.isTrue(fixPathOrder < startOrder); + }), + ); + it.effect("records a startup heartbeat with thread/project counts", () => Effect.gen(function* () { const recordTelemetry = vi.fn( diff --git a/apps/server/src/os-jank.test.ts b/apps/server/src/os-jank.test.ts new file mode 100644 index 0000000000..ca03ab5868 --- /dev/null +++ b/apps/server/src/os-jank.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from "vitest"; + +import { fixPath } from "./os-jank"; + +describe("fixPath", () => { + it("hydrates PATH on linux using the resolved login shell", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "/bin/zsh", + PATH: "/usr/bin", + }; + const readPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin"); + + fixPath({ + env, + platform: "linux", + readPath, + }); + + expect(readPath).toHaveBeenCalledWith("/bin/zsh"); + expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin"); + }); + + it("does nothing outside macOS and linux even when SHELL is set", () => { + const env: NodeJS.ProcessEnv = { + SHELL: "C:/Program Files/Git/bin/bash.exe", + PATH: "C:\\Windows\\System32", + }; + const readPath = vi.fn(() => "/usr/local/bin:/usr/bin"); + + fixPath({ + env, + platform: "win32", + readPath, + }); + + expect(readPath).not.toHaveBeenCalled(); + expect(env.PATH).toBe("C:\\Windows\\System32"); + }); +}); diff --git a/apps/server/src/os-jank.ts b/apps/server/src/os-jank.ts index 0721d0d9f8..c3629e8fde 100644 --- a/apps/server/src/os-jank.ts +++ b/apps/server/src/os-jank.ts @@ -1,15 +1,25 @@ import * as OS from "node:os"; import { Effect, Path } from "effect"; -import { readPathFromLoginShell } from "@t3tools/shared/shell"; +import { readPathFromLoginShell, resolveLoginShell } from "@t3tools/shared/shell"; -export function fixPath(): void { - if (process.platform !== "darwin") return; +export function fixPath( + options: { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; + readPath?: typeof readPathFromLoginShell; + } = {}, +): void { + const platform = options.platform ?? process.platform; + if (platform !== "darwin" && platform !== "linux") return; + + const env = options.env ?? process.env; try { - const shell = process.env.SHELL ?? "/bin/zsh"; - const result = readPathFromLoginShell(shell); + const shell = resolveLoginShell(platform, env.SHELL); + if (!shell) return; + const result = (options.readPath ?? readPathFromLoginShell)(shell); if (result) { - process.env.PATH = result; + env.PATH = result; } } catch { // Silently ignore — keep default PATH diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index f1d60bf334..d9e8a7881b 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -10,6 +10,26 @@ type ExecFileSyncLike = ( options: { encoding: "utf8"; timeout: number }, ) => string; +export function resolveLoginShell( + platform: NodeJS.Platform, + shell: string | undefined, +): string | undefined { + const trimmedShell = shell?.trim(); + if (trimmedShell) { + return trimmedShell; + } + + if (platform === "darwin") { + return "/bin/zsh"; + } + + if (platform === "linux") { + return "/bin/bash"; + } + + return undefined; +} + export function extractPathFromShellOutput(output: string): string | null { const startIndex = output.indexOf(PATH_CAPTURE_START); if (startIndex === -1) return null; From 61f983098be44316944e77e3bc81538a6a8fb0e9 Mon Sep 17 00:00:00 2001 From: Ibrahim Elkamali <126423069+Marve10s@users.noreply.github.com> Date: Sat, 28 Mar 2026 20:38:29 +0200 Subject: [PATCH 18/66] fix(web): allow switching away from Ultrathink without manual prompt editing (#1307) --- .../CompactComposerControlsMenu.browser.tsx | 25 ++++++++++++++++--- .../components/chat/TraitsPicker.browser.tsx | 22 +++++++++++++--- apps/web/src/components/chat/TraitsPicker.tsx | 24 ++++++++++++++---- 3 files changed, 60 insertions(+), 11 deletions(-) diff --git a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx index aa3550e007..eee6f885e9 100644 --- a/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx +++ b/apps/web/src/components/chat/CompactComposerControlsMenu.browser.tsx @@ -220,7 +220,7 @@ describe("CompactComposerControlsMenu", () => { }); }); - it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => { + it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { await using _ = await mountMenu({ modelSelection: { provider: "claudeAgent", @@ -235,8 +235,27 @@ describe("CompactComposerControlsMenu", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain("Effort"); - expect(text).toContain("Remove Ultrathink from the prompt to change effort."); - expect(text).not.toContain("Fallback Effort"); + expect(text).not.toContain("ultrathink"); + }); + }); + + it("warns when ultrathink appears in prompt body text", async () => { + await using _ = await mountMenu({ + modelSelection: { + provider: "claudeAgent", + model: "claude-opus-4-6", + options: { effort: "high" }, + }, + prompt: "Ultrathink:\nplease ultrathink about this problem", + }); + + await page.getByLabelText("More composer controls").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain( + 'Your prompt contains "ultrathink" in the text. Remove it to change effort.', + ); }); }); }); diff --git a/apps/web/src/components/chat/TraitsPicker.browser.tsx b/apps/web/src/components/chat/TraitsPicker.browser.tsx index 99d09fd634..9dea3651ea 100644 --- a/apps/web/src/components/chat/TraitsPicker.browser.tsx +++ b/apps/web/src/components/chat/TraitsPicker.browser.tsx @@ -296,7 +296,7 @@ describe("TraitsPicker (Claude)", () => { }); }); - it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => { + it("shows prompt-controlled Ultrathink state with selectable effort controls", async () => { await using _ = await mountClaudePicker({ model: "claude-opus-4-6", options: { effort: "high" }, @@ -312,8 +312,24 @@ describe("TraitsPicker (Claude)", () => { await vi.waitFor(() => { const text = document.body.textContent ?? ""; expect(text).toContain("Effort"); - expect(text).toContain("Remove Ultrathink from the prompt to change effort."); - expect(text).not.toContain("Fallback Effort"); + expect(text).not.toContain("ultrathink"); + }); + }); + + it("warns when ultrathink appears in prompt body text", async () => { + await using _ = await mountClaudePicker({ + model: "claude-opus-4-6", + options: { effort: "high" }, + prompt: "Ultrathink:\nplease ultrathink about this problem", + }); + + await page.getByRole("button").click(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain( + 'Your prompt contains "ultrathink" in the text. Remove it to change effort.', + ); }); }); diff --git a/apps/web/src/components/chat/TraitsPicker.tsx b/apps/web/src/components/chat/TraitsPicker.tsx index a3b6cbb48f..061594ad53 100644 --- a/apps/web/src/components/chat/TraitsPicker.tsx +++ b/apps/web/src/components/chat/TraitsPicker.tsx @@ -120,6 +120,10 @@ function getSelectedTraits( caps.promptInjectedEffortLevels.length > 0 && isClaudeUltrathinkPrompt(prompt); + // Check if "ultrathink" appears in the body text (not just our prefix) + const ultrathinkInBodyText = + ultrathinkPromptControlled && isClaudeUltrathinkPrompt(prompt.replace(/^Ultrathink:\s*/i, "")); + return { caps, effort, @@ -130,6 +134,7 @@ function getSelectedTraits( contextWindow, defaultContextWindow, ultrathinkPromptControlled, + ultrathinkInBodyText, }; } @@ -176,12 +181,12 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ contextWindow, defaultContextWindow, ultrathinkPromptControlled, + ultrathinkInBodyText, } = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort); const defaultEffort = getDefaultEffort(caps); const handleEffortChange = useCallback( (value: string) => { - if (ultrathinkPromptControlled) return; if (!value) return; const nextOption = effortLevels.find((option) => option.value === value); if (!nextOption) return; @@ -193,6 +198,11 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ onPromptChange(nextPrompt); return; } + if (ultrathinkInBodyText) return; + if (ultrathinkPromptControlled) { + const stripped = prompt.replace(/^Ultrathink:\s*/i, ""); + onPromptChange(stripped); + } const effortKey = provider === "codex" ? "reasoningEffort" : "effort"; updateModelOptions( buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }), @@ -200,6 +210,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ }, [ ultrathinkPromptControlled, + ultrathinkInBodyText, modelOptions, onPromptChange, updateModelOptions, @@ -220,17 +231,20 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({ <>
Effort
- {ultrathinkPromptControlled ? ( + {ultrathinkInBodyText ? (
- Remove Ultrathink from the prompt to change effort. + Your prompt contains "ultrathink" in the text. Remove it to change effort.
) : null} - + {effortLevels.map((option) => ( {option.label} {option.value === defaultEffort ? " (default)" : ""} From 04298962be548a2d80433d0cc2c777a8b9de12a2 Mon Sep 17 00:00:00 2001 From: Rishi Raj Singh Chauhan <29247443+rishi-chauhan@users.noreply.github.com> Date: Sun, 29 Mar 2026 00:11:26 +0530 Subject: [PATCH 19/66] Fix server fallback to direct fd read on /proc/self/fd failure (#1488) Co-authored-by: Julius Marminge --- apps/server/src/bootstrap.test.ts | 53 ++++++++++++++++++++++++++++++ apps/server/src/bootstrap.ts | 54 +++++++++++++++++++++++-------- 2 files changed, 94 insertions(+), 13 deletions(-) diff --git a/apps/server/src/bootstrap.test.ts b/apps/server/src/bootstrap.test.ts index 804f2440a9..3fce6af9c4 100644 --- a/apps/server/src/bootstrap.test.ts +++ b/apps/server/src/bootstrap.test.ts @@ -8,10 +8,33 @@ import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import { TestClock } from "effect/testing"; +import { vi } from "vitest"; import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap"; import { assertNone, assertSome } from "@effect/vitest/utils"; +const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null })); + +vi.mock("node:fs", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + openSync: (...args: Parameters) => { + const [filePath, flags] = args; + if ( + typeof filePath === "string" && + filePath === openSyncInterceptor.failPath && + flags === "r" + ) { + const error = new Error("no such device or address"); + Object.assign(error, { code: "ENXIO" }); + throw error; + } + return (actual.openSync as (...a: typeof args) => number)(...args); + }, + }; +}); + const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String }); it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => { @@ -47,6 +70,36 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => { }), ); + it.effect("falls back to reading the inherited fd when path duplication fails", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" }); + + yield* fs.writeFileString( + filePath, + `${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({ + mode: "desktop", + })}\n`, + ); + + // Open without acquireRelease: the direct-stream fallback uses autoClose: true, + // so the stream owns the fd lifecycle and closes it asynchronously on end. + // Attempting to also close it synchronously in a finalizer races with the + // stream's async close and produces an uncaught EBADF. + const fd = NFS.openSync(filePath, "r"); + + openSyncInterceptor.failPath = `/proc/self/fd/${fd}`; + try { + const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 }); + assertSome(payload, { + mode: "desktop", + }); + } finally { + openSyncInterceptor.failPath = null; + } + }), + ); + it.effect("returns none when the fd is unavailable", () => Effect.gen(function* () { const fd = NFS.openSync("/dev/null", "r"); diff --git a/apps/server/src/bootstrap.ts b/apps/server/src/bootstrap.ts index b837ac6c18..0fb1352268 100644 --- a/apps/server/src/bootstrap.ts +++ b/apps/server/src/bootstrap.ts @@ -108,21 +108,26 @@ const makeBootstrapInputStream = (fd: number) => try: () => { const fdPath = resolveFdPath(fd); if (fdPath === undefined) { - const stream = new Net.Socket({ - fd, - readable: true, - writable: false, - }); - stream.setEncoding("utf8"); - return stream; + return makeDirectBootstrapStream(fd); } - const streamFd = NFS.openSync(fdPath, "r"); - return NFS.createReadStream("", { - fd: streamFd, - encoding: "utf8", - autoClose: true, - }); + let streamFd: number | undefined; + try { + streamFd = NFS.openSync(fdPath, "r"); + return NFS.createReadStream("", { + fd: streamFd, + encoding: "utf8", + autoClose: true, + }); + } catch (error) { + if (isBootstrapFdPathDuplicationError(error)) { + if (streamFd !== undefined) { + NFS.closeSync(streamFd); + } + return makeDirectBootstrapStream(fd); + } + throw error; + } }, catch: (error) => new BootstrapError({ @@ -131,6 +136,29 @@ const makeBootstrapInputStream = (fd: number) => }), }); +const makeDirectBootstrapStream = (fd: number): Readable => { + try { + return NFS.createReadStream("", { + fd, + encoding: "utf8", + autoClose: true, + }); + } catch { + const stream = new Net.Socket({ + fd, + readable: true, + writable: false, + }); + stream.setEncoding("utf8"); + return stream; + } +}; + +const isBootstrapFdPathDuplicationError = Predicate.compose( + Predicate.hasProperty("code"), + (_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM", +); + export function resolveFdPath( fd: number, platform: NodeJS.Platform = process.platform, From 52fa6a733342a2e5c5d421e90c8f31755fb76395 Mon Sep 17 00:00:00 2001 From: Daniels <73656233+danielss-dev@users.noreply.github.com> Date: Sat, 28 Mar 2026 19:51:44 +0100 Subject: [PATCH 20/66] fix(desktop): ensure all windows are destroyed before launching the NSIS installer during update process (#1461) Co-authored-by: Daniel Schwarz --- apps/desktop/src/main.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index c718a31272..9e2950462e 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -810,7 +810,11 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed clearUpdatePollTimer(); try { await stopBackendAndWaitForExit(); - autoUpdater.quitAndInstall(); + // Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close. + for (const win of BrowserWindow.getAllWindows()) { + win.destroy(); + } + autoUpdater.quitAndInstall(true, true); return { accepted: true, completed: true }; } catch (error: unknown) { const message = formatErrorMessage(error); @@ -1390,7 +1394,7 @@ app }); app.on("window-all-closed", () => { - if (process.platform !== "darwin") { + if (process.platform !== "darwin" && !isQuitting) { app.quit(); } }); From ce463a5360ab4a2426d9744d830266d3ef7f4410 Mon Sep 17 00:00:00 2001 From: Fllip <39161142+FllipEis@users.noreply.github.com> Date: Sat, 28 Mar 2026 19:56:46 +0100 Subject: [PATCH 21/66] fix(web): add project path action to sidebar menu (#1436) Co-authored-by: Julius Marminge --- apps/web/src/components/Sidebar.tsx | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index af60ce7d29..2d974be3ee 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -818,15 +818,22 @@ export default function Sidebar() { async (projectId: ProjectId, position: { x: number; y: number }) => { const api = readNativeApi(); if (!api) return; - const clicked = await api.contextMenu.show( - [{ id: "delete", label: "Remove project", destructive: true }], - position, - ); - if (clicked !== "delete") return; - const project = projects.find((entry) => entry.id === projectId); if (!project) return; + const clicked = await api.contextMenu.show( + [ + { id: "copy-path", label: "Copy Project Path" }, + { id: "delete", label: "Remove project", destructive: true }, + ], + position, + ); + if (clicked === "copy-path") { + copyPathToClipboard(project.cwd, { path: project.cwd }); + return; + } + if (clicked !== "delete") return; + const projectThreads = threads.filter((thread) => thread.projectId === projectId); if (projectThreads.length > 0) { toastManager.add({ @@ -864,6 +871,7 @@ export default function Sidebar() { [ clearComposerDraftForThread, clearProjectDraftThreadId, + copyPathToClipboard, getDraftThreadByProjectId, projects, threads, From 73b2f255a9c81f1efaa4133bee581d071abe6841 Mon Sep 17 00:00:00 2001 From: Danila Yudin Date: Sat, 28 Mar 2026 21:59:56 +0300 Subject: [PATCH 22/66] fix: add noopener to external chat markdown links (#1315) Co-authored-by: Julius Marminge --- apps/web/src/components/ChatMarkdown.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index 9663d158eb..b364a8e3a1 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -243,7 +243,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) { a({ node: _node, href, ...props }) { const targetPath = resolveMarkdownFileLinkTarget(href, cwd); if (!targetPath) { - return
; + return ; } return ( From c426452239e06417ec8e231b7883f9c2292df63c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 15:01:37 -0700 Subject: [PATCH 23/66] Tighten settings nav and add Escape back navigation (#1503) --- .../components/settings/SettingsSidebarNav.tsx | 6 +++--- apps/web/src/routes/settings.tsx | 17 ++++++++++++++++- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index ffca1e2092..20914b499d 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -41,8 +41,8 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { isActive={isActive} className={ isActive - ? "gap-2 px-2 py-2 text-left text-sm text-foreground" - : "gap-2 px-2 py-2 text-left text-sm text-muted-foreground hover:text-foreground/80" + ? "gap-2 px-2 py-2 text-left text-xs text-foreground" + : "gap-2 px-2 py-2 text-left text-xs text-muted-foreground hover:text-foreground/80" } onClick={() => void navigate({ to: item.to, replace: true })} > @@ -68,7 +68,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) { window.history.back()} > diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsx index edee426732..45096fd6d6 100644 --- a/apps/web/src/routes/settings.tsx +++ b/apps/web/src/routes/settings.tsx @@ -1,6 +1,6 @@ import { RotateCcwIcon } from "lucide-react"; import { Outlet, createFileRoute, redirect } from "@tanstack/react-router"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { useSettingsRestore } from "../components/settings/SettingsPanels"; import { Button } from "../components/ui/button"; @@ -13,6 +13,21 @@ function SettingsContentLayout() { setRestoreSignal((value) => value + 1), ); + useEffect(() => { + const onKeyDown = (event: KeyboardEvent) => { + if (event.defaultPrevented) return; + if (event.key === "Escape") { + event.preventDefault(); + window.history.back(); + } + }; + + window.addEventListener("keydown", onKeyDown); + return () => { + window.removeEventListener("keydown", onKeyDown); + }; + }, []); + return (
From f4617e7b19830111d88b1d914b3ca4e1396912a3 Mon Sep 17 00:00:00 2001 From: Noah Gregory Date: Sat, 28 Mar 2026 18:44:13 -0400 Subject: [PATCH 24/66] feat: add mock update server (#1180) Co-authored-by: Julius Marminge --- .gitignore | 1 + apps/desktop/src/main.ts | 24 +++++++++- .../components/desktopUpdate.logic.test.ts | 13 ++++-- .../web/src/components/desktopUpdate.logic.ts | 2 +- package.json | 1 + scripts/build-desktop-artifact.ts | 42 +++++++++++++++++- scripts/mock-update-server.ts | 44 +++++++++++++++++++ 7 files changed, 121 insertions(+), 6 deletions(-) create mode 100644 scripts/mock-update-server.ts diff --git a/.gitignore b/.gitignore index 471855de15..6e5f8cc59c 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ packages/*/dist build/ .logs/ release/ +release-mock/ .t3 .idea/ apps/web/.playwright diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 9e2950462e..81a02d446c 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -287,10 +287,12 @@ let updatePollTimer: ReturnType | null = null; let updateStartupTimer: ReturnType | null = null; let updateCheckInFlight = false; let updateDownloadInFlight = false; +let updateInstallInFlight = false; let updaterConfigured = false; let updateState: DesktopUpdateState = initialUpdateState(); function resolveUpdaterErrorContext(): DesktopUpdateErrorContext { + if (updateInstallInFlight) return "install"; if (updateDownloadInFlight) return "download"; if (updateCheckInFlight) return "check"; return updateState.errorContext; @@ -807,6 +809,7 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed } isQuitting = true; + updateInstallInFlight = true; clearUpdatePollTimer(); try { await stopBackendAndWaitForExit(); @@ -814,10 +817,14 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed for (const win of BrowserWindow.getAllWindows()) { win.destroy(); } + // `quitAndInstall()` only starts the handoff to the updater. The actual + // install may still fail asynchronously, so keep the action incomplete + // until we either quit or receive an updater error. autoUpdater.quitAndInstall(true, true); - return { accepted: true, completed: true }; + return { accepted: true, completed: false }; } catch (error: unknown) { const message = formatErrorMessage(error); + updateInstallInFlight = false; isQuitting = false; setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); console.error(`[desktop-updater] Failed to install update: ${message}`); @@ -854,6 +861,13 @@ function configureAutoUpdater(): void { } } + if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) { + autoUpdater.setFeedURL({ + provider: "generic", + url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`, + }); + } + autoUpdater.autoDownload = false; autoUpdater.autoInstallOnAppQuit = false; // Keep alpha branding, but force all installs onto the stable update track. @@ -890,6 +904,13 @@ function configureAutoUpdater(): void { }); autoUpdater.on("error", (error) => { const message = formatErrorMessage(error); + if (updateInstallInFlight) { + updateInstallInFlight = false; + isQuitting = false; + setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message)); + console.error(`[desktop-updater] Updater error: ${message}`); + return; + } if (!updateCheckInFlight && !updateDownloadInFlight) { setUpdateState({ status: "error", @@ -1365,6 +1386,7 @@ async function bootstrap(): Promise { app.on("before-quit", () => { isQuitting = true; + updateInstallInFlight = false; writeDesktopLogHeader("before-quit received"); clearUpdatePollTimer(); stopBackend(); diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.ts index 984eebd6b1..340b9a0164 100644 --- a/apps/web/src/components/desktopUpdate.logic.test.ts +++ b/apps/web/src/components/desktopUpdate.logic.test.ts @@ -145,19 +145,26 @@ describe("getDesktopUpdateActionError", () => { }); describe("desktop update UI helpers", () => { - it("toasts only for accepted incomplete actions", () => { + it("toasts only for actionable updater errors", () => { expect( shouldToastDesktopUpdateActionResult({ accepted: true, completed: false, - state: baseState, + state: { ...baseState, message: "checksum mismatch" }, }), ).toBe(true); + expect( + shouldToastDesktopUpdateActionResult({ + accepted: true, + completed: false, + state: { ...baseState, message: null }, + }), + ).toBe(false); expect( shouldToastDesktopUpdateActionResult({ accepted: true, completed: true, - state: baseState, + state: { ...baseState, message: "checksum mismatch" }, }), ).toBe(false); }); diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index faf30883cc..5c9c303026 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -87,7 +87,7 @@ export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): } export function shouldToastDesktopUpdateActionResult(result: DesktopUpdateActionResult): boolean { - return result.accepted && !result.completed; + return getDesktopUpdateActionError(result) !== null; } export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | null): boolean { diff --git a/package.json b/package.json index 33e65e90e9..6f14f7b77f 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "start": "turbo run start --filter=t3", "start:desktop": "turbo run start --filter=@t3tools/desktop", "start:marketing": "turbo run preview --filter=@t3tools/marketing", + "start:mock-update-server": "bun run scripts/mock-update-server.ts", "build": "turbo run build", "build:marketing": "turbo run build --filter=@t3tools/marketing", "build:desktop": "turbo run build --filter=@t3tools/desktop --filter=t3", diff --git a/scripts/build-desktop-artifact.ts b/scripts/build-desktop-artifact.ts index 0b875721fd..4f1886c4ad 100644 --- a/scripts/build-desktop-artifact.ts +++ b/scripts/build-desktop-artifact.ts @@ -74,6 +74,8 @@ interface BuildCliInput { readonly keepStage: Option.Option; readonly signed: Option.Option; readonly verbose: Option.Option; + readonly mockUpdates: Option.Option; + readonly mockUpdateServerPort: Option.Option; } function detectHostBuildPlatform(hostPlatform: string): typeof BuildPlatform.Type | undefined { @@ -162,6 +164,8 @@ interface ResolvedBuildOptions { readonly keepStage: boolean; readonly signed: boolean; readonly verbose: boolean; + readonly mockUpdates: boolean; + readonly mockUpdateServerPort: string | undefined; } interface StagePackageJson { @@ -204,6 +208,8 @@ const BuildEnvConfig = Config.all({ keepStage: Config.boolean("T3CODE_DESKTOP_KEEP_STAGE").pipe(Config.withDefault(false)), signed: Config.boolean("T3CODE_DESKTOP_SIGNED").pipe(Config.withDefault(false)), verbose: Config.boolean("T3CODE_DESKTOP_VERBOSE").pipe(Config.withDefault(false)), + mockUpdates: Config.boolean("T3CODE_DESKTOP_MOCK_UPDATES").pipe(Config.withDefault(false)), + mockUpdateServerPort: Config.string("T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT").pipe(Config.option), }); const resolveBooleanFlag = (flag: Option.Option, envValue: boolean) => @@ -231,13 +237,26 @@ const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: B const target = mergeOptions(input.target, env.target, PLATFORM_CONFIG[platform].defaultTarget); const arch = mergeOptions(input.arch, env.arch, getDefaultArch(platform)); const version = mergeOptions(input.buildVersion, env.version, undefined); - const outputDir = path.resolve(repoRoot, mergeOptions(input.outputDir, env.outputDir, "release")); + const releaseDir = resolveBooleanFlag(input.mockUpdates, env.mockUpdates) + ? "release-mock" + : "release"; + const outputDir = path.resolve( + repoRoot, + mergeOptions(input.outputDir, env.outputDir, releaseDir), + ); const skipBuild = resolveBooleanFlag(input.skipBuild, env.skipBuild); const keepStage = resolveBooleanFlag(input.keepStage, env.keepStage); const signed = resolveBooleanFlag(input.signed, env.signed); const verbose = resolveBooleanFlag(input.verbose, env.verbose); + const mockUpdates = resolveBooleanFlag(input.mockUpdates, env.mockUpdates); + const mockUpdateServerPort = mergeOptions( + input.mockUpdateServerPort, + env.mockUpdateServerPort, + undefined, + ); + return { platform, target, @@ -248,6 +267,8 @@ const resolveBuildOptions = Effect.fn("resolveBuildOptions")(function* (input: B keepStage, signed, verbose, + mockUpdates, + mockUpdateServerPort, } satisfies ResolvedBuildOptions; }); @@ -447,6 +468,8 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( target: string, productName: string, signed: boolean, + mockUpdates: boolean, + mockUpdateServerPort: string | undefined, ) { const buildConfig: Record = { appId: "com.t3tools.t3code", @@ -459,6 +482,13 @@ const createBuildConfig = Effect.fn("createBuildConfig")(function* ( const publishConfig = resolveGitHubPublishConfig(); if (publishConfig) { buildConfig.publish = [publishConfig]; + } else if (mockUpdates) { + buildConfig.publish = [ + { + provider: "generic", + url: `http://localhost:${mockUpdateServerPort ?? 3000}`, + }, + ]; } if (platform === "mac") { @@ -631,6 +661,8 @@ const buildDesktopArtifact = Effect.fn("buildDesktopArtifact")(function* ( options.target, desktopPackageJson.productName ?? "T3 Code", options.signed, + options.mockUpdates, + options.mockUpdateServerPort, ), dependencies: { ...resolvedServerDependencies, @@ -769,6 +801,14 @@ const buildDesktopArtifactCli = Command.make("build-desktop-artifact", { Flag.withDescription("Stream subprocess stdout (env: T3CODE_DESKTOP_VERBOSE)."), Flag.optional, ), + mockUpdates: Flag.boolean("mock-updates").pipe( + Flag.withDescription("Enable mock updates (env: T3CODE_DESKTOP_MOCK_UPDATES)."), + Flag.optional, + ), + mockUpdateServerPort: Flag.string("mock-update-server-port").pipe( + Flag.withDescription("Mock update server port (env: T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT)."), + Flag.optional, + ), }).pipe( Command.withDescription("Build a desktop artifact for T3 Code."), Command.withHandler((input) => Effect.flatMap(resolveBuildOptions(input), buildDesktopArtifact)), diff --git a/scripts/mock-update-server.ts b/scripts/mock-update-server.ts new file mode 100644 index 0000000000..57dab49ffa --- /dev/null +++ b/scripts/mock-update-server.ts @@ -0,0 +1,44 @@ +import { resolve, relative } from "node:path"; +import { realpathSync } from "node:fs"; + +const port = Number(process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000); +const root = + process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_ROOT ?? + resolve(import.meta.dirname, "..", "release-mock"); + +const mockServerLog = (level: "info" | "warn" | "error" = "info", message: string) => { + console[level](`[mock-update-server] ${message}`); +}; + +function isWithinRoot(filePath: string): boolean { + try { + return !relative(realpathSync(root), realpathSync(filePath)).startsWith("."); + } catch (error) { + mockServerLog("error", `Error checking if file is within root: ${error}`); + return false; + } +} + +Bun.serve({ + port, + hostname: "localhost", + fetch: async (request) => { + const url = new URL(request.url); + const path = url.pathname; + mockServerLog("info", `Request received for path: ${path}`); + const filePath = resolve(root, `.${path}`); + if (!isWithinRoot(filePath)) { + mockServerLog("warn", `Attempted to access file outside of root: ${filePath}`); + return new Response("Not Found", { status: 404 }); + } + const file = Bun.file(filePath); + if (!(await file.exists())) { + mockServerLog("warn", `Attempted to access non-existent file: ${filePath}`); + return new Response("Not Found", { status: 404 }); + } + mockServerLog("info", `Serving file: ${filePath}`); + return new Response(file.stream()); + }, +}); + +mockServerLog("info", `running on http://localhost:${port}`); From 5b1d5c1220165db816ea5eee15436df778a11aac Mon Sep 17 00:00:00 2001 From: maria Date: Sat, 28 Mar 2026 19:49:53 -0300 Subject: [PATCH 25/66] fix(ci): use whitespace-insensitive PR size diff (#1500) --- .github/workflows/pr-size.yml | 99 ++++++++++++++++++++++++----------- 1 file changed, 68 insertions(+), 31 deletions(-) diff --git a/.github/workflows/pr-size.yml b/.github/workflows/pr-size.yml index ced845a28f..15c04d663d 100644 --- a/.github/workflows/pr-size.yml +++ b/.github/workflows/pr-size.yml @@ -124,25 +124,49 @@ jobs: group: pr-size-${{ github.event.pull_request.number }} cancel-in-progress: true steps: + - name: Checkout base repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 - name: Sync PR size label uses: actions/github-script@v8 env: PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }} with: script: | + const { execFileSync } = require("node:child_process"); + const issueNumber = context.payload.pull_request.number; + const baseSha = context.payload.pull_request.base.sha; + const headSha = context.payload.pull_request.head.sha; + const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`; const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]"); const managedLabelNames = new Set(managedLabels.map((label) => label.name)); // Keep this aligned with the repo's test entrypoints and test-only support files. - const testFilePatterns = [ - /(^|\/)__tests__(\/|$)/, - /(^|\/)tests?(\/|$)/, - /^apps\/server\/integration\//, - /\.(test|spec|browser|integration)\.[^.\/]+$/, + const testExcludePathspecs = [ + ":(glob,exclude)**/__tests__/**", + ":(glob,exclude)**/test/**", + ":(glob,exclude)**/tests/**", + ":(glob,exclude)apps/server/integration/**", + ":(glob,exclude)**/*.test.*", + ":(glob,exclude)**/*.spec.*", + ":(glob,exclude)**/*.browser.*", + ":(glob,exclude)**/*.integration.*", ]; - const isTestFile = (filename) => - testFilePatterns.some((pattern) => pattern.test(filename)); + const sumNumstat = (text) => + text + .split("\n") + .filter(Boolean) + .reduce((total, line) => { + const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t"); + const additions = + insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0; + const deletions = + deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0; + + return total + additions + deletions; + }, 0); const resolveSizeLabel = (totalChangedLines) => { if (totalChangedLines < 10) { @@ -168,40 +192,53 @@ jobs: return "size:XXL"; }; - const files = await github.paginate( - github.rest.pulls.listFiles, + execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], { + stdio: "inherit", + }); + + execFileSync( + "git", + ["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`], { - owner: context.repo.owner, - repo: context.repo.repo, - pull_number: issueNumber, - per_page: 100, + stdio: "inherit", }, - (response) => response.data, ); - if (files.length >= 3000) { + const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], { + encoding: "utf8", + }).trim(); + + if (resolvedHeadSha !== headSha) { core.warning( - "The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.", + `Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`, ); } - let testChangedLines = 0; - let nonTestChangedLines = 0; + execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], { + stdio: "inherit", + }); - for (const file of files) { - const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0); + const diffArgs = [ + "diff", + "--numstat", + "--ignore-all-space", + "--ignore-blank-lines", + `${baseSha}...${resolvedHeadSha}`, + ]; - if (changedLinesForFile === 0) { - continue; - } - - if (isTestFile(file.filename)) { - testChangedLines += changedLinesForFile; - continue; - } - - nonTestChangedLines += changedLinesForFile; - } + const totalChangedLines = sumNumstat( + execFileSync( + "git", + diffArgs, + { encoding: "utf8" }, + ), + ); + const nonTestChangedLines = sumNumstat( + execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], { + encoding: "utf8", + }), + ); + const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines); const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines; const nextLabelName = resolveSizeLabel(changedLines); From 5210a833a58d24388611fb6a47b56a460a96422f Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sun, 29 Mar 2026 04:28:37 +0530 Subject: [PATCH 26/66] Fix sidebar thread panel weird states. (#1497) Co-authored-by: Julius Marminge --- apps/web/src/components/Sidebar.tsx | 79 ++++++++++++++--------------- 1 file changed, 38 insertions(+), 41 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 2d974be3ee..299948c862 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -72,7 +72,6 @@ import { } from "./desktopUpdate.logic"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; import { Button } from "./ui/button"; -import { Collapsible, CollapsibleContent } from "./ui/collapsible"; import { Menu, MenuGroup, MenuPopup, MenuRadioGroup, MenuRadioItem, MenuTrigger } from "./ui/menu"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { @@ -1228,7 +1227,7 @@ export default function Sidebar() { }; return ( - + <>
- - - {renderedThreads.map((thread) => renderThreadRow(thread))} + + {shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))} - {project.expanded && hasHiddenThreads && !isThreadListExpanded && ( - - } - data-thread-selection-safe - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - expandThreadListForProject(project.id); - }} - > - Show more - - - )} - {project.expanded && hasHiddenThreads && isThreadListExpanded && ( - - } - data-thread-selection-safe - size="sm" - className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" - onClick={() => { - collapseThreadListForProject(project.id); - }} - > - Show less - - - )} - - -
+ {project.expanded && hasHiddenThreads && !isThreadListExpanded && ( + + } + data-thread-selection-safe + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + expandThreadListForProject(project.id); + }} + > + Show more + + + )} + {project.expanded && hasHiddenThreads && isThreadListExpanded && ( + + } + data-thread-selection-safe + size="sm" + className="h-6 w-full translate-x-0 justify-start px-2 text-left text-[10px] text-muted-foreground/60 hover:bg-accent hover:text-muted-foreground/80" + onClick={() => { + collapseThreadListForProject(project.id); + }} + > + Show less + + + )} + + ); } From 64d21bd6d29fbf795262fd6f031db81e3ddbad02 Mon Sep 17 00:00:00 2001 From: Jono Kemball Date: Sun, 29 Mar 2026 12:09:19 +1300 Subject: [PATCH 27/66] fix: Prevent sidebar project dragging when using macos control+click to open context menu (#873) Co-authored-by: Julius Marminge --- apps/web/src/components/Sidebar.logic.test.ts | 33 +++++++++++++++ apps/web/src/components/Sidebar.logic.ts | 9 +++++ apps/web/src/components/Sidebar.tsx | 40 +++++++++++++++++-- 3 files changed, 78 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 0824758baa..cc49a82e69 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -5,6 +5,7 @@ import { getVisibleThreadsForProject, getProjectSortTimestamp, hasUnseenCompletion, + isContextMenuPointerDown, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, @@ -96,6 +97,38 @@ describe("resolveSidebarNewThreadEnvMode", () => { }); }); +describe("isContextMenuPointerDown", () => { + it("treats secondary-button presses as context menu gestures on all platforms", () => { + expect( + isContextMenuPointerDown({ + button: 2, + ctrlKey: false, + isMac: false, + }), + ).toBe(true); + }); + + it("treats ctrl+primary-click as a context menu gesture on macOS", () => { + expect( + isContextMenuPointerDown({ + button: 0, + ctrlKey: true, + isMac: true, + }), + ).toBe(true); + }); + + it("does not treat ctrl+primary-click as a context menu gesture off macOS", () => { + expect( + isContextMenuPointerDown({ + button: 0, + ctrlKey: true, + isMac: false, + }), + ).toBe(false); + }); +}); + describe("resolveThreadStatusPill", () => { const baseThread = { interactionMode: "plan" as const, diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 6ca29d27e9..22a6268ac7 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -67,6 +67,15 @@ export function resolveSidebarNewThreadEnvMode(input: { return input.requestedEnvMode ?? input.defaultEnvMode; } +export function isContextMenuPointerDown(input: { + button: number; + ctrlKey: boolean; + isMac: boolean; +}): boolean { + if (input.button === 2) return true; + return input.isMac && input.button === 0 && input.ctrlKey; +} + export function resolveThreadRowClassName(input: { isActive: boolean; isSelected: boolean; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 299948c862..d6ef9fc819 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -13,7 +13,15 @@ import { } from "lucide-react"; import { ProjectFavicon } from "./ProjectFavicon"; import { autoAnimate } from "@formkit/auto-animate"; -import { useCallback, useEffect, useMemo, useRef, useState, type MouseEvent } from "react"; +import { + useCallback, + useEffect, + useMemo, + useRef, + useState, + type MouseEvent, + type PointerEvent, +} from "react"; import { DndContext, type DragCancelEvent, @@ -93,6 +101,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore"; import { isNonEmpty as isNonEmptyString } from "effect/String"; import { getVisibleThreadsForProject, + isContextMenuPointerDown, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, @@ -348,6 +357,7 @@ export default function Sidebar() { const renamingInputRef = useRef(null); const dragInProgressRef = useRef(false); const suppressProjectClickAfterDragRef = useRef(false); + const suppressProjectClickForContextMenuRef = useRef(false); const [desktopUpdateState, setDesktopUpdateState] = useState(null); const selectedThreadIds = useThreadSelectionStore((s) => s.selectedThreadIds); const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); @@ -941,9 +951,24 @@ export default function Sidebar() { animatedThreadListsRef.current.add(node); }, []); - const handleProjectTitlePointerDownCapture = useCallback(() => { - suppressProjectClickAfterDragRef.current = false; - }, []); + const handleProjectTitlePointerDownCapture = useCallback( + (event: PointerEvent) => { + suppressProjectClickForContextMenuRef.current = false; + if ( + isContextMenuPointerDown({ + button: event.button, + ctrlKey: event.ctrlKey, + isMac: isMacPlatform(navigator.platform), + }) + ) { + // Keep context-menu gestures from arming the sortable drag sensor. + event.stopPropagation(); + } + + suppressProjectClickAfterDragRef.current = false; + }, + [], + ); const visibleThreads = useMemo( () => threads.filter((thread) => thread.archivedAt === null), @@ -1242,6 +1267,7 @@ export default function Sidebar() { onKeyDown={(event) => handleProjectTitleKeyDown(event, project.id)} onContextMenu={(event) => { event.preventDefault(); + suppressProjectClickForContextMenuRef.current = true; void handleProjectContextMenu(project.id, { x: event.clientX, y: event.clientY, @@ -1351,6 +1377,12 @@ export default function Sidebar() { const handleProjectTitleClick = useCallback( (event: React.MouseEvent, projectId: ProjectId) => { + if (suppressProjectClickForContextMenuRef.current) { + suppressProjectClickForContextMenuRef.current = false; + event.preventDefault(); + event.stopPropagation(); + return; + } if (dragInProgressRef.current) { event.preventDefault(); event.stopPropagation(); From 33773ff17eb7dcdb3a020b0d0a1c27ac0df86125 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 16:13:52 -0700 Subject: [PATCH 28/66] Harden Claude stream exit handling (#1504) --- .../src/provider/Layers/ClaudeAdapter.ts | 21 +++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index b0f080118e..6b50bd4fbb 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -2817,16 +2817,25 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( providerRefs: {}, }); - const streamFiber = runFork(runSdkStream(context)); + let streamFiber: Fiber.Fiber; + streamFiber = runFork( + Effect.exit(runSdkStream(context)).pipe( + Effect.flatMap((exit) => { + if (context.stopped) { + return Effect.void; + } + if (context.streamFiber === streamFiber) { + context.streamFiber = undefined; + } + return handleStreamExit(context, exit); + }), + ), + ); context.streamFiber = streamFiber; - streamFiber.addObserver((exit) => { - if (context.stopped) { - return; - } + streamFiber.addObserver(() => { if (context.streamFiber === streamFiber) { context.streamFiber = undefined; } - runFork(handleStreamExit(context, exit)); }); return { From 5513845fd56acf7a019d24e72fc4e11bf5654f50 Mon Sep 17 00:00:00 2001 From: maria Date: Sat, 28 Mar 2026 21:03:01 -0300 Subject: [PATCH 29/66] feat(threads): auto-generate first-turn thread titles (#1375) --- .../OrchestrationEngineHarness.integration.ts | 3 +- .../git/Layers/ClaudeTextGeneration.test.ts | 59 +++++ .../src/git/Layers/ClaudeTextGeneration.ts | 37 +++- .../git/Layers/CodexTextGeneration.test.ts | 64 ++++++ .../src/git/Layers/CodexTextGeneration.ts | 50 ++++- apps/server/src/git/Layers/GitManager.test.ts | 25 ++- .../src/git/Layers/RoutingTextGeneration.ts | 1 + apps/server/src/git/Prompts.test.ts | 45 +++- apps/server/src/git/Prompts.ts | 65 +++++- .../server/src/git/Services/TextGeneration.ts | 20 ++ apps/server/src/git/Utils.ts | 21 ++ .../Layers/ProviderCommandReactor.test.ts | 209 +++++++++++++++++- .../Layers/ProviderCommandReactor.ts | 104 +++++++-- apps/server/src/orchestration/decider.ts | 2 +- apps/web/src/components/ChatView.tsx | 9 +- apps/web/src/truncateTitle.test.ts | 17 -- packages/contracts/src/orchestration.test.ts | 31 +++ packages/contracts/src/orchestration.ts | 5 +- packages/shared/package.json | 4 + packages/shared/src/String.test.ts | 17 ++ .../shared/src/String.ts | 3 +- 21 files changed, 732 insertions(+), 59 deletions(-) delete mode 100644 apps/web/src/truncateTitle.test.ts create mode 100644 packages/shared/src/String.test.ts rename apps/web/src/truncateTitle.ts => packages/shared/src/String.ts (66%) diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 115d18d02b..1a8f802d73 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -306,7 +306,8 @@ export const makeOrchestrationIntegrationHarness = ( Effect.succeed({ branch: input.newBranch }), } as unknown as GitCoreShape); const textGenerationLayer = Layer.succeed(TextGeneration, { - generateBranchName: () => Effect.succeed({ branch: null }), + generateBranchName: () => Effect.succeed({ branch: "update" }), + generateThreadTitle: () => Effect.succeed({ title: "New thread" }), } as unknown as TextGenerationShape); const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts index 29ae4796fe..0847134698 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.test.ts @@ -5,6 +5,7 @@ import { expect } from "vitest"; import { ServerConfig } from "../../config.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; +import { sanitizeThreadTitle } from "../Utils.ts"; import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; @@ -247,4 +248,62 @@ it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => { }), ), ); + + it.effect("generates thread titles through the Claude provider", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: + ' "Reconnect failures after restart because the session state does not recover" ', + }, + }), + stdinMustContain: "You write concise thread titles for coding conversations.", + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate reconnect failures after restarting the session.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe( + sanitizeThreadTitle( + '"Reconnect failures after restart because the session state does not recover"', + ), + ); + }), + ), + ); + + it.effect("falls back when Claude thread title normalization becomes whitespace-only", () => + withFakeClaudeEnv( + { + output: JSON.stringify({ + structured_output: { + title: ' """ """ ', + }, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + }, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); }); diff --git a/apps/server/src/git/Layers/ClaudeTextGeneration.ts b/apps/server/src/git/Layers/ClaudeTextGeneration.ts index 919c3a323d..f4d3833627 100644 --- a/apps/server/src/git/Layers/ClaudeTextGeneration.ts +++ b/apps/server/src/git/Layers/ClaudeTextGeneration.ts @@ -20,11 +20,13 @@ import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "../Prompts.ts"; import { normalizeCliError, sanitizeCommitSubject, sanitizePrTitle, + sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts"; @@ -70,7 +72,11 @@ const makeClaudeTextGeneration = Effect.gen(function* () { outputSchemaJson, modelSelection, }: { - operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName"; + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; cwd: string; prompt: string; outputSchemaJson: S; @@ -299,10 +305,39 @@ const makeClaudeTextGeneration = Effect.gen(function* () { }; }); + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "ClaudeTextGeneration.generateThreadTitle", + )(function* (input) { + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "claudeAgent") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runClaudeJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + }; + }); + return { generateCommitMessage, generatePrContent, generateBranchName, + generateThreadTitle, } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Layers/CodexTextGeneration.test.ts b/apps/server/src/git/Layers/CodexTextGeneration.test.ts index 1b07d87d90..21a97eec9c 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.test.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.test.ts @@ -358,6 +358,70 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => { ), ); + it.effect("generates thread titles and trims them for sidebar use", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: + ' "Investigate websocket reconnect regressions after worktree restore" \nignored line', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Please investigate websocket reconnect regressions after a worktree restore.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("Investigate websocket reconnect regressions aft..."); + }), + ), + ); + + it.effect("falls back when thread title normalization becomes whitespace-only", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ' """ """ ', + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("New thread"); + }), + ), + ); + + it.effect("trims whitespace exposed after quote removal in thread titles", () => + withFakeCodexEnv( + { + output: JSON.stringify({ + title: ` "' hello world '" `, + }), + }, + Effect.gen(function* () { + const textGeneration = yield* TextGeneration; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: process.cwd(), + message: "Name this thread.", + modelSelection: DEFAULT_TEST_MODEL_SELECTION, + }); + + expect(generated.title).toBe("hello world"); + }), + ), + ); + it.effect("omits attachment metadata section when no attachments are provided", () => withFakeCodexEnv( { diff --git a/apps/server/src/git/Layers/CodexTextGeneration.ts b/apps/server/src/git/Layers/CodexTextGeneration.ts index 8f332bf13e..c82923f93e 100644 --- a/apps/server/src/git/Layers/CodexTextGeneration.ts +++ b/apps/server/src/git/Layers/CodexTextGeneration.ts @@ -11,6 +11,7 @@ import { ServerConfig } from "../../config.ts"; import { TextGenerationError } from "../Errors.ts"; import { type BranchNameGenerationInput, + type ThreadTitleGenerationResult, type TextGenerationShape, TextGeneration, } from "../Services/TextGeneration.ts"; @@ -18,11 +19,13 @@ import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "../Prompts.ts"; import { normalizeCliError, sanitizeCommitSubject, sanitizePrTitle, + sanitizeThreadTitle, toJsonSchemaObject, } from "../Utils.ts"; import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts"; @@ -30,7 +33,6 @@ import { ServerSettingsService } from "../../serverSettings.ts"; const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low"; const CODEX_TIMEOUT_MS = 180_000; - const makeCodexTextGeneration = Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -83,7 +85,11 @@ const makeCodexTextGeneration = Effect.gen(function* () { fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void)); const materializeImageAttachments = ( - _operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName", + _operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle", attachments: BranchNameGenerationInput["attachments"], ): Effect.Effect => Effect.gen(function* () { @@ -124,7 +130,11 @@ const makeCodexTextGeneration = Effect.gen(function* () { cleanupPaths = [], modelSelection, }: { - operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName"; + operation: + | "generateCommitMessage" + | "generatePrContent" + | "generateBranchName" + | "generateThreadTitle"; cwd: string; prompt: string; outputSchemaJson: S; @@ -363,10 +373,44 @@ const makeCodexTextGeneration = Effect.gen(function* () { }; }); + const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn( + "CodexTextGeneration.generateThreadTitle", + )(function* (input) { + const { imagePaths } = yield* materializeImageAttachments( + "generateThreadTitle", + input.attachments, + ); + const { prompt, outputSchema } = buildThreadTitlePrompt({ + message: input.message, + attachments: input.attachments, + }); + + if (input.modelSelection.provider !== "codex") { + return yield* new TextGenerationError({ + operation: "generateThreadTitle", + detail: "Invalid model selection.", + }); + } + + const generated = yield* runCodexJson({ + operation: "generateThreadTitle", + cwd: input.cwd, + prompt, + outputSchemaJson: outputSchema, + imagePaths, + modelSelection: input.modelSelection, + }); + + return { + title: sanitizeThreadTitle(generated.title), + } satisfies ThreadTitleGenerationResult; + }); + return { generateCommitMessage, generatePrContent, generateBranchName, + generateThreadTitle, } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index 57d6853c4a..d13c389fc8 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -6,7 +6,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { it } from "@effect/vitest"; import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; import { expect } from "vitest"; -import type { GitActionProgressEvent } from "@t3tools/contracts"; +import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts"; import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts"; import { type GitManagerShape } from "../Services/GitManager.ts"; @@ -49,6 +49,7 @@ interface FakeGitTextGeneration { stagedSummary: string; stagedPatch: string; includeBranch?: boolean; + modelSelection: ModelSelection; }) => Effect.Effect< { subject: string; body: string; branch?: string | undefined }, TextGenerationError @@ -60,11 +61,18 @@ interface FakeGitTextGeneration { commitSummary: string; diffSummary: string; diffPatch: string; + modelSelection: ModelSelection; }) => Effect.Effect<{ title: string; body: string }, TextGenerationError>; generateBranchName: (input: { cwd: string; message: string; + modelSelection: ModelSelection; }) => Effect.Effect<{ branch: string }, TextGenerationError>; + generateThreadTitle: (input: { + cwd: string; + message: string; + modelSelection: ModelSelection; + }) => Effect.Effect<{ title: string }, TextGenerationError>; } type FakePullRequest = NonNullable; @@ -168,6 +176,10 @@ function createTextGeneration(overrides: Partial = {}): T Effect.succeed({ branch: "update-workflow", }), + generateThreadTitle: () => + Effect.succeed({ + title: "Update workflow", + }), ...overrides, }; @@ -205,6 +217,17 @@ function createTextGeneration(overrides: Partial = {}): T }), ), ), + generateThreadTitle: (input) => + implementation.generateThreadTitle(input).pipe( + Effect.mapError( + (cause) => + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "fake text generation failed", + ...(cause !== undefined ? { cause } : {}), + }), + ), + ), }; } diff --git a/apps/server/src/git/Layers/RoutingTextGeneration.ts b/apps/server/src/git/Layers/RoutingTextGeneration.ts index 7915131385..dee12a3e0e 100644 --- a/apps/server/src/git/Layers/RoutingTextGeneration.ts +++ b/apps/server/src/git/Layers/RoutingTextGeneration.ts @@ -47,6 +47,7 @@ const makeRoutingTextGeneration = Effect.gen(function* () { route(input.modelSelection.provider).generateCommitMessage(input), generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input), generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input), + generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input), } satisfies TextGenerationShape; }); diff --git a/apps/server/src/git/Prompts.test.ts b/apps/server/src/git/Prompts.test.ts index 23c3eca557..7951e78b39 100644 --- a/apps/server/src/git/Prompts.test.ts +++ b/apps/server/src/git/Prompts.test.ts @@ -4,8 +4,9 @@ import { buildBranchNamePrompt, buildCommitMessagePrompt, buildPrContentPrompt, + buildThreadTitlePrompt, } from "./Prompts.ts"; -import { normalizeCliError } from "./Utils.ts"; +import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts"; import { TextGenerationError } from "./Errors.ts"; describe("buildCommitMessagePrompt", () => { @@ -103,6 +104,48 @@ describe("buildBranchNamePrompt", () => { }); }); +describe("buildThreadTitlePrompt", () => { + it("includes the user message in the prompt", () => { + const result = buildThreadTitlePrompt({ + message: "Investigate reconnect regressions after session restore", + }); + + expect(result.prompt).toContain("User message:"); + expect(result.prompt).toContain("Investigate reconnect regressions after session restore"); + expect(result.prompt).not.toContain("Attachment metadata:"); + }); + + it("includes attachment metadata when attachments are provided", () => { + const result = buildThreadTitlePrompt({ + message: "Name this thread from the screenshot", + attachments: [ + { + type: "image" as const, + id: "att-456", + name: "thread.png", + mimeType: "image/png", + sizeBytes: 67890, + }, + ], + }); + + expect(result.prompt).toContain("Attachment metadata:"); + expect(result.prompt).toContain("thread.png"); + expect(result.prompt).toContain("image/png"); + expect(result.prompt).toContain("67890 bytes"); + }); +}); + +describe("sanitizeThreadTitle", () => { + it("truncates long titles with the shared sidebar-safe limit", () => { + expect( + sanitizeThreadTitle( + ' "Reconnect failures after restart because the session state does not recover" ', + ), + ).toBe("Reconnect failures after restart because the se..."); + }); +}); + describe("normalizeCliError", () => { it("detects 'Command not found' and includes CLI name in the message", () => { const error = normalizeCliError( diff --git a/apps/server/src/git/Prompts.ts b/apps/server/src/git/Prompts.ts index 2eacf370eb..4092358825 100644 --- a/apps/server/src/git/Prompts.ts +++ b/apps/server/src/git/Prompts.ts @@ -119,19 +119,24 @@ export interface BranchNamePromptInput { attachments?: ReadonlyArray | undefined; } -export function buildBranchNamePrompt(input: BranchNamePromptInput) { +interface PromptFromMessageInput { + instruction: string; + responseShape: string; + rules: ReadonlyArray; + message: string; + attachments?: ReadonlyArray | undefined; +} + +function buildPromptFromMessage(input: PromptFromMessageInput): string { const attachmentLines = (input.attachments ?? []).map( (attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`, ); const promptSections = [ - "You generate concise git branch names.", - "Return a JSON object with key: branch.", + input.instruction, + input.responseShape, "Rules:", - "- Branch should describe the requested work from the user message.", - "- Keep it short and specific (2-6 words).", - "- Use plain words only, no issue prefixes and no punctuation-heavy text.", - "- If images are attached, use them as primary context for visual/UI issues.", + ...input.rules.map((rule) => `- ${rule}`), "", "User message:", limitSection(input.message, 8_000), @@ -144,10 +149,54 @@ export function buildBranchNamePrompt(input: BranchNamePromptInput) { ); } - const prompt = promptSections.join("\n"); + return promptSections.join("\n"); +} + +export function buildBranchNamePrompt(input: BranchNamePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You generate concise git branch names.", + responseShape: "Return a JSON object with key: branch.", + rules: [ + "Branch should describe the requested work from the user message.", + "Keep it short and specific (2-6 words).", + "Use plain words only, no issue prefixes and no punctuation-heavy text.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); const outputSchema = Schema.Struct({ branch: Schema.String, }); return { prompt, outputSchema }; } + +// --------------------------------------------------------------------------- +// Thread title +// --------------------------------------------------------------------------- + +export interface ThreadTitlePromptInput { + message: string; + attachments?: ReadonlyArray | undefined; +} + +export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) { + const prompt = buildPromptFromMessage({ + instruction: "You write concise thread titles for coding conversations.", + responseShape: "Return a JSON object with key: title.", + rules: [ + "Title should summarize the user's request, not restate it verbatim.", + "Keep it short and specific (3-8 words).", + "Avoid quotes, filler, prefixes, and trailing punctuation.", + "If images are attached, use them as primary context for visual/UI issues.", + ], + message: input.message, + attachments: input.attachments, + }); + const outputSchema = Schema.Struct({ + title: Schema.String, + }); + + return { prompt, outputSchema }; +} diff --git a/apps/server/src/git/Services/TextGeneration.ts b/apps/server/src/git/Services/TextGeneration.ts index e9f2230f43..0df2fff62c 100644 --- a/apps/server/src/git/Services/TextGeneration.ts +++ b/apps/server/src/git/Services/TextGeneration.ts @@ -61,12 +61,25 @@ export interface BranchNameGenerationResult { branch: string; } +export interface ThreadTitleGenerationInput { + cwd: string; + message: string; + attachments?: ReadonlyArray | undefined; + /** What model and provider to use for generation. */ + modelSelection: ModelSelection; +} + +export interface ThreadTitleGenerationResult { + title: string; +} + export interface TextGenerationService { generateCommitMessage( input: CommitMessageGenerationInput, ): Promise; generatePrContent(input: PrContentGenerationInput): Promise; generateBranchName(input: BranchNameGenerationInput): Promise; + generateThreadTitle(input: ThreadTitleGenerationInput): Promise; } /** @@ -93,6 +106,13 @@ export interface TextGenerationShape { readonly generateBranchName: ( input: BranchNameGenerationInput, ) => Effect.Effect; + + /** + * Generate a concise thread title from a user's first message. + */ + readonly generateThreadTitle: ( + input: ThreadTitleGenerationInput, + ) => Effect.Effect; } /** diff --git a/apps/server/src/git/Utils.ts b/apps/server/src/git/Utils.ts index eb208deccb..8f0321fd52 100644 --- a/apps/server/src/git/Utils.ts +++ b/apps/server/src/git/Utils.ts @@ -53,6 +53,27 @@ export function sanitizePrTitle(raw: string): string { return "Update project changes"; } +/** Normalise a raw thread title to a compact single-line sidebar-safe label. */ +export function sanitizeThreadTitle(raw: string): string { + const normalized = raw + .trim() + .split(/\r?\n/g)[0] + ?.trim() + .replace(/^['"`]+|['"`]+$/g, "") + .trim() + .replace(/\s+/g, " "); + + if (!normalized || normalized.trim().length === 0) { + return "New thread"; + } + + if (normalized.length <= 50) { + return normalized; + } + + return `${normalized.slice(0, 47).trimEnd()}...`; +} + /** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */ function cliLabel(cliName: string): string { const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 834ab9be9e..4e87390eb1 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -176,7 +176,7 @@ describe("ProviderCommandReactor", () => { : "renamed-branch", }), ); - const generateBranchName = vi.fn(() => + const generateBranchName = vi.fn((_) => Effect.fail( new TextGenerationError({ operation: "generateBranchName", @@ -184,6 +184,14 @@ describe("ProviderCommandReactor", () => { }), ), ); + const generateThreadTitle = vi.fn((_) => + Effect.fail( + new TextGenerationError({ + operation: "generateThreadTitle", + detail: "disabled in test harness", + }), + ), + ); const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never; const service: ProviderServiceShape = { @@ -213,7 +221,10 @@ describe("ProviderCommandReactor", () => { Layer.provideMerge(Layer.succeed(ProviderService, service)), Layer.provideMerge(Layer.succeed(GitCore, { renameBranch } as unknown as GitCoreShape)), Layer.provideMerge( - Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape), + Layer.mock(TextGeneration, { + generateBranchName, + generateThreadTitle, + }), ), Layer.provideMerge(ServerSettingsService.layerTest()), Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)), @@ -264,6 +275,7 @@ describe("ProviderCommandReactor", () => { stopSession, renameBranch, generateBranchName, + generateThreadTitle, stateDir, drain, }; @@ -308,6 +320,199 @@ describe("ProviderCommandReactor", () => { expect(thread?.session?.runtimeMode).toBe("approval-required"); }); + it("generates a thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + harness.generateThreadTitle.mockReturnValue(Effect.succeed({ title: "Generated title" })); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + expect(harness.generateThreadTitle.mock.calls[0]?.[0]).toMatchObject({ + message: "Please investigate reconnect failures after restarting the session.", + }); + + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Generated title" + ); + }); + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Generated title"); + }); + + it("does not overwrite an existing custom thread title on the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Please investigate reconnect failures after restar..."; + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-custom"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: "Keep this custom title", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-preserve"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-preserve"), + role: "user", + text: "Please investigate reconnect failures after restarting the session.", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + expect(harness.generateThreadTitle).not.toHaveBeenCalled(); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Keep this custom title"); + }); + + it("matches the client-seeded title even when the outgoing prompt is reformatted", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + const seededTitle = "Fix reconnect spinner on resume"; + harness.generateThreadTitle.mockReturnValue( + Effect.succeed({ + title: "Reconnect spinner resume bug", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-title-formatted-seed"), + threadId: ThreadId.makeUnsafe("thread-1"), + title: seededTitle, + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-title-formatted"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-title-formatted"), + role: "user", + text: "[effort:high]\\n\\nFix reconnect spinner on resume", + attachments: [], + }, + titleSeed: seededTitle, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateThreadTitle.mock.calls.length === 1); + await waitFor(async () => { + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"))?.title === + "Reconnect spinner resume bug" + ); + }); + + const readModel = await Effect.runPromise(harness.engine.getReadModel()); + const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1")); + expect(thread?.title).toBe("Reconnect spinner resume bug"); + }); + + it("generates a worktree branch name for the first turn", async () => { + const harness = await createHarness(); + const now = new Date().toISOString(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.meta.update", + commandId: CommandId.makeUnsafe("cmd-thread-branch"), + threadId: ThreadId.makeUnsafe("thread-1"), + branch: "t3code/1234abcd", + worktreePath: "/tmp/provider-project-worktree", + }), + ); + + harness.generateBranchName.mockImplementation((input: unknown) => + Effect.succeed({ + branch: + typeof input === "object" && + input !== null && + "modelSelection" in input && + typeof input.modelSelection === "object" && + input.modelSelection !== null && + "model" in input.modelSelection && + typeof input.modelSelection.model === "string" + ? `feature/${input.modelSelection.model}` + : "feature/generated", + }), + ); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.makeUnsafe("cmd-turn-start-branch-model"), + threadId: ThreadId.makeUnsafe("thread-1"), + message: { + messageId: asMessageId("user-message-branch-model"), + role: "user", + text: "Add a safer reconnect backoff.", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }), + ); + + await waitFor(() => harness.generateBranchName.mock.calls.length === 1); + expect(harness.generateBranchName.mock.calls[0]?.[0]).toMatchObject({ + message: "Add a safer reconnect backoff.", + }); + }); + it("forwards codex model options through session start and turn send", async () => { const harness = await createHarness(); const now = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 7c522e5799..f65137f4b5 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -73,6 +73,19 @@ const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30); const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access"; const WORKTREE_BRANCH_PREFIX = "t3code"; const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`); +const DEFAULT_THREAD_TITLE = "New thread"; + +function canReplaceThreadTitle(currentTitle: string, titleSeed?: string): boolean { + const trimmedCurrentTitle = currentTitle.trim(); + if (trimmedCurrentTitle === DEFAULT_THREAD_TITLE) { + return true; + } + + const trimmedTitleSeed = titleSeed?.trim(); + return trimmedTitleSeed !== undefined && trimmedTitleSeed.length > 0 + ? trimmedCurrentTitle === trimmedTitleSeed + : false; +} function isUnknownPendingApprovalRequestError(cause: Cause.Cause): boolean { const error = Cause.squash(cause); @@ -400,7 +413,6 @@ const make = Effect.gen(function* () { readonly threadId: ThreadId; readonly branch: string | null; readonly worktreePath: string | null; - readonly messageId: string; readonly messageText: string; readonly attachments?: ReadonlyArray; }) { @@ -411,16 +423,6 @@ const make = Effect.gen(function* () { return; } - const thread = yield* resolveThread(input.threadId); - if (!thread) { - return; - } - - const userMessages = thread.messages.filter((message) => message.role === "user"); - if (userMessages.length !== 1 || userMessages[0]?.id !== input.messageId) { - return; - } - const oldBranch = input.branch; const cwd = input.worktreePath; const attachments = input.attachments ?? []; @@ -459,6 +461,49 @@ const make = Effect.gen(function* () { ); }); + const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: { + readonly threadId: ThreadId; + readonly cwd: string; + readonly messageText: string; + readonly attachments?: ReadonlyArray; + readonly titleSeed?: string; + }) { + const attachments = input.attachments ?? []; + yield* Effect.gen(function* () { + const { textGenerationModelSelection: modelSelection } = + yield* serverSettingsService.getSettings; + + const generated = yield* textGeneration.generateThreadTitle({ + cwd: input.cwd, + message: input.messageText, + ...(attachments.length > 0 ? { attachments } : {}), + modelSelection, + }); + if (!generated) return; + + const thread = yield* resolveThread(input.threadId); + if (!thread) return; + if (!canReplaceThreadTitle(thread.title, input.titleSeed)) { + return; + } + + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: serverCommandId("thread-title-rename"), + threadId: input.threadId, + title: generated.title, + }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider command reactor failed to generate or rename thread title", { + threadId: input.threadId, + cwd: input.cwd, + cause: Cause.pretty(cause), + }), + ), + ); + }); + const processTurnStartRequested = Effect.fnUntraced(function* ( event: Extract, ) { @@ -485,14 +530,35 @@ const make = Effect.gen(function* () { return; } - yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ - threadId: event.payload.threadId, - branch: thread.branch, - worktreePath: thread.worktreePath, - messageId: message.id, - messageText: message.text, - ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), - }).pipe(Effect.forkScoped); + const isFirstUserMessageTurn = + thread.messages.filter((entry) => entry.role === "user").length === 1; + if (isFirstUserMessageTurn) { + const generationCwd = + resolveThreadWorkspaceCwd({ + thread, + projects: (yield* orchestrationEngine.getReadModel()).projects, + }) ?? process.cwd(); + const generationInput = { + messageText: message.text, + ...(message.attachments !== undefined ? { attachments: message.attachments } : {}), + ...(event.payload.titleSeed !== undefined ? { titleSeed: event.payload.titleSeed } : {}), + }; + + yield* maybeGenerateAndRenameWorktreeBranchForFirstTurn({ + threadId: event.payload.threadId, + branch: thread.branch, + worktreePath: thread.worktreePath, + ...generationInput, + }).pipe(Effect.forkScoped); + + if (canReplaceThreadTitle(thread.title, event.payload.titleSeed)) { + yield* maybeGenerateThreadTitleForFirstTurn({ + threadId: event.payload.threadId, + cwd: generationCwd, + ...generationInput, + }).pipe(Effect.forkScoped); + } + } yield* sendTurnForThread({ threadId: event.payload.threadId, diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index c70194befa..22f5bcb280 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -16,7 +16,6 @@ import { } from "./commandInvariants.ts"; const nowIso = () => new Date().toISOString(); - const defaultMetadata: Omit = { eventId: crypto.randomUUID() as OrchestrationEvent["eventId"], aggregateKind: "thread", @@ -376,6 +375,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.modelSelection !== undefined ? { modelSelection: command.modelSelection } : {}), + ...(command.titleSeed !== undefined ? { titleSeed: command.titleSeed } : {}), runtimeMode: targetThread.runtimeMode, interactionMode: targetThread.interactionMode, ...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}), diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1d926bf308..e572f3c470 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -22,6 +22,7 @@ import { RuntimeMode, } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model"; +import { truncate } from "@t3tools/shared/String"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useDebouncedValue } from "@tanstack/react-pacer"; @@ -69,7 +70,6 @@ import { proposedPlanTitle, resolvePlanFollowUpSubmission, } from "../proposedPlan"; -import { truncateTitle } from "../truncateTitle"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -2625,7 +2625,7 @@ export default function ChatView({ threadId }: ChatViewProps) { titleSeed = "New thread"; } } - const title = truncateTitle(titleSeed); + const title = truncate(titleSeed); const threadCreateModelSelection: ModelSelection = { provider: selectedProvider, model: @@ -2710,6 +2710,7 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: turnAttachments, }, modelSelection: selectedModelSelection, + titleSeed: title, runtimeMode, interactionMode, createdAt: messageCreatedAt, @@ -2991,6 +2992,7 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: [], }, modelSelection: selectedModelSelection, + titleSeed: activeThread.title, runtimeMode, interactionMode: nextInteractionMode, ...(nextInteractionMode === "default" && activeProposedPlan @@ -3070,7 +3072,7 @@ export default function ChatView({ threadId }: ChatViewProps) { effort: selectedPromptEffort, text: implementationPrompt, }); - const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown)); + const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown)); const nextThreadModelSelection: ModelSelection = selectedModelSelection; sendInFlightRef.current = true; @@ -3106,6 +3108,7 @@ export default function ChatView({ threadId }: ChatViewProps) { attachments: [], }, modelSelection: selectedModelSelection, + titleSeed: nextThreadTitle, runtimeMode, interactionMode: "default", createdAt, diff --git a/apps/web/src/truncateTitle.test.ts b/apps/web/src/truncateTitle.test.ts deleted file mode 100644 index d7d61c5da1..0000000000 --- a/apps/web/src/truncateTitle.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { truncateTitle } from "./truncateTitle"; - -describe("truncateTitle", () => { - it("trims surrounding whitespace", () => { - expect(truncateTitle(" hello world ")).toBe("hello world"); - }); - - it("returns trimmed text when within max length", () => { - expect(truncateTitle("alpha", 10)).toBe("alpha"); - }); - - it("appends ellipsis when text exceeds max length", () => { - expect(truncateTitle("abcdefghij", 5)).toBe("abcde..."); - }); -}); diff --git a/packages/contracts/src/orchestration.test.ts b/packages/contracts/src/orchestration.test.ts index 59c023e62a..06bb35038d 100644 --- a/packages/contracts/src/orchestration.test.ts +++ b/packages/contracts/src/orchestration.test.ts @@ -319,6 +319,25 @@ it.effect("accepts provider-scoped model options in thread.turn.start", () => }), ); +it.effect("accepts a title seed in thread.turn.start", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadTurnStartCommand({ + type: "thread.turn.start", + commandId: "cmd-turn-title-seed", + threadId: "thread-1", + message: { + messageId: "msg-title-seed", + role: "user", + text: "hello", + attachments: [], + }, + titleSeed: "Investigate reconnect failures", + createdAt: "2026-01-01T00:00:00.000Z", + }); + assert.strictEqual(parsed.titleSeed, "Investigate reconnect failures"); + }), +); + it.effect("accepts a source proposed plan reference in thread.turn.start", () => Effect.gen(function* () { const parsed = yield* decodeThreadTurnStartCommand({ @@ -378,6 +397,18 @@ it.effect("decodes thread.turn-start-requested source proposed plan metadata whe }), ); +it.effect("decodes thread.turn-start-requested title seed when present", () => + Effect.gen(function* () { + const parsed = yield* decodeThreadTurnStartRequestedPayload({ + threadId: "thread-2", + messageId: "msg-2", + titleSeed: "Investigate reconnect failures", + createdAt: "2026-01-01T00:00:00.000Z", + }); + assert.strictEqual(parsed.titleSeed, "Investigate reconnect failures"); + }), +); + it.effect("decodes latest turn source proposed plan metadata when present", () => Effect.gen(function* () { const parsed = yield* decodeOrchestrationLatestTurn({ diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 31631666e2..a780a55c78 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -42,6 +42,7 @@ export const ProviderSandboxMode = Schema.Literals([ "danger-full-access", ]); export type ProviderSandboxMode = typeof ProviderSandboxMode.Type; + export const DEFAULT_PROVIDER_KIND: ProviderKind = "codex"; export const CodexModelSelection = Schema.Struct({ @@ -398,6 +399,7 @@ export const ThreadTurnStartCommand = Schema.Struct({ attachments: Schema.Array(ChatAttachment), }), modelSelection: Schema.optional(ModelSelection), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)), interactionMode: ProviderInteractionMode.pipe( Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE), @@ -417,6 +419,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({ attachments: Schema.Array(UploadChatAttachment), }), modelSelection: Schema.optional(ModelSelection), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode, interactionMode: ProviderInteractionMode, sourceProposedPlan: Schema.optional(SourceProposedPlanReference), @@ -711,7 +714,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({ threadId: ThreadId, messageId: MessageId, modelSelection: Schema.optional(ModelSelection), - assistantDeliveryMode: Schema.optional(AssistantDeliveryMode), + titleSeed: Schema.optional(TrimmedNonEmptyString), runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)), interactionMode: ProviderInteractionMode.pipe( Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE), diff --git a/packages/shared/package.json b/packages/shared/package.json index d34d1ce453..40ffbf35c2 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -35,6 +35,10 @@ "./Struct": { "types": "./src/Struct.ts", "import": "./src/Struct.ts" + }, + "./String": { + "types": "./src/String.ts", + "import": "./src/String.ts" } }, "scripts": { diff --git a/packages/shared/src/String.test.ts b/packages/shared/src/String.test.ts new file mode 100644 index 0000000000..d70bfe840f --- /dev/null +++ b/packages/shared/src/String.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from "vitest"; + +import { truncate } from "./String"; + +describe("truncate", () => { + it("trims surrounding whitespace", () => { + expect(truncate(" hello world ")).toBe("hello world"); + }); + + it("returns shorter strings unchanged", () => { + expect(truncate("alpha", 10)).toBe("alpha"); + }); + + it("truncates long strings and appends an ellipsis", () => { + expect(truncate("abcdefghij", 5)).toBe("abcde..."); + }); +}); diff --git a/apps/web/src/truncateTitle.ts b/packages/shared/src/String.ts similarity index 66% rename from apps/web/src/truncateTitle.ts rename to packages/shared/src/String.ts index bce5545283..c93d0c90cb 100644 --- a/apps/web/src/truncateTitle.ts +++ b/packages/shared/src/String.ts @@ -1,7 +1,8 @@ -export function truncateTitle(text: string, maxLength = 50): string { +export function truncate(text: string, maxLength = 50): string { const trimmed = text.trim(); if (trimmed.length <= maxLength) { return trimmed; } + return `${trimmed.slice(0, maxLength)}...`; } From 58ba4f12633ef05f7a8ab707cba4cd7ccaad0d58 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Sat, 28 Mar 2026 18:23:30 -0700 Subject: [PATCH 30/66] Add keyboard shortcuts for jumping to sidebar threads (#1456) Co-authored-by: Julius Marminge --- apps/server/src/keybindings.test.ts | 13 + apps/server/src/keybindings.ts | 7 + apps/web/src/components/ChatView.tsx | 34 +- apps/web/src/components/Sidebar.logic.test.ts | 76 +++++ apps/web/src/components/Sidebar.logic.ts | 41 +++ apps/web/src/components/Sidebar.tsx | 318 ++++++++++++++---- apps/web/src/keybindings.test.ts | 127 ++++++- apps/web/src/keybindings.ts | 138 +++++++- packages/contracts/src/keybindings.test.ts | 19 +- packages/contracts/src/keybindings.ts | 21 ++ 10 files changed, 713 insertions(+), 81 deletions(-) diff --git a/apps/server/src/keybindings.test.ts b/apps/server/src/keybindings.test.ts index 846c3778b0..9cf0394142 100644 --- a/apps/server/src/keybindings.test.ts +++ b/apps/server/src/keybindings.test.ts @@ -165,6 +165,19 @@ it.layer(NodeServices.layer)("keybindings", (it) => { }).pipe(Effect.provide(makeKeybindingsLayer())), ); + it.effect("ships configurable thread navigation defaults", () => + Effect.sync(() => { + const defaultsByCommand = new Map( + DEFAULT_KEYBINDINGS.map((binding) => [binding.command, binding.key] as const), + ); + + assert.equal(defaultsByCommand.get("thread.previous"), "mod+shift+["); + assert.equal(defaultsByCommand.get("thread.next"), "mod+shift+]"); + assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1"); + assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9"); + }), + ); + it.effect("uses defaults in runtime when config is malformed without overriding file", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index 58363d2138..176e0300ad 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -15,6 +15,7 @@ import { MAX_WHEN_EXPRESSION_DEPTH, ResolvedKeybindingRule, ResolvedKeybindingsConfig, + THREAD_JUMP_KEYBINDING_COMMANDS, type ServerConfigIssue, } from "@t3tools/contracts"; import { Mutable } from "effect/Types"; @@ -76,6 +77,12 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray = [ { key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" }, { key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" }, { key: "mod+o", command: "editor.openFavorite" }, + { key: "mod+shift+[", command: "thread.previous" }, + { key: "mod+shift+]", command: "thread.next" }, + ...THREAD_JUMP_KEYBINDING_COMMANDS.map((command, index) => ({ + key: `mod+${index + 1}`, + command, + })), ]; function normalizeKeyToken(token: string): string { diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e572f3c470..fbd332354a 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -1162,25 +1162,43 @@ export default function ChatView({ threadId }: ChatViewProps) { }, [activeProjectCwd, activeThreadWorktreePath]); // Default true while loading to avoid toolbar flicker. const isGitRepo = branchesQuery.data?.isRepo ?? true; + const terminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: true, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); + const nonTerminalShortcutLabelOptions = useMemo( + () => ({ + context: { + terminalFocus: false, + terminalOpen: Boolean(terminalState.terminalOpen), + }, + }), + [terminalState.terminalOpen], + ); const terminalToggleShortcutLabel = useMemo( () => shortcutLabelForCommand(keybindings, "terminal.toggle"), [keybindings], ); const splitTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.split"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const newTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.new"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const closeTerminalShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "terminal.close"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions), + [keybindings, terminalShortcutLabelOptions], ); const diffPanelShortcutLabel = useMemo( - () => shortcutLabelForCommand(keybindings, "diff.toggle"), - [keybindings], + () => shortcutLabelForCommand(keybindings, "diff.toggle", nonTerminalShortcutLabelOptions), + [keybindings, nonTerminalShortcutLabelOptions], ); const onToggleDiff = useCallback(() => { void navigate({ diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index cc49a82e69..b54ec1cb93 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1,6 +1,8 @@ import { describe, expect, it } from "vitest"; import { + getVisibleSidebarThreadIds, + resolveAdjacentThreadId, getFallbackThreadIdAfterDelete, getVisibleThreadsForProject, getProjectSortTimestamp, @@ -97,6 +99,80 @@ describe("resolveSidebarNewThreadEnvMode", () => { }); }); +describe("resolveAdjacentThreadId", () => { + it("resolves adjacent thread ids in ordered sidebar traversal", () => { + const threads = [ + ThreadId.makeUnsafe("thread-1"), + ThreadId.makeUnsafe("thread-2"), + ThreadId.makeUnsafe("thread-3"), + ]; + + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[1] ?? null, + direction: "previous", + }), + ).toBe(threads[0]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[1] ?? null, + direction: "next", + }), + ).toBe(threads[2]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: null, + direction: "next", + }), + ).toBe(threads[0]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: null, + direction: "previous", + }), + ).toBe(threads[2]); + expect( + resolveAdjacentThreadId({ + threadIds: threads, + currentThreadId: threads[0] ?? null, + direction: "previous", + }), + ).toBeNull(); + }); +}); + +describe("getVisibleSidebarThreadIds", () => { + it("returns only the rendered visible thread order across projects", () => { + expect( + getVisibleSidebarThreadIds([ + { + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-12") }, + { id: ThreadId.makeUnsafe("thread-11") }, + { id: ThreadId.makeUnsafe("thread-10") }, + ], + }, + { + renderedThreads: [ + { id: ThreadId.makeUnsafe("thread-8") }, + { id: ThreadId.makeUnsafe("thread-6") }, + ], + }, + ]), + ).toEqual([ + ThreadId.makeUnsafe("thread-12"), + ThreadId.makeUnsafe("thread-11"), + ThreadId.makeUnsafe("thread-10"), + ThreadId.makeUnsafe("thread-8"), + ThreadId.makeUnsafe("thread-6"), + ]); + }); +}); + describe("isContextMenuPointerDown", () => { it("treats secondary-button presses as context menu gestures on all platforms", () => { expect( diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 22a6268ac7..1e0871e0d2 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -17,6 +17,8 @@ type SidebarProject = { }; type SidebarThreadSortInput = Pick; +export type ThreadTraversalDirection = "previous" | "next"; + export interface ThreadStatusPill { label: | "Working" @@ -67,6 +69,45 @@ export function resolveSidebarNewThreadEnvMode(input: { return input.requestedEnvMode ?? input.defaultEnvMode; } +export function getVisibleSidebarThreadIds( + renderedProjects: readonly { + renderedThreads: readonly { + id: TThreadId; + }[]; + }[], +): TThreadId[] { + return renderedProjects.flatMap((renderedProject) => + renderedProject.renderedThreads.map((thread) => thread.id), + ); +} + +export function resolveAdjacentThreadId(input: { + threadIds: readonly T[]; + currentThreadId: T | null; + direction: ThreadTraversalDirection; +}): T | null { + const { currentThreadId, direction, threadIds } = input; + + if (threadIds.length === 0) { + return null; + } + + if (currentThreadId === null) { + return direction === "previous" ? (threadIds.at(-1) ?? null) : (threadIds[0] ?? null); + } + + const currentIndex = threadIds.indexOf(currentThreadId); + if (currentIndex === -1) { + return null; + } + + if (direction === "previous") { + return currentIndex > 0 ? (threadIds[currentIndex - 1] ?? null) : null; + } + + return currentIndex < threadIds.length - 1 ? (threadIds[currentIndex + 1] ?? null) : null; +} + export function isContextMenuPointerDown(input: { button: number; ctrlKey: boolean; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index d6ef9fc819..89640ed5d2 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -53,9 +53,17 @@ import { } from "@t3tools/contracts/settings"; import { isElectron } from "../env"; import { APP_STAGE_LABEL, APP_VERSION } from "../branding"; +import { isTerminalFocused } from "../lib/terminalFocus"; import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils"; import { useStore } from "../store"; -import { shortcutLabelForCommand } from "../keybindings"; +import { + resolveShortcutCommand, + shortcutLabelForCommand, + shouldShowThreadJumpHints, + threadJumpCommandForIndex, + threadJumpIndexFromCommand, + threadTraversalDirectionFromCommand, +} from "../keybindings"; import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic"; import { gitStatusQueryOptions } from "../lib/gitReactQuery"; import { serverConfigQueryOptions } from "../lib/serverReactQuery"; @@ -100,7 +108,9 @@ import { import { useThreadSelectionStore } from "../threadSelectionStore"; import { isNonEmpty as isNonEmptyString } from "effect/String"; import { + getVisibleSidebarThreadIds, getVisibleThreadsForProject, + resolveAdjacentThreadId, isContextMenuPointerDown, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, @@ -353,6 +363,7 @@ export default function Sidebar() { const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState< ReadonlySet >(() => new Set()); + const [showThreadJumpHints, setShowThreadJumpHints] = useState(false); const renamingCommittedRef = useRef(false); const renamingInputRef = useRef(null); const dragInProgressRef = useRef(false); @@ -366,12 +377,26 @@ export default function Sidebar() { const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const isLinuxDesktop = isElectron && isLinuxPlatform(navigator.platform); + const platform = navigator.platform; const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop; const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately; const projectCwdById = useMemo( () => new Map(projects.map((project) => [project.id, project.cwd] as const)), [projects], ); + const routeTerminalOpen = routeThreadId + ? selectThreadTerminalState(terminalStateByThreadId, routeThreadId).terminalOpen + : false; + const sidebarShortcutLabelOptions = useMemo( + () => ({ + platform, + context: { + terminalFocus: false, + terminalOpen: routeTerminalOpen, + }, + }), + [platform, routeTerminalOpen], + ); const threadGitTargets = useMemo( () => threads.map((thread) => ({ @@ -823,6 +848,20 @@ export default function Sidebar() { ], ); + const navigateToThread = useCallback( + (threadId: ThreadId) => { + if (selectedThreadIds.size > 0) { + clearSelection(); + } + setSelectionAnchor(threadId); + void navigate({ + to: "/$threadId", + params: { threadId }, + }); + }, + [clearSelection, navigate, selectedThreadIds.size, setSelectionAnchor], + ); + const handleProjectContextMenu = useCallback( async (projectId: ProjectId, position: { x: number; y: number }) => { const api = readNativeApi(); @@ -979,45 +1018,201 @@ export default function Sidebar() { [appSettings.sidebarProjectSortOrder, projects, visibleThreads], ); const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual"; + const renderedProjects = useMemo( + () => + sortedProjects.map((project) => { + const projectThreads = sortThreadsForSidebar( + visibleThreads.filter((thread) => thread.projectId === project.id), + appSettings.sidebarThreadSortOrder, + ); + const projectStatus = resolveProjectStatusIndicator( + projectThreads.map((thread) => + resolveThreadStatusPill({ + thread, + hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, + hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, + }), + ), + ); + const activeThreadId = routeThreadId ?? undefined; + const isThreadListExpanded = expandedThreadListsByProject.has(project.id); + const pinnedCollapsedThread = + !project.expanded && activeThreadId + ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) + : null; + const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null; + const { hasHiddenThreads, visibleThreads: visibleProjectThreads } = + getVisibleThreadsForProject({ + threads: projectThreads, + activeThreadId, + isThreadListExpanded, + previewLimit: THREAD_PREVIEW_LIMIT, + }); + const orderedProjectThreadIds = projectThreads.map((thread) => thread.id); + const renderedThreads = pinnedCollapsedThread + ? [pinnedCollapsedThread] + : visibleProjectThreads; + + return { + hasHiddenThreads, + orderedProjectThreadIds, + project, + projectStatus, + projectThreads, + renderedThreads, + shouldShowThreadPanel, + isThreadListExpanded, + }; + }), + [ + appSettings.sidebarThreadSortOrder, + expandedThreadListsByProject, + routeThreadId, + sortedProjects, + visibleThreads, + ], + ); + const threadJumpCommandById = useMemo(() => { + const mapping = new Map>>(); + let visibleThreadIndex = 0; + + for (const renderedProject of renderedProjects) { + for (const thread of renderedProject.renderedThreads) { + const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex); + if (!jumpCommand) { + return mapping; + } + mapping.set(thread.id, jumpCommand); + visibleThreadIndex += 1; + } + } + + return mapping; + }, [renderedProjects]); + const threadJumpThreadIds = useMemo( + () => [...threadJumpCommandById.keys()], + [threadJumpCommandById], + ); + const threadJumpLabelById = useMemo(() => { + const mapping = new Map(); + for (const [threadId, command] of threadJumpCommandById) { + const label = shortcutLabelForCommand(keybindings, command, sidebarShortcutLabelOptions); + if (label) { + mapping.set(threadId, label); + } + } + return mapping; + }, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]); + const orderedSidebarThreadIds = useMemo( + () => getVisibleSidebarThreadIds(renderedProjects), + [renderedProjects], + ); + + useEffect(() => { + const getShortcutContext = () => ({ + terminalFocus: isTerminalFocused(), + terminalOpen: routeTerminalOpen, + }); + + const onWindowKeyDown = (event: KeyboardEvent) => { + setShowThreadJumpHints( + shouldShowThreadJumpHints(event, keybindings, { + platform, + context: getShortcutContext(), + }), + ); + + if (event.defaultPrevented || event.repeat) { + return; + } + + const command = resolveShortcutCommand(event, keybindings, { + platform, + context: getShortcutContext(), + }); + const traversalDirection = threadTraversalDirectionFromCommand(command); + if (traversalDirection !== null) { + const targetThreadId = resolveAdjacentThreadId({ + threadIds: orderedSidebarThreadIds, + currentThreadId: routeThreadId, + direction: traversalDirection, + }); + if (!targetThreadId) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + navigateToThread(targetThreadId); + return; + } + + const jumpIndex = threadJumpIndexFromCommand(command ?? ""); + if (jumpIndex === null) { + return; + } + + const targetThreadId = threadJumpThreadIds[jumpIndex]; + if (!targetThreadId) { + return; + } + + event.preventDefault(); + event.stopPropagation(); + navigateToThread(targetThreadId); + }; + + const onWindowKeyUp = (event: KeyboardEvent) => { + setShowThreadJumpHints( + shouldShowThreadJumpHints(event, keybindings, { + platform, + context: getShortcutContext(), + }), + ); + }; + + const onWindowBlur = () => { + setShowThreadJumpHints(false); + }; + + window.addEventListener("keydown", onWindowKeyDown); + window.addEventListener("keyup", onWindowKeyUp); + window.addEventListener("blur", onWindowBlur); + + return () => { + window.removeEventListener("keydown", onWindowKeyDown); + window.removeEventListener("keyup", onWindowKeyUp); + window.removeEventListener("blur", onWindowBlur); + }; + }, [ + keybindings, + navigateToThread, + orderedSidebarThreadIds, + platform, + routeTerminalOpen, + routeThreadId, + threadJumpThreadIds, + ]); function renderProjectItem( - project: (typeof sortedProjects)[number], + renderedProject: (typeof renderedProjects)[number], dragHandleProps: SortableProjectHandleProps | null, ) { - const projectThreads = sortThreadsForSidebar( - visibleThreads.filter((thread) => thread.projectId === project.id), - appSettings.sidebarThreadSortOrder, - ); - const projectStatus = resolveProjectStatusIndicator( - projectThreads.map((thread) => - resolveThreadStatusPill({ - thread, - hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, - hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, - }), - ), - ); - const activeThreadId = routeThreadId ?? undefined; - const isThreadListExpanded = expandedThreadListsByProject.has(project.id); - const pinnedCollapsedThread = - !project.expanded && activeThreadId - ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) - : null; - const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null; - const { hasHiddenThreads, visibleThreads: visibleProjectThreads } = getVisibleThreadsForProject( - { - threads: projectThreads, - activeThreadId, - isThreadListExpanded, - previewLimit: THREAD_PREVIEW_LIMIT, - }, - ); - const orderedProjectThreadIds = projectThreads.map((thread) => thread.id); - const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleProjectThreads; + const { + hasHiddenThreads, + orderedProjectThreadIds, + project, + projectStatus, + projectThreads, + renderedThreads, + shouldShowThreadPanel, + isThreadListExpanded, + } = renderedProject; const renderThreadRow = (thread: (typeof projectThreads)[number]) => { const isActive = routeThreadId === thread.id; const isSelected = selectedThreadIds.has(thread.id); const isHighlighted = isActive || isSelected; + const jumpLabel = threadJumpLabelById.get(thread.id) ?? null; const isThreadRunning = thread.session?.status === "running" && thread.session.activeTurnId != null; const threadStatus = resolveThreadStatusPill({ @@ -1057,14 +1252,7 @@ export default function Sidebar() { onKeyDown={(event) => { if (event.key !== "Enter" && event.key !== " ") return; event.preventDefault(); - if (selectedThreadIds.size > 0) { - clearSelection(); - } - setSelectionAnchor(thread.id); - void navigate({ - to: "/$threadId", - params: { threadId: thread.id }, - }); + navigateToThread(thread.id); }} onContextMenu={(event) => { event.preventDefault(); @@ -1234,15 +1422,26 @@ export default function Sidebar() { ) ) : ( - - {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} - + <> + {showThreadJumpHints && jumpLabel ? ( + + {jumpLabel} + + ) : ( + + {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} + + )} + )}
@@ -1490,8 +1689,8 @@ export default function Sidebar() { ? "text-rose-500 animate-pulse" : "text-amber-500 animate-pulse"; const newThreadShortcutLabel = - shortcutLabelForCommand(keybindings, "chat.newLocal") ?? - shortcutLabelForCommand(keybindings, "chat.new"); + shortcutLabelForCommand(keybindings, "chat.newLocal", sidebarShortcutLabelOptions) ?? + shortcutLabelForCommand(keybindings, "chat.new", sidebarShortcutLabelOptions); const handleDesktopUpdateButtonClick = useCallback(() => { const bridge = window.desktopBridge; @@ -1773,12 +1972,15 @@ export default function Sidebar() { > project.id)} + items={renderedProjects.map((renderedProject) => renderedProject.project.id)} strategy={verticalListSortingStrategy} > - {sortedProjects.map((project) => ( - - {(dragHandleProps) => renderProjectItem(project, dragHandleProps)} + {renderedProjects.map((renderedProject) => ( + + {(dragHandleProps) => renderProjectItem(renderedProject, dragHandleProps)} ))} @@ -1786,9 +1988,9 @@ export default function Sidebar() { ) : ( - {sortedProjects.map((project) => ( - - {renderProjectItem(project, null)} + {renderedProjects.map((renderedProject) => ( + + {renderProjectItem(renderedProject, null)} ))} diff --git a/apps/web/src/keybindings.test.ts b/apps/web/src/keybindings.test.ts index 0ecccf43f8..eba0bd3b46 100644 --- a/apps/web/src/keybindings.test.ts +++ b/apps/web/src/keybindings.test.ts @@ -18,8 +18,12 @@ import { isTerminalSplitShortcut, isTerminalToggleShortcut, resolveShortcutCommand, + shouldShowThreadJumpHints, shortcutLabelForCommand, terminalNavigationShortcutData, + threadJumpCommandForIndex, + threadJumpIndexFromCommand, + threadTraversalDirectionFromCommand, type ShortcutEventLike, } from "./keybindings"; @@ -100,6 +104,11 @@ const DEFAULT_BINDINGS = compile([ { shortcut: modShortcut("o", { shiftKey: true }), command: "chat.new" }, { shortcut: modShortcut("n", { shiftKey: true }), command: "chat.newLocal" }, { shortcut: modShortcut("o"), command: "editor.openFavorite" }, + { shortcut: modShortcut("[", { shiftKey: true }), command: "thread.previous" }, + { shortcut: modShortcut("]", { shiftKey: true }), command: "thread.next" }, + { shortcut: modShortcut("1"), command: "thread.jump.1" }, + { shortcut: modShortcut("2"), command: "thread.jump.2" }, + { shortcut: modShortcut("3"), command: "thread.jump.3" }, ]); describe("isTerminalToggleShortcut", () => { @@ -215,7 +224,7 @@ describe("split/new/close terminal shortcuts", () => { }); describe("shortcutLabelForCommand", () => { - it("returns the most recent binding label", () => { + it("returns the effective binding label", () => { const bindings = compile([ { shortcut: modShortcut("\\"), @@ -229,18 +238,107 @@ describe("shortcutLabelForCommand", () => { }, ]); assert.strictEqual( - shortcutLabelForCommand(bindings, "terminal.split", "Linux"), + shortcutLabelForCommand(bindings, "terminal.split", { + platform: "Linux", + context: { terminalFocus: false }, + }), "Ctrl+Shift+\\", ); }); - it("returns labels for non-terminal commands", () => { + it("returns effective labels for non-terminal commands", () => { assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "chat.new", "MacIntel"), "⇧⌘O"); assert.strictEqual(shortcutLabelForCommand(DEFAULT_BINDINGS, "diff.toggle", "Linux"), "Ctrl+D"); assert.strictEqual( shortcutLabelForCommand(DEFAULT_BINDINGS, "editor.openFavorite", "Linux"), "Ctrl+O", ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_BINDINGS, "thread.jump.3", "MacIntel"), + "⌘3", + ); + assert.strictEqual( + shortcutLabelForCommand(DEFAULT_BINDINGS, "thread.previous", "Linux"), + "Ctrl+Shift+[", + ); + }); + + it("returns null for commands shadowed by a later conflicting shortcut", () => { + const bindings = compile([ + { shortcut: modShortcut("1", { shiftKey: true }), command: "thread.jump.1" }, + { shortcut: modShortcut("1", { shiftKey: true }), command: "thread.jump.7" }, + ]); + + assert.isNull(shortcutLabelForCommand(bindings, "thread.jump.1", "MacIntel")); + assert.strictEqual(shortcutLabelForCommand(bindings, "thread.jump.7", "MacIntel"), "⇧⌘1"); + }); + + it("respects when-context while resolving labels", () => { + const bindings = compile([ + { shortcut: modShortcut("d"), command: "diff.toggle" }, + { + shortcut: modShortcut("d"), + command: "terminal.split", + whenAst: whenIdentifier("terminalFocus"), + }, + ]); + + assert.strictEqual( + shortcutLabelForCommand(bindings, "diff.toggle", { + platform: "Linux", + context: { terminalFocus: false }, + }), + "Ctrl+D", + ); + assert.isNull( + shortcutLabelForCommand(bindings, "diff.toggle", { + platform: "Linux", + context: { terminalFocus: true }, + }), + ); + assert.strictEqual( + shortcutLabelForCommand(bindings, "terminal.split", { + platform: "Linux", + context: { terminalFocus: true }, + }), + "Ctrl+D", + ); + }); +}); + +describe("thread navigation helpers", () => { + it("maps jump commands to visible thread indices", () => { + assert.strictEqual(threadJumpCommandForIndex(0), "thread.jump.1"); + assert.strictEqual(threadJumpCommandForIndex(2), "thread.jump.3"); + assert.isNull(threadJumpCommandForIndex(9)); + assert.strictEqual(threadJumpIndexFromCommand("thread.jump.1"), 0); + assert.strictEqual(threadJumpIndexFromCommand("thread.jump.3"), 2); + assert.isNull(threadJumpIndexFromCommand("thread.next")); + }); + + it("maps traversal commands to directions", () => { + assert.strictEqual(threadTraversalDirectionFromCommand("thread.previous"), "previous"); + assert.strictEqual(threadTraversalDirectionFromCommand("thread.next"), "next"); + assert.isNull(threadTraversalDirectionFromCommand("thread.jump.1")); + assert.isNull(threadTraversalDirectionFromCommand(null)); + }); + + it("shows jump hints only when configured modifiers match", () => { + assert.isTrue( + shouldShowThreadJumpHints(event({ metaKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + }), + ); + assert.isFalse( + shouldShowThreadJumpHints(event({ metaKey: true, shiftKey: true }), DEFAULT_BINDINGS, { + platform: "MacIntel", + }), + ); + assert.isTrue( + shouldShowThreadJumpHints(event({ ctrlKey: true }), DEFAULT_BINDINGS, { + platform: "Linux", + }), + ); }); }); @@ -373,6 +471,29 @@ describe("resolveShortcutCommand", () => { "script.setup.run", ); }); + + it("matches bracket shortcuts using the physical key code", () => { + assert.strictEqual( + resolveShortcutCommand( + event({ key: "{", code: "BracketLeft", metaKey: true, shiftKey: true }), + DEFAULT_BINDINGS, + { + platform: "MacIntel", + }, + ), + "thread.previous", + ); + assert.strictEqual( + resolveShortcutCommand( + event({ key: "}", code: "BracketRight", ctrlKey: true, shiftKey: true }), + DEFAULT_BINDINGS, + { + platform: "Linux", + }, + ), + "thread.next", + ); + }); }); describe("formatShortcutLabel", () => { diff --git a/apps/web/src/keybindings.ts b/apps/web/src/keybindings.ts index 09d9308aad..286454dc05 100644 --- a/apps/web/src/keybindings.ts +++ b/apps/web/src/keybindings.ts @@ -3,11 +3,14 @@ import { type KeybindingShortcut, type KeybindingWhenNode, type ResolvedKeybindingsConfig, + THREAD_JUMP_KEYBINDING_COMMANDS, + type ThreadJumpKeybindingCommand, } from "@t3tools/contracts"; import { isMacPlatform } from "./lib/utils"; export interface ShortcutEventLike { type?: string; + code?: string; key: string; metaKey: boolean; ctrlKey: boolean; @@ -26,10 +29,28 @@ interface ShortcutMatchOptions { context?: Partial; } +interface ResolvedShortcutLabelOptions extends ShortcutMatchOptions { + platform?: string; +} + const TERMINAL_WORD_BACKWARD = "\u001bb"; const TERMINAL_WORD_FORWARD = "\u001bf"; const TERMINAL_LINE_START = "\u0001"; const TERMINAL_LINE_END = "\u0005"; +const EVENT_CODE_KEY_ALIASES: Readonly> = { + BracketLeft: ["["], + BracketRight: ["]"], + Digit0: ["0"], + Digit1: ["1"], + Digit2: ["2"], + Digit3: ["3"], + Digit4: ["4"], + Digit5: ["5"], + Digit6: ["6"], + Digit7: ["7"], + Digit8: ["8"], + Digit9: ["9"], +}; function normalizeEventKey(key: string): string { const normalized = key.toLowerCase(); @@ -37,14 +58,22 @@ function normalizeEventKey(key: string): string { return normalized; } -function matchesShortcut( +function resolveEventKeys(event: ShortcutEventLike): Set { + const keys = new Set([normalizeEventKey(event.key)]); + const aliases = event.code ? EVENT_CODE_KEY_ALIASES[event.code] : undefined; + if (!aliases) return keys; + + for (const alias of aliases) { + keys.add(alias); + } + return keys; +} + +function matchesShortcutModifiers( event: ShortcutEventLike, shortcut: KeybindingShortcut, platform = navigator.platform, ): boolean { - const key = normalizeEventKey(event.key); - if (key !== shortcut.key) return false; - const useMetaForMod = isMacPlatform(platform); const expectedMeta = shortcut.metaKey || (shortcut.modKey && useMetaForMod); const expectedCtrl = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod); @@ -56,6 +85,15 @@ function matchesShortcut( ); } +function matchesShortcut( + event: ShortcutEventLike, + shortcut: KeybindingShortcut, + platform = navigator.platform, +): boolean { + if (!matchesShortcutModifiers(event, shortcut, platform)) return false; + return resolveEventKeys(event).has(shortcut.key); +} + function resolvePlatform(options: ShortcutMatchOptions | undefined): string { return options?.platform ?? navigator.platform; } @@ -91,6 +129,48 @@ function matchesWhenClause( return evaluateWhenNode(whenAst, context); } +function shortcutConflictKey(shortcut: KeybindingShortcut, platform = navigator.platform): string { + const useMetaForMod = isMacPlatform(platform); + const metaKey = shortcut.metaKey || (shortcut.modKey && useMetaForMod); + const ctrlKey = shortcut.ctrlKey || (shortcut.modKey && !useMetaForMod); + + return [ + shortcut.key, + metaKey ? "meta" : "", + ctrlKey ? "ctrl" : "", + shortcut.shiftKey ? "shift" : "", + shortcut.altKey ? "alt" : "", + ].join("|"); +} + +function findEffectiveShortcutForCommand( + keybindings: ResolvedKeybindingsConfig, + command: KeybindingCommand, + options?: ShortcutMatchOptions, +): KeybindingShortcut | null { + const platform = resolvePlatform(options); + const context = resolveContext(options); + const claimedShortcuts = new Set(); + + for (let index = keybindings.length - 1; index >= 0; index -= 1) { + const binding = keybindings[index]; + if (!binding) continue; + if (!matchesWhenClause(binding.whenAst, context)) continue; + + const conflictKey = shortcutConflictKey(binding.shortcut, platform); + if (claimedShortcuts.has(conflictKey)) { + continue; + } + + claimedShortcuts.add(conflictKey); + if (binding.command === command) { + return binding.shortcut; + } + } + + return null; +} + function matchesCommandShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, @@ -104,7 +184,7 @@ export function resolveShortcutCommand( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, options?: ShortcutMatchOptions, -): string | null { +): KeybindingCommand | null { const platform = resolvePlatform(options); const context = resolveContext(options); @@ -156,16 +236,52 @@ export function formatShortcutLabel( export function shortcutLabelForCommand( keybindings: ResolvedKeybindingsConfig, command: KeybindingCommand, - platform = navigator.platform, + options?: string | ResolvedShortcutLabelOptions, ): string | null { - for (let index = keybindings.length - 1; index >= 0; index -= 1) { - const binding = keybindings[index]; - if (!binding || binding.command !== command) continue; - return formatShortcutLabel(binding.shortcut, platform); - } + const resolvedOptions = + typeof options === "string" + ? ({ platform: options } satisfies ResolvedShortcutLabelOptions) + : options; + const platform = resolvePlatform(resolvedOptions); + const shortcut = findEffectiveShortcutForCommand(keybindings, command, resolvedOptions); + return shortcut ? formatShortcutLabel(shortcut, platform) : null; +} + +export function threadJumpCommandForIndex(index: number): ThreadJumpKeybindingCommand | null { + return THREAD_JUMP_KEYBINDING_COMMANDS[index] ?? null; +} + +export function threadJumpIndexFromCommand(command: string): number | null { + const index = THREAD_JUMP_KEYBINDING_COMMANDS.indexOf(command as ThreadJumpKeybindingCommand); + return index === -1 ? null : index; +} + +export function threadTraversalDirectionFromCommand( + command: string | null, +): "previous" | "next" | null { + if (command === "thread.previous") return "previous"; + if (command === "thread.next") return "next"; return null; } +export function shouldShowThreadJumpHints( + event: ShortcutEventLike, + keybindings: ResolvedKeybindingsConfig, + options?: ShortcutMatchOptions, +): boolean { + const platform = resolvePlatform(options); + + for (const command of THREAD_JUMP_KEYBINDING_COMMANDS) { + const shortcut = findEffectiveShortcutForCommand(keybindings, command, options); + if (!shortcut) continue; + if (matchesShortcutModifiers(event, shortcut, platform)) { + return true; + } + } + + return false; +} + export function isTerminalToggleShortcut( event: ShortcutEventLike, keybindings: ResolvedKeybindingsConfig, diff --git a/packages/contracts/src/keybindings.test.ts b/packages/contracts/src/keybindings.test.ts index 1b99362c53..c3a7d9f00e 100644 --- a/packages/contracts/src/keybindings.test.ts +++ b/packages/contracts/src/keybindings.test.ts @@ -46,6 +46,12 @@ it.effect("parses keybinding rules", () => command: "chat.newLocal", }); assert.strictEqual(parsedLocal.command, "chat.newLocal"); + + const parsedThreadPrevious = yield* decode(KeybindingRule, { + key: "mod+shift+[", + command: "thread.previous", + }); + assert.strictEqual(parsedThreadPrevious.command, "thread.previous"); }), ); @@ -120,8 +126,19 @@ it.effect("parses resolved keybindings arrays", () => modKey: true, }, }, + { + command: "thread.jump.3", + shortcut: { + key: "3", + metaKey: false, + ctrlKey: false, + shiftKey: false, + altKey: false, + modKey: true, + }, + }, ]); - assert.lengthOf(parsed, 1); + assert.lengthOf(parsed, 2); }), ); diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 48821b1824..067cba8804 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -7,6 +7,26 @@ export const MAX_WHEN_EXPRESSION_DEPTH = 64; export const MAX_SCRIPT_ID_LENGTH = 24; export const MAX_KEYBINDINGS_COUNT = 256; +export const THREAD_JUMP_KEYBINDING_COMMANDS = [ + "thread.jump.1", + "thread.jump.2", + "thread.jump.3", + "thread.jump.4", + "thread.jump.5", + "thread.jump.6", + "thread.jump.7", + "thread.jump.8", + "thread.jump.9", +] as const; +export type ThreadJumpKeybindingCommand = (typeof THREAD_JUMP_KEYBINDING_COMMANDS)[number]; + +export const THREAD_KEYBINDING_COMMANDS = [ + "thread.previous", + "thread.next", + ...THREAD_JUMP_KEYBINDING_COMMANDS, +] as const; +export type ThreadKeybindingCommand = (typeof THREAD_KEYBINDING_COMMANDS)[number]; + const STATIC_KEYBINDING_COMMANDS = [ "terminal.toggle", "terminal.split", @@ -16,6 +36,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "chat.new", "chat.newLocal", "editor.openFavorite", + ...THREAD_KEYBINDING_COMMANDS, ] as const; export const SCRIPT_RUN_COMMAND_PATTERN = Schema.TemplateLiteral([ From afc807ac3f8cc827d5f30f587a599dd077f244ff Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 18:28:52 -0700 Subject: [PATCH 31/66] Add new GitHub users to VOUCHED.td (#1508) --- .github/VOUCHED.td | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td index 72f270dca3..5535d54a5b 100644 --- a/.github/VOUCHED.td +++ b/.github/VOUCHED.td @@ -28,4 +28,5 @@ github:realAhmedRoach github:shiroyasha9 github:Yash-Singh1 github:eggfriedrice24 -github:Ymit24 \ No newline at end of file +github:Ymit24 +github:shivamhwp From 9e60597174dcd69ae405d3966a374213c745388a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 20:50:23 -0700 Subject: [PATCH 32/66] Truncate oversized git diffs instead of failing (#1499) --- .../Layers/CheckpointStore.test.ts | 122 ++++++++++++++++++ apps/server/src/git/Layers/GitCore.test.ts | 40 ++++++ apps/server/src/git/Layers/GitCore.ts | 95 +++++++++++--- apps/server/src/git/Services/GitCore.ts | 1 + 4 files changed, 239 insertions(+), 19 deletions(-) create mode 100644 apps/server/src/checkpointing/Layers/CheckpointStore.test.ts diff --git a/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts new file mode 100644 index 0000000000..c430dbbde0 --- /dev/null +++ b/apps/server/src/checkpointing/Layers/CheckpointStore.test.ts @@ -0,0 +1,122 @@ +import path from "node:path"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it } from "@effect/vitest"; +import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect"; +import { describe, expect } from "vitest"; + +import { checkpointRefForThreadTurn } from "../Utils.ts"; +import { CheckpointStoreLive } from "./CheckpointStore.ts"; +import { CheckpointStore } from "../Services/CheckpointStore.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { GitCommandError } from "../../git/Errors.ts"; +import { ServerConfig } from "../../config.ts"; +import { ThreadId } from "@t3tools/contracts"; + +const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), { + prefix: "t3-checkpoint-store-test-", +}); +const GitCoreTestLayer = GitCoreLive.pipe( + Layer.provide(ServerConfigLayer), + Layer.provide(NodeServices.layer), +); +const CheckpointStoreTestLayer = CheckpointStoreLive.pipe( + Layer.provide(GitCoreTestLayer), + Layer.provide(NodeServices.layer), +); +const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer); + +function makeTmpDir( + prefix = "checkpoint-store-test-", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ prefix }); + }); +} + +function writeTextFile( + filePath: string, + contents: string, +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + yield* fileSystem.writeFileString(filePath, contents); + }); +} + +function git( + cwd: string, + args: ReadonlyArray, +): Effect.Effect { + return Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "CheckpointStore.test.git", + cwd, + args, + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); +} + +function initRepoWithCommit( + cwd: string, +): Effect.Effect< + void, + GitCommandError | PlatformError.PlatformError, + GitCore | FileSystem.FileSystem +> { + return Effect.gen(function* () { + const core = yield* GitCore; + yield* core.initRepo({ cwd }); + yield* git(cwd, ["config", "user.email", "test@test.com"]); + yield* git(cwd, ["config", "user.name", "Test"]); + yield* writeTextFile(path.join(cwd, "README.md"), "# test\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "initial commit"]); + }); +} + +function buildLargeText(lineCount = 20_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .concat("\n"); +} + +it.layer(TestLayer)("CheckpointStoreLive", (it) => { + describe("diffCheckpoints", () => { + it.effect("returns full oversized checkpoint diffs without truncation", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const checkpointStore = yield* CheckpointStore; + const threadId = ThreadId.makeUnsafe("thread-checkpoint-store"); + const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0); + const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1); + + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: fromCheckpointRef, + }); + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + yield* checkpointStore.captureCheckpoint({ + cwd: tmp, + checkpointRef: toCheckpointRef, + }); + + const diff = yield* checkpointStore.diffCheckpoints({ + cwd: tmp, + fromCheckpointRef, + toCheckpointRef, + }); + + expect(diff).toContain("diff --git"); + expect(diff).not.toContain("[truncated]"); + expect(diff).toContain("+line 19999"); + }), + ); + }); +}); diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index dc97b93649..547a69e7e1 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -132,6 +132,12 @@ function commitWithDate( }); } +function buildLargeText(lineCount = 20_000): string { + return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`) + .join("\n") + .concat("\n"); +} + // ── Tests ── it.layer(TestLayer)("git integration", (it) => { @@ -1670,6 +1676,40 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("prepareCommitContext truncates oversized staged patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText()); + + const context = yield* core.prepareCommitContext(tmp); + expect(context).not.toBeNull(); + expect(context!.stagedSummary).toContain("README.md"); + expect(context!.stagedPatch).toContain("[truncated]"); + }), + ); + + it.effect("readRangeContext truncates oversized diff patches instead of failing", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const core = yield* GitCore; + + yield* core.createBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* core.checkoutBranch({ cwd: tmp, branch: "feature/large-range-context" }); + yield* writeTextFile(path.join(tmp, "large.txt"), buildLargeText()); + yield* git(tmp, ["add", "large.txt"]); + yield* git(tmp, ["commit", "-m", "Add large range context"]); + + const rangeContext = yield* core.readRangeContext(tmp, initialBranch); + expect(rangeContext.commitSummary).toContain("Add large range context"); + expect(rangeContext.diffSummary).toContain("large.txt"); + expect(rangeContext.diffPatch).toContain("[truncated]"); + }), + ); + it.effect("pushes with upstream setup and then skips when up to date", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 8bb5844228..fcb2f9c58e 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -32,6 +32,11 @@ import { decodeJsonResult } from "@t3tools/shared/schemaJson"; const DEFAULT_TIMEOUT_MS = 30_000; const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000; +const OUTPUT_TRUNCATED_MARKER = "\n\n[truncated]"; +const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; +const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; +const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; +const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; @@ -53,6 +58,8 @@ interface ExecuteGitOptions { timeoutMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorMessage?: string | undefined; + maxOutputBytes?: number | undefined; + truncateOutputAtMaxBytes?: boolean | undefined; progress?: ExecuteGitProgress | undefined; } @@ -439,12 +446,14 @@ const collectOutput = Effect.fn(function* ( input: Pick, stream: Stream.Stream, maxOutputBytes: number, + truncateOutputAtMaxBytes: boolean, onLine: ((line: string) => Effect.Effect) | undefined, ): Effect.fn.Return { const decoder = new TextDecoder(); let bytes = 0; let text = ""; let lineBuffer = ""; + let truncated = false; const emitCompleteLines = (flush: boolean) => Effect.gen(function* () { @@ -469,8 +478,11 @@ const collectOutput = Effect.fn(function* ( yield* Stream.runForEach(stream, (chunk) => Effect.gen(function* () { - bytes += chunk.byteLength; - if (bytes > maxOutputBytes) { + if (truncateOutputAtMaxBytes && truncated) { + return; + } + const nextBytes = bytes + chunk.byteLength; + if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { return yield* new GitCommandError({ operation: input.operation, command: quoteGitCommand(input.args), @@ -478,18 +490,26 @@ const collectOutput = Effect.fn(function* ( detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, }); } - const decoded = decoder.decode(chunk, { stream: true }); + + const chunkToDecode = + truncateOutputAtMaxBytes && nextBytes > maxOutputBytes + ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) + : chunk; + bytes += chunkToDecode.byteLength; + truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; + + const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); text += decoded; lineBuffer += decoded; yield* emitCompleteLines(false); }), ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed."))); - const remainder = decoder.decode(); + const remainder = truncated ? "" : decoder.decode(); text += remainder; lineBuffer += remainder; yield* emitCompleteLines(true); - return text; + return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text; }); export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"] }) => @@ -511,6 +531,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" } as const; const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; const commandEffect = Effect.gen(function* () { const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( @@ -537,12 +558,14 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" commandInput, child.stdout, maxOutputBytes, + truncateOutputAtMaxBytes, input.progress?.onStdoutLine, ), collectOutput( commandInput, child.stderr, maxOutputBytes, + truncateOutputAtMaxBytes, input.progress?.onStderrLine, ), child.exitCode.pipe( @@ -603,6 +626,10 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" args, allowNonZeroExit: true, ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), + ...(options.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } + : {}), ...(options.progress ? { progress: options.progress } : {}), }).pipe( Effect.flatMap((result) => { @@ -647,6 +674,14 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" Effect.map((result) => result.stdout), ); + const runGitStdoutWithOptions = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); + const branchExists = (cwd: string, branch: string): Effect.Effect => executeGit( "GitCore.branchExists", @@ -1162,12 +1197,15 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" return null; } - const stagedPatch = yield* runGitStdout("GitCore.prepareCommitContext.stagedPatch", cwd, [ - "diff", - "--cached", - "--patch", - "--minimal", - ]); + const stagedPatch = yield* runGitStdoutWithOptions( + "GitCore.prepareCommitContext.stagedPatch", + cwd, + ["diff", "--cached", "--patch", "--minimal"], + { + maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); return { stagedSummary, @@ -1363,14 +1401,33 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute" const range = `${baseBranch}..HEAD`; const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( [ - runGitStdout("GitCore.readRangeContext.log", cwd, ["log", "--oneline", range]), - runGitStdout("GitCore.readRangeContext.diffStat", cwd, ["diff", "--stat", range]), - runGitStdout("GitCore.readRangeContext.diffPatch", cwd, [ - "diff", - "--patch", - "--minimal", - range, - ]), + runGitStdoutWithOptions( + "GitCore.readRangeContext.log", + cwd, + ["log", "--oneline", range], + { + maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffStat", + cwd, + ["diff", "--stat", range], + { + maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffPatch", + cwd, + ["diff", "--patch", "--minimal", range], + { + maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), ], { concurrency: "unbounded" }, ); diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index b74c526897..f1a4e065cd 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -32,6 +32,7 @@ export interface ExecuteGitInput { readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; readonly maxOutputBytes?: number; + readonly truncateOutputAtMaxBytes?: boolean; readonly progress?: ExecuteGitProgress; } From f82bae16680206e4be20baf3d835941aa68611cf Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Sun, 29 Mar 2026 09:53:10 +0530 Subject: [PATCH 33/66] Update system overhaul (#1505) Co-authored-by: Jono Kemball Co-authored-by: Ariaj Sarkar Co-authored-by: Julius Marminge Co-authored-by: codex --- apps/desktop/src/main.ts | 25 ++- apps/desktop/src/preload.ts | 2 + apps/web/src/components/Sidebar.tsx | 55 +----- .../components/desktopUpdate.logic.test.ts | 115 ++++++++++-- .../web/src/components/desktopUpdate.logic.ts | 28 ++- .../components/settings/SettingsPanels.tsx | 158 +++++++++++++++- .../settings/SettingsSidebarNav.tsx | 2 +- .../components/sidebar/SidebarUpdatePill.tsx | 176 ++++++++++++++++++ .../src/lib/desktopUpdateReactQuery.test.ts | 49 +++++ apps/web/src/lib/desktopUpdateReactQuery.ts | 42 +++++ packages/contracts/src/ipc.ts | 6 + 11 files changed, 575 insertions(+), 83 deletions(-) create mode 100644 apps/web/src/components/sidebar/SidebarUpdatePill.tsx create mode 100644 apps/web/src/lib/desktopUpdateReactQuery.test.ts create mode 100644 apps/web/src/lib/desktopUpdateReactQuery.ts diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 81a02d446c..f1086e9c29 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -20,6 +20,7 @@ import * as Effect from "effect/Effect"; import type { DesktopTheme, DesktopUpdateActionResult, + DesktopUpdateCheckResult, DesktopUpdateState, } from "@t3tools/contracts"; import { autoUpdater } from "electron-updater"; @@ -56,6 +57,7 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state"; const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3"); const STATE_DIR = Path.join(BASE_DIR, "userdata"); @@ -756,13 +758,13 @@ function shouldEnableAutoUpdates(): boolean { ); } -async function checkForUpdates(reason: string): Promise { - if (isQuitting || !updaterConfigured || updateCheckInFlight) return; +async function checkForUpdates(reason: string): Promise { + if (isQuitting || !updaterConfigured || updateCheckInFlight) return false; if (updateState.status === "downloading" || updateState.status === "downloaded") { console.info( `[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`, ); - return; + return false; } updateCheckInFlight = true; setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString())); @@ -770,12 +772,14 @@ async function checkForUpdates(reason: string): Promise { try { await autoUpdater.checkForUpdates(); + return true; } catch (error: unknown) { const message = error instanceof Error ? error.message : String(error); setUpdateState( reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()), ); console.error(`[desktop-updater] Failed to check for updates: ${message}`); + return true; } finally { updateCheckInFlight = false; } @@ -1263,6 +1267,21 @@ function registerIpcHandlers(): void { state: updateState, } satisfies DesktopUpdateActionResult; }); + + ipcMain.removeHandler(UPDATE_CHECK_CHANNEL); + ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => { + if (!updaterConfigured) { + return { + checked: false, + state: updateState, + } satisfies DesktopUpdateCheckResult; + } + const checked = await checkForUpdates("web-ui"); + return { + checked, + state: updateState, + } satisfies DesktopUpdateCheckResult; + }); } function getIconOption(): { icon: string } | Record { diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 2fb7e3a1db..3d59db1714 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -9,6 +9,7 @@ const OPEN_EXTERNAL_CHANNEL = "desktop:open-external"; const MENU_ACTION_CHANNEL = "desktop:menu-action"; const UPDATE_STATE_CHANNEL = "desktop:update-state"; const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state"; +const UPDATE_CHECK_CHANNEL = "desktop:update-check"; const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download"; const UPDATE_INSTALL_CHANNEL = "desktop:update-install"; const GET_WS_URL_CHANNEL = "desktop:get-ws-url"; @@ -35,6 +36,7 @@ contextBridge.exposeInMainWorld("desktopBridge", { }; }, getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL), + checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL), downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL), installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL), onUpdateState: (listener) => { diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 89640ed5d2..100d0e3f47 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -5,7 +5,6 @@ import { FolderIcon, GitPullRequestIcon, PlusIcon, - RocketIcon, SettingsIcon, SquarePenIcon, TerminalIcon, @@ -78,12 +77,10 @@ import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; import { getArm64IntelBuildWarningDescription, getDesktopUpdateActionError, - getDesktopUpdateButtonTooltip, + getDesktopUpdateInstallConfirmationMessage, isDesktopUpdateButtonDisabled, resolveDesktopUpdateButtonAction, shouldShowArm64IntelBuildWarning, - shouldHighlightDesktopUpdateError, - shouldShowDesktopUpdateButton, shouldToastDesktopUpdateActionResult, } from "./desktopUpdate.logic"; import { Alert, AlertAction, AlertDescription, AlertTitle } from "./ui/alert"; @@ -120,6 +117,7 @@ import { sortProjectsForSidebar, sortThreadsForSidebar, } from "./Sidebar.logic"; +import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; @@ -1661,12 +1659,6 @@ export default function Sidebar() { }; }, []); - const showDesktopUpdateButton = isElectron && shouldShowDesktopUpdateButton(desktopUpdateState); - - const desktopUpdateTooltip = desktopUpdateState - ? getDesktopUpdateButtonTooltip(desktopUpdateState) - : "Update available"; - const desktopUpdateButtonDisabled = isDesktopUpdateButtonDisabled(desktopUpdateState); const desktopUpdateButtonAction = desktopUpdateState ? resolveDesktopUpdateButtonAction(desktopUpdateState) @@ -1677,17 +1669,6 @@ export default function Sidebar() { desktopUpdateState && showArm64IntelBuildWarning ? getArm64IntelBuildWarningDescription(desktopUpdateState) : null; - const desktopUpdateButtonInteractivityClasses = desktopUpdateButtonDisabled - ? "cursor-not-allowed opacity-60" - : "hover:bg-accent hover:text-foreground"; - const desktopUpdateButtonClasses = - desktopUpdateState?.status === "downloaded" - ? "text-emerald-500" - : desktopUpdateState?.status === "downloading" - ? "text-sky-400" - : shouldHighlightDesktopUpdateError(desktopUpdateState) - ? "text-rose-500 animate-pulse" - : "text-amber-500 animate-pulse"; const newThreadShortcutLabel = shortcutLabelForCommand(keybindings, "chat.newLocal", sidebarShortcutLabelOptions) ?? shortcutLabelForCommand(keybindings, "chat.new", sidebarShortcutLabelOptions); @@ -1728,6 +1709,10 @@ export default function Sidebar() { } if (desktopUpdateButtonAction === "install") { + const confirmed = window.confirm( + getDesktopUpdateInstallConfirmationMessage(desktopUpdateState), + ); + if (!confirmed) return; void bridge .installUpdate() .then((result) => { @@ -1795,30 +1780,9 @@ export default function Sidebar() { return ( <> {isElectron ? ( - <> - - {wordmark} - {showDesktopUpdateButton && ( - - - - - } - /> - {desktopUpdateTooltip} - - )} - - + + {wordmark} + ) : ( {wordmark} @@ -2006,6 +1970,7 @@ export default function Sidebar() { + { expect(getDesktopUpdateButtonTooltip(state)).toContain("Click to retry"); }); + it("prefers install when a downloaded version already exists", () => { + const state: DesktopUpdateState = { + ...baseState, + status: "available", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + }; + expect(resolveDesktopUpdateButtonAction(state)).toBe("install"); + }); + it("hides the button for non-actionable check errors", () => { const state: DesktopUpdateState = { ...baseState, @@ -169,25 +180,6 @@ describe("desktop update UI helpers", () => { ).toBe(false); }); - it("highlights only actionable updater errors", () => { - expect( - shouldHighlightDesktopUpdateError({ - ...baseState, - status: "error", - errorContext: "download", - canRetry: true, - }), - ).toBe(true); - expect( - shouldHighlightDesktopUpdateError({ - ...baseState, - status: "error", - errorContext: "check", - canRetry: true, - }), - ).toBe(false); - }); - it("shows an Apple Silicon warning for Intel builds under Rosetta", () => { const state: DesktopUpdateState = { ...baseState, @@ -213,4 +205,87 @@ describe("desktop update UI helpers", () => { expect(getArm64IntelBuildWarningDescription(state)).toContain("Download the available update"); }); + + it("includes the downloaded version in the install confirmation copy", () => { + expect( + getDesktopUpdateInstallConfirmationMessage({ + availableVersion: "1.1.0", + downloadedVersion: "1.1.1", + }), + ).toContain("Install update 1.1.1 and restart T3 Code?"); + }); + + it("falls back to generic install confirmation copy when no version is available", () => { + expect( + getDesktopUpdateInstallConfirmationMessage({ + availableVersion: null, + downloadedVersion: null, + }), + ).toContain("Install update and restart T3 Code?"); + }); +}); + +describe("canCheckForUpdate", () => { + it("returns false for null state", () => { + expect(canCheckForUpdate(null)).toBe(false); + }); + + it("returns false when updates are disabled", () => { + expect(canCheckForUpdate({ ...baseState, enabled: false, status: "disabled" })).toBe(false); + }); + + it("returns false while checking", () => { + expect(canCheckForUpdate({ ...baseState, status: "checking" })).toBe(false); + }); + + it("returns false while downloading", () => { + expect(canCheckForUpdate({ ...baseState, status: "downloading", downloadPercent: 50 })).toBe( + false, + ); + }); + + it("returns false once an update has been downloaded", () => { + expect( + canCheckForUpdate({ + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + }), + ).toBe(false); + }); + + it("returns true when idle", () => { + expect(canCheckForUpdate({ ...baseState, status: "idle" })).toBe(true); + }); + + it("returns true when up-to-date", () => { + expect(canCheckForUpdate({ ...baseState, status: "up-to-date" })).toBe(true); + }); + + it("returns true when an update is available", () => { + expect( + canCheckForUpdate({ ...baseState, status: "available", availableVersion: "1.1.0" }), + ).toBe(true); + }); + + it("returns true on error so the user can retry", () => { + expect( + canCheckForUpdate({ + ...baseState, + status: "error", + errorContext: "check", + message: "network", + }), + ).toBe(true); + }); +}); + +describe("getDesktopUpdateButtonTooltip", () => { + it("returns 'Up to date' for non-actionable states", () => { + expect(getDesktopUpdateButtonTooltip({ ...baseState, status: "idle" })).toBe("Up to date"); + expect(getDesktopUpdateButtonTooltip({ ...baseState, status: "up-to-date" })).toBe( + "Up to date", + ); + }); }); diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.ts index 5c9c303026..38983c810b 100644 --- a/apps/web/src/components/desktopUpdate.logic.ts +++ b/apps/web/src/components/desktopUpdate.logic.ts @@ -5,16 +5,13 @@ export type DesktopUpdateButtonAction = "download" | "install" | "none"; export function resolveDesktopUpdateButtonAction( state: DesktopUpdateState, ): DesktopUpdateButtonAction { + if (state.downloadedVersion) { + return "install"; + } if (state.status === "available") { return "download"; } - if (state.status === "downloaded") { - return "install"; - } if (state.status === "error") { - if (state.errorContext === "install" && state.downloadedVersion) { - return "install"; - } if (state.errorContext === "download" && state.availableVersion) { return "download"; } @@ -76,7 +73,14 @@ export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string } return state.message ?? "Update failed"; } - return "Update available"; + return "Up to date"; +} + +export function getDesktopUpdateInstallConfirmationMessage( + state: Pick, +): string { + const version = state.downloadedVersion ?? state.availableVersion; + return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.`; } export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null { @@ -94,3 +98,13 @@ export function shouldHighlightDesktopUpdateError(state: DesktopUpdateState | nu if (!state || state.status !== "error") return false; return state.errorContext === "download" || state.errorContext === "install"; } + +export function canCheckForUpdate(state: DesktopUpdateState | null): boolean { + if (!state || !state.enabled) return false; + return ( + state.status !== "checking" && + state.status !== "downloading" && + state.status !== "downloaded" && + state.status !== "disabled" + ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index bb149c00a4..f9fdb1d615 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -22,12 +22,24 @@ import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings"; import { normalizeModelSlug } from "@t3tools/shared/model"; import { Equal } from "effect"; import { APP_VERSION } from "../../branding"; +import { + canCheckForUpdate, + getDesktopUpdateButtonTooltip, + getDesktopUpdateInstallConfirmationMessage, + isDesktopUpdateButtonDisabled, + resolveDesktopUpdateButtonAction, +} from "../../components/desktopUpdate.logic"; import { ProviderModelPicker } from "../chat/ProviderModelPicker"; import { TraitsPicker } from "../chat/TraitsPicker"; import { resolveAndPersistPreferredEditor } from "../../editorPreferences"; +import { isElectron } from "../../env"; import { useTheme } from "../../hooks/useTheme"; import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; import { useThreadActions } from "../../hooks/useThreadActions"; +import { + setDesktopUpdateStateQueryData, + useDesktopUpdateState, +} from "../../lib/desktopUpdateReactQuery"; import { serverConfigQueryOptions, serverQueryKeys } from "../../lib/serverReactQuery"; import { MAX_CUSTOM_MODEL_LENGTH, @@ -236,7 +248,7 @@ function SettingsRow({ control, children, }: { - title: string; + title: ReactNode; description: string; status?: ReactNode; resetAction?: ReactNode; @@ -299,6 +311,133 @@ function SettingsPageContainer({ children }: { children: ReactNode }) { ); } +function AboutVersionTitle() { + return ( + + Version + {APP_VERSION} + + ); +} + +function AboutVersionSection() { + const queryClient = useQueryClient(); + const updateStateQuery = useDesktopUpdateState(); + + const updateState = updateStateQuery.data ?? null; + + const handleButtonClick = useCallback(() => { + const bridge = window.desktopBridge; + if (!bridge) return; + + const action = updateState ? resolveDesktopUpdateButtonAction(updateState) : "none"; + + if (action === "download") { + void bridge + .downloadUpdate() + .then((result) => { + setDesktopUpdateStateQueryData(queryClient, result.state); + }) + .catch((error: unknown) => { + toastManager.add({ + type: "error", + title: "Could not download update", + description: error instanceof Error ? error.message : "Download failed.", + }); + }); + return; + } + + if (action === "install") { + const confirmed = window.confirm( + getDesktopUpdateInstallConfirmationMessage( + updateState ?? { availableVersion: null, downloadedVersion: null }, + ), + ); + if (!confirmed) return; + void bridge + .installUpdate() + .then((result) => { + setDesktopUpdateStateQueryData(queryClient, result.state); + }) + .catch((error: unknown) => { + toastManager.add({ + type: "error", + title: "Could not install update", + description: error instanceof Error ? error.message : "Install failed.", + }); + }); + return; + } + + if (typeof bridge.checkForUpdate !== "function") return; + void bridge + .checkForUpdate() + .then((result) => { + setDesktopUpdateStateQueryData(queryClient, result.state); + if (!result.checked) { + toastManager.add({ + type: "error", + title: "Could not check for updates", + description: + result.state.message ?? "Automatic updates are not available in this build.", + }); + } + }) + .catch((error: unknown) => { + toastManager.add({ + type: "error", + title: "Could not check for updates", + description: error instanceof Error ? error.message : "Update check failed.", + }); + }); + }, [queryClient, updateState]); + + const action = updateState ? resolveDesktopUpdateButtonAction(updateState) : "none"; + const buttonTooltip = updateState ? getDesktopUpdateButtonTooltip(updateState) : null; + const buttonDisabled = + action === "none" + ? !canCheckForUpdate(updateState) + : isDesktopUpdateButtonDisabled(updateState); + + const actionLabel: Record = { download: "Download", install: "Install" }; + const statusLabel: Record = { + checking: "Checking…", + downloading: "Downloading…", + "up-to-date": "Up to Date", + }; + const buttonLabel = + actionLabel[action] ?? statusLabel[updateState?.status ?? ""] ?? "Check for Updates"; + const description = + action === "download" || action === "install" + ? "Update available." + : "Current version of the application."; + + return ( + } + description={description} + control={ + + + {buttonLabel} + + } + /> + {buttonTooltip ? {buttonTooltip} : null} + + } + /> + ); +} + export function useSettingsRestore(onRestored?: () => void) { const { theme, setTheme } = useTheme(); const settings = useSettings(); @@ -1258,12 +1397,17 @@ export function GeneralSettingsPanel() { } /> + - {APP_VERSION}} - /> + + {isElectron ? ( + + ) : ( + } + description="Current version of the application." + /> + )} ); @@ -1325,7 +1469,7 @@ export function ArchivedThreadsPanel() { {archivedGroups.length === 0 ? ( - + diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsx index 20914b499d..6ba698c91f 100644 --- a/apps/web/src/components/settings/SettingsSidebarNav.tsx +++ b/apps/web/src/components/settings/SettingsSidebarNav.tsx @@ -20,7 +20,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{ icon: ComponentType<{ className?: string }>; }> = [ { label: "General", to: "/settings/general", icon: Settings2Icon }, - { label: "Archived threads", to: "/settings/archived", icon: ArchiveIcon }, + { label: "Archive", to: "/settings/archived", icon: ArchiveIcon }, ]; export function SettingsSidebarNav({ pathname }: { pathname: string }) { diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx new file mode 100644 index 0000000000..2f9aec112a --- /dev/null +++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx @@ -0,0 +1,176 @@ +import { DownloadIcon, RotateCwIcon, TriangleAlertIcon, XIcon } from "lucide-react"; +import { useQueryClient } from "@tanstack/react-query"; +import { useCallback, useState } from "react"; +import { isElectron } from "../../env"; +import { + setDesktopUpdateStateQueryData, + useDesktopUpdateState, +} from "../../lib/desktopUpdateReactQuery"; +import { toastManager } from "../ui/toast"; +import { + getArm64IntelBuildWarningDescription, + getDesktopUpdateActionError, + getDesktopUpdateButtonTooltip, + getDesktopUpdateInstallConfirmationMessage, + isDesktopUpdateButtonDisabled, + resolveDesktopUpdateButtonAction, + shouldShowArm64IntelBuildWarning, + shouldShowDesktopUpdateButton, + shouldToastDesktopUpdateActionResult, +} from "../desktopUpdate.logic"; +import { Alert, AlertDescription, AlertTitle } from "../ui/alert"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; + +export function SidebarUpdatePill() { + const queryClient = useQueryClient(); + const state = useDesktopUpdateState().data ?? null; + const [dismissed, setDismissed] = useState(false); + + const visible = isElectron && shouldShowDesktopUpdateButton(state) && !dismissed; + const tooltip = state ? getDesktopUpdateButtonTooltip(state) : "Update available"; + const disabled = isDesktopUpdateButtonDisabled(state); + const action = state ? resolveDesktopUpdateButtonAction(state) : "none"; + + const showArm64Warning = isElectron && shouldShowArm64IntelBuildWarning(state); + const arm64Description = + state && showArm64Warning ? getArm64IntelBuildWarningDescription(state) : null; + + const handleAction = useCallback(() => { + const bridge = window.desktopBridge; + if (!bridge || !state) return; + if (disabled || action === "none") return; + + if (action === "download") { + void bridge + .downloadUpdate() + .then((result) => { + setDesktopUpdateStateQueryData(queryClient, result.state); + if (result.completed) { + toastManager.add({ + type: "success", + title: "Update downloaded", + description: "Restart the app from the update button to install it.", + }); + } + if (!shouldToastDesktopUpdateActionResult(result)) return; + const actionError = getDesktopUpdateActionError(result); + if (!actionError) return; + toastManager.add({ + type: "error", + title: "Could not download update", + description: actionError, + }); + }) + .catch((error) => { + toastManager.add({ + type: "error", + title: "Could not start update download", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }); + }); + return; + } + + if (action === "install") { + const confirmed = window.confirm(getDesktopUpdateInstallConfirmationMessage(state)); + if (!confirmed) return; + void bridge + .installUpdate() + .then((result) => { + setDesktopUpdateStateQueryData(queryClient, result.state); + if (!shouldToastDesktopUpdateActionResult(result)) return; + const actionError = getDesktopUpdateActionError(result); + if (!actionError) return; + toastManager.add({ + type: "error", + title: "Could not install update", + description: actionError, + }); + }) + .catch((error) => { + toastManager.add({ + type: "error", + title: "Could not install update", + description: error instanceof Error ? error.message : "An unexpected error occurred.", + }); + }); + } + }, [action, disabled, queryClient, state]); + + if (!visible && !showArm64Warning) return null; + + return ( +
+ {showArm64Warning && arm64Description && ( + + + Intel build on Apple Silicon + {arm64Description} + + )} + {visible && ( +
+
+ + + {action === "install" ? ( + <> + + Restart to update + + ) : state?.status === "downloading" ? ( + <> + + + Downloading + {typeof state.downloadPercent === "number" + ? ` (${Math.floor(state.downloadPercent)}%)` + : "…"} + + + ) : ( + <> + + Update available + + )} + + } + /> + {tooltip} + + {action === "download" && ( + + setDismissed(true)} + > + + + } + /> + Dismiss until next launch + + )} +
+ )} +
+ ); +} diff --git a/apps/web/src/lib/desktopUpdateReactQuery.test.ts b/apps/web/src/lib/desktopUpdateReactQuery.test.ts new file mode 100644 index 0000000000..a0f4755918 --- /dev/null +++ b/apps/web/src/lib/desktopUpdateReactQuery.test.ts @@ -0,0 +1,49 @@ +import { QueryClient } from "@tanstack/react-query"; +import { describe, expect, it } from "vitest"; +import type { DesktopUpdateState } from "@t3tools/contracts"; +import { + desktopUpdateQueryKeys, + desktopUpdateStateQueryOptions, + setDesktopUpdateStateQueryData, +} from "./desktopUpdateReactQuery"; + +const baseState: DesktopUpdateState = { + enabled: true, + status: "idle", + currentVersion: "1.0.0", + hostArch: "x64", + appArch: "x64", + runningUnderArm64Translation: false, + availableVersion: null, + downloadedVersion: null, + downloadPercent: null, + checkedAt: null, + message: null, + errorContext: null, + canRetry: false, +}; + +describe("desktopUpdateStateQueryOptions", () => { + it("always refetches on mount so Settings does not reuse stale desktop update state", () => { + const options = desktopUpdateStateQueryOptions(); + + expect(options.staleTime).toBe(Infinity); + expect(options.refetchOnMount).toBe("always"); + }); +}); + +describe("setDesktopUpdateStateQueryData", () => { + it("writes desktop update state into the shared cache key", () => { + const queryClient = new QueryClient(); + const nextState: DesktopUpdateState = { + ...baseState, + status: "downloaded", + availableVersion: "1.1.0", + downloadedVersion: "1.1.0", + }; + + setDesktopUpdateStateQueryData(queryClient, nextState); + + expect(queryClient.getQueryData(desktopUpdateQueryKeys.state())).toEqual(nextState); + }); +}); diff --git a/apps/web/src/lib/desktopUpdateReactQuery.ts b/apps/web/src/lib/desktopUpdateReactQuery.ts new file mode 100644 index 0000000000..9315772786 --- /dev/null +++ b/apps/web/src/lib/desktopUpdateReactQuery.ts @@ -0,0 +1,42 @@ +import { queryOptions, useQuery, useQueryClient, type QueryClient } from "@tanstack/react-query"; +import { useEffect } from "react"; +import type { DesktopUpdateState } from "@t3tools/contracts"; + +export const desktopUpdateQueryKeys = { + all: ["desktop", "update"] as const, + state: () => ["desktop", "update", "state"] as const, +}; + +export const setDesktopUpdateStateQueryData = ( + queryClient: QueryClient, + state: DesktopUpdateState | null, +) => queryClient.setQueryData(desktopUpdateQueryKeys.state(), state); + +export function desktopUpdateStateQueryOptions() { + return queryOptions({ + queryKey: desktopUpdateQueryKeys.state(), + queryFn: async () => { + const bridge = window.desktopBridge; + if (!bridge || typeof bridge.getUpdateState !== "function") return null; + return bridge.getUpdateState(); + }, + staleTime: Infinity, + refetchOnMount: "always", + }); +} + +export function useDesktopUpdateState() { + const queryClient = useQueryClient(); + const query = useQuery(desktopUpdateStateQueryOptions()); + + useEffect(() => { + const bridge = window.desktopBridge; + if (!bridge || typeof bridge.onUpdateState !== "function") return; + + return bridge.onUpdateState((nextState) => { + setDesktopUpdateStateQueryData(queryClient, nextState); + }); + }, [queryClient]); + + return query; +} diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 0443128dd5..5585e7f309 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -101,6 +101,11 @@ export interface DesktopUpdateActionResult { state: DesktopUpdateState; } +export interface DesktopUpdateCheckResult { + checked: boolean; + state: DesktopUpdateState; +} + export interface DesktopBridge { getWsUrl: () => string | null; pickFolder: () => Promise; @@ -113,6 +118,7 @@ export interface DesktopBridge { openExternal: (url: string) => Promise; onMenuAction: (listener: (action: string) => void) => () => void; getUpdateState: () => Promise; + checkForUpdate: () => Promise; downloadUpdate: () => Promise; installUpdate: () => Promise; onUpdateState: (listener: (state: DesktopUpdateState) => void) => () => void; From 5462d501774a25b8cc16a572d6e6b44dc54bc796 Mon Sep 17 00:00:00 2001 From: "t3-code[bot]" <269035359+t3-code[bot]@users.noreply.github.com> Date: Sun, 29 Mar 2026 04:52:14 +0000 Subject: [PATCH 34/66] chore(release): prepare v0.0.15 --- apps/desktop/package.json | 2 +- apps/server/package.json | 2 +- apps/web/package.json | 2 +- bun.lock | 8 ++++---- packages/contracts/package.json | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 188e701e7e..7ecb81c791 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/desktop", - "version": "0.0.14", + "version": "0.0.15", "private": true, "main": "dist-electron/main.js", "scripts": { diff --git a/apps/server/package.json b/apps/server/package.json index ea818b7d3e..e473e21fd1 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "t3", - "version": "0.0.14", + "version": "0.0.15", "license": "MIT", "repository": { "type": "git", diff --git a/apps/web/package.json b/apps/web/package.json index 5127faf827..bd0fb9e0ac 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/web", - "version": "0.0.14", + "version": "0.0.15", "private": true, "type": "module", "scripts": { diff --git a/bun.lock b/bun.lock index fa083cdc53..e13245b727 100644 --- a/bun.lock +++ b/bun.lock @@ -14,7 +14,7 @@ }, "apps/desktop": { "name": "@t3tools/desktop", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "effect": "catalog:", "electron": "40.6.0", @@ -43,7 +43,7 @@ }, "apps/server": { "name": "t3", - "version": "0.0.14", + "version": "0.0.15", "bin": { "t3": "./dist/index.mjs", }, @@ -73,7 +73,7 @@ }, "apps/web": { "name": "@t3tools/web", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "@base-ui/react": "^1.2.0", "@dnd-kit/core": "^6.3.1", @@ -124,7 +124,7 @@ }, "packages/contracts": { "name": "@t3tools/contracts", - "version": "0.0.14", + "version": "0.0.15", "dependencies": { "effect": "catalog:", }, diff --git a/packages/contracts/package.json b/packages/contracts/package.json index 29d0c1398f..fe03c205a5 100644 --- a/packages/contracts/package.json +++ b/packages/contracts/package.json @@ -1,6 +1,6 @@ { "name": "@t3tools/contracts", - "version": "0.0.14", + "version": "0.0.15", "private": true, "files": [ "dist" From 7f3387a86cf6ed2e9bb7318db56b1ab19de80e69 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 22:35:18 -0700 Subject: [PATCH 35/66] Annotate Git core Effect.fn helpers (#1511) --- apps/server/src/git/Layers/GitCore.ts | 2808 ++++++++--------- apps/server/src/git/Layers/GitManager.test.ts | 2 +- apps/server/src/git/Layers/GitManager.ts | 1127 +++---- docs/effect-fn-checklist.md | 63 +- 4 files changed, 2006 insertions(+), 1994 deletions(-) diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index fcb2f9c58e..64ed409508 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -294,7 +294,7 @@ function trace2ChildKey(record: Record): string | null { const Trace2Record = Schema.Record(Schema.String, Schema.Unknown); -const createTrace2Monitor = Effect.fn(function* ( +const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* ( input: Pick, progress: ExecuteGitProgress | undefined, ): Effect.fn.Return< @@ -321,61 +321,58 @@ const createTrace2Monitor = Effect.fn(function* ( remainder: "", }); - const handleTraceLine = (line: string) => - Effect.gen(function* () { - const trimmedLine = line.trim(); - if (trimmedLine.length === 0) { - return; - } + const handleTraceLine = Effect.fn("handleTraceLine")(function* (line: string) { + const trimmedLine = line.trim(); + if (trimmedLine.length === 0) { + return; + } - const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); - if (Result.isFailure(traceRecord)) { - yield* Effect.logDebug( - `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, - traceRecord.failure, - ); - return; - } + const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine); + if (Result.isFailure(traceRecord)) { + yield* Effect.logDebug( + `GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`, + traceRecord.failure, + ); + return; + } - if (traceRecord.success.child_class !== "hook") { - return; - } + if (traceRecord.success.child_class !== "hook") { + return; + } - const event = traceRecord.success.event; - const childKey = trace2ChildKey(traceRecord.success); - if (childKey === null) { - return; - } - const started = hookStartByChildKey.get(childKey); - const hookNameFromEvent = - typeof traceRecord.success.hook_name === "string" - ? traceRecord.success.hook_name.trim() - : ""; - const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); - if (hookName.length === 0) { - return; - } + const event = traceRecord.success.event; + const childKey = trace2ChildKey(traceRecord.success); + if (childKey === null) { + return; + } + const started = hookStartByChildKey.get(childKey); + const hookNameFromEvent = + typeof traceRecord.success.hook_name === "string" ? traceRecord.success.hook_name.trim() : ""; + const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? ""); + if (hookName.length === 0) { + return; + } - if (event === "child_start") { - hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); - if (progress.onHookStarted) { - yield* progress.onHookStarted(hookName); - } - return; + if (event === "child_start") { + hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() }); + if (progress.onHookStarted) { + yield* progress.onHookStarted(hookName); } + return; + } - if (event === "child_exit") { - hookStartByChildKey.delete(childKey); - if (progress.onHookFinished) { - const code = traceRecord.success.code; - yield* progress.onHookFinished({ - hookName: started?.hookName ?? hookName, - exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, - durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, - }); - } + if (event === "child_exit") { + hookStartByChildKey.delete(childKey); + if (progress.onHookFinished) { + const code = traceRecord.success.code; + yield* progress.onHookFinished({ + hookName: started?.hookName ?? hookName, + exitCode: typeof code === "number" && Number.isInteger(code) ? code : null, + durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null, + }); } - }); + } + }); const deltaMutex = yield* Semaphore.make(1); const readTraceDelta = deltaMutex.withPermit( @@ -418,21 +415,21 @@ const createTrace2Monitor = Effect.fn(function* ( return readTraceDelta; }).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped); - yield* Effect.addFinalizer(() => - Effect.gen(function* () { - yield* readTraceDelta; - const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ - remainder.trim(), - { - processedChars, - remainder: "", - }, - ]); - if (finalLine.length > 0) { - yield* handleTraceLine(finalLine); - } - }), - ); + const finalizeTrace2Monitor = Effect.fn("finalizeTrace2Monitor")(function* () { + yield* readTraceDelta; + const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [ + remainder.trim(), + { + processedChars, + remainder: "", + }, + ]); + if (finalLine.length > 0) { + yield* handleTraceLine(finalLine); + } + }); + + yield* Effect.addFinalizer(finalizeTrace2Monitor); return { env: { @@ -442,7 +439,7 @@ const createTrace2Monitor = Effect.fn(function* ( }; }); -const collectOutput = Effect.fn(function* ( +const collectOutput = Effect.fn("collectOutput")(function* ( input: Pick, stream: Stream.Stream, maxOutputBytes: number, @@ -455,55 +452,56 @@ const collectOutput = Effect.fn(function* ( let lineBuffer = ""; let truncated = false; - const emitCompleteLines = (flush: boolean) => - Effect.gen(function* () { - let newlineIndex = lineBuffer.indexOf("\n"); - while (newlineIndex >= 0) { - const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); - lineBuffer = lineBuffer.slice(newlineIndex + 1); - if (line.length > 0 && onLine) { - yield* onLine(line); - } - newlineIndex = lineBuffer.indexOf("\n"); + const emitCompleteLines = Effect.fn("emitCompleteLines")(function* (flush: boolean) { + let newlineIndex = lineBuffer.indexOf("\n"); + while (newlineIndex >= 0) { + const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, ""); + lineBuffer = lineBuffer.slice(newlineIndex + 1); + if (line.length > 0 && onLine) { + yield* onLine(line); } + newlineIndex = lineBuffer.indexOf("\n"); + } - if (flush) { - const trailing = lineBuffer.replace(/\r$/, ""); - lineBuffer = ""; - if (trailing.length > 0 && onLine) { - yield* onLine(trailing); - } + if (flush) { + const trailing = lineBuffer.replace(/\r$/, ""); + lineBuffer = ""; + if (trailing.length > 0 && onLine) { + yield* onLine(trailing); } - }); + } + }); - yield* Stream.runForEach(stream, (chunk) => - Effect.gen(function* () { - if (truncateOutputAtMaxBytes && truncated) { - return; - } - const nextBytes = bytes + chunk.byteLength; - if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { - return yield* new GitCommandError({ - operation: input.operation, - command: quoteGitCommand(input.args), - cwd: input.cwd, - detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, - }); - } + const processChunk = Effect.fn("processChunk")(function* (chunk: Uint8Array) { + if (truncateOutputAtMaxBytes && truncated) { + return; + } + const nextBytes = bytes + chunk.byteLength; + if (!truncateOutputAtMaxBytes && nextBytes > maxOutputBytes) { + return yield* new GitCommandError({ + operation: input.operation, + command: quoteGitCommand(input.args), + cwd: input.cwd, + detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`, + }); + } - const chunkToDecode = - truncateOutputAtMaxBytes && nextBytes > maxOutputBytes - ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) - : chunk; - bytes += chunkToDecode.byteLength; - truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; + const chunkToDecode = + truncateOutputAtMaxBytes && nextBytes > maxOutputBytes + ? chunk.subarray(0, Math.max(0, maxOutputBytes - bytes)) + : chunk; + bytes += chunkToDecode.byteLength; + truncated = truncateOutputAtMaxBytes && nextBytes > maxOutputBytes; - const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); - text += decoded; - lineBuffer += decoded; - yield* emitCompleteLines(false); - }), - ).pipe(Effect.mapError(toGitCommandError(input, "output stream failed."))); + const decoded = decoder.decode(chunkToDecode, { stream: !truncated }); + text += decoded; + lineBuffer += decoded; + yield* emitCompleteLines(false); + }); + + yield* Stream.runForEach(stream, processChunk).pipe( + Effect.mapError(toGitCommandError(input, "output stream failed.")), + ); const remainder = truncated ? "" : decoder.decode(); text += remainder; @@ -512,1367 +510,1343 @@ const collectOutput = Effect.fn(function* ( return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text; }); -export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"] }) => - Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const { worktreesDir } = yield* ServerConfig; +export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { + executeOverride?: GitCoreShape["execute"]; +}) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const { worktreesDir } = yield* ServerConfig; - let execute: GitCoreShape["execute"]; + let execute: GitCoreShape["execute"]; - if (options?.executeOverride) { - execute = options.executeOverride; - } else { - const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; - execute = Effect.fnUntraced(function* (input) { - const commandInput = { - ...input, - args: [...input.args], - } as const; - const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; - const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; - const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; + if (options?.executeOverride) { + execute = options.executeOverride; + } else { + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + execute = Effect.fnUntraced(function* (input) { + const commandInput = { + ...input, + args: [...input.args], + } as const; + const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES; + const truncateOutputAtMaxBytes = input.truncateOutputAtMaxBytes ?? false; - const commandEffect = Effect.gen(function* () { - const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( - Effect.provideService(Path.Path, path), - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), - ); - const child = yield* commandSpawner - .spawn( - ChildProcess.make("git", commandInput.args, { - cwd: commandInput.cwd, - env: { - ...process.env, - ...input.env, - ...trace2Monitor.env, - }, - }), - ) - .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); - - const [stdout, stderr, exitCode] = yield* Effect.all( - [ - collectOutput( - commandInput, - child.stdout, - maxOutputBytes, - truncateOutputAtMaxBytes, - input.progress?.onStdoutLine, - ), - collectOutput( - commandInput, - child.stderr, - maxOutputBytes, - truncateOutputAtMaxBytes, - input.progress?.onStderrLine, - ), - child.exitCode.pipe( - Effect.map((value) => Number(value)), - Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), - ), - ], - { concurrency: "unbounded" }, - ); - yield* trace2Monitor.flush; - - if (!input.allowNonZeroExit && exitCode !== 0) { - const trimmedStderr = stderr.trim(); - return yield* new GitCommandError({ - operation: commandInput.operation, - command: quoteGitCommand(commandInput.args), + const runGitCommand = Effect.fn("runGitCommand")(function* () { + const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe( + Effect.provideService(Path.Path, path), + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")), + ); + const child = yield* commandSpawner + .spawn( + ChildProcess.make("git", commandInput.args, { cwd: commandInput.cwd, - detail: - trimmedStderr.length > 0 - ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` - : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, - }); - } - - return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; - }); - - return yield* commandEffect.pipe( - Effect.scoped, - Effect.timeoutOption(timeoutMs), - Effect.flatMap((result) => - Option.match(result, { - onNone: () => - Effect.fail( - new GitCommandError({ - operation: commandInput.operation, - command: quoteGitCommand(commandInput.args), - cwd: commandInput.cwd, - detail: `${quoteGitCommand(commandInput.args)} timed out.`, - }), - ), - onSome: Effect.succeed, + env: { + ...process.env, + ...input.env, + ...trace2Monitor.env, + }, }), - ), - ); - }); - } + ) + .pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn."))); - const executeGit = ( - operation: string, - cwd: string, - args: readonly string[], - options: ExecuteGitOptions = {}, - ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => - execute({ - operation, - cwd, - args, - allowNonZeroExit: true, - ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), - ...(options.truncateOutputAtMaxBytes !== undefined - ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } - : {}), - ...(options.progress ? { progress: options.progress } : {}), - }).pipe( - Effect.flatMap((result) => { - if (options.allowNonZeroExit || result.code === 0) { - return Effect.succeed(result); - } - const stderr = result.stderr.trim(); - if (stderr.length > 0) { - return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); - } - if (options.fallbackErrorMessage) { - return Effect.fail( - createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), - ); - } - return Effect.fail( - createGitCommandError( - operation, - cwd, - args, - `${commandLabel(args)} failed: code=${result.code ?? "null"}`, + const [stdout, stderr, exitCode] = yield* Effect.all( + [ + collectOutput( + commandInput, + child.stdout, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStdoutLine, + ), + collectOutput( + commandInput, + child.stderr, + maxOutputBytes, + truncateOutputAtMaxBytes, + input.progress?.onStderrLine, + ), + child.exitCode.pipe( + Effect.map((value) => Number(value)), + Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), ), - ); - }), - ); - - const runGit = ( - operation: string, - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Effect.Effect => - executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); - - const runGitStdout = ( - operation: string, - cwd: string, - args: readonly string[], - allowNonZeroExit = false, - ): Effect.Effect => - executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( - Effect.map((result) => result.stdout), - ); - - const runGitStdoutWithOptions = ( - operation: string, - cwd: string, - args: readonly string[], - options: ExecuteGitOptions = {}, - ): Effect.Effect => - executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); - - const branchExists = (cwd: string, branch: string): Effect.Effect => - executeGit( - "GitCore.branchExists", - cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], - { - allowNonZeroExit: true, - timeoutMs: 5_000, - }, - ).pipe(Effect.map((result) => result.code === 0)); - - const resolveAvailableBranchName = ( - cwd: string, - desiredBranch: string, - ): Effect.Effect => - Effect.gen(function* () { - const isDesiredTaken = yield* branchExists(cwd, desiredBranch); - if (!isDesiredTaken) { - return desiredBranch; - } - - for (let suffix = 1; suffix <= 100; suffix += 1) { - const candidate = `${desiredBranch}-${suffix}`; - const isCandidateTaken = yield* branchExists(cwd, candidate); - if (!isCandidateTaken) { - return candidate; - } - } - - return yield* createGitCommandError( - "GitCore.renameBranch", - cwd, - ["branch", "-m", "--", desiredBranch], - `Could not find an available branch name for '${desiredBranch}'.`, - ); - }); - - const resolveCurrentUpstream = ( - cwd: string, - ): Effect.Effect< - { upstreamRef: string; remoteName: string; upstreamBranch: string } | null, - GitCommandError - > => - Effect.gen(function* () { - const upstreamRef = yield* runGitStdout( - "GitCore.resolveCurrentUpstream", - cwd, - ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { - return null; - } - - const separatorIndex = upstreamRef.indexOf("/"); - if (separatorIndex <= 0) { - return null; - } - const remoteName = upstreamRef.slice(0, separatorIndex); - const upstreamBranch = upstreamRef.slice(separatorIndex + 1); - if (remoteName.length === 0 || upstreamBranch.length === 0) { - return null; - } - - return { - upstreamRef, - remoteName, - upstreamBranch, - }; - }); - - const fetchUpstreamRef = ( - cwd: string, - upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, - ): Effect.Effect => { - const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; - return runGit( - "GitCore.fetchUpstreamRef", - cwd, - ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], - true, - ); - }; - - const fetchUpstreamRefForStatus = ( - cwd: string, - upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, - ): Effect.Effect => { - const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; - return executeGit( - "GitCore.fetchUpstreamRefForStatus", - cwd, - ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], - { - allowNonZeroExit: true, - timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), - }, - ).pipe(Effect.asVoid); - }; - - const statusUpstreamRefreshCache = yield* Cache.makeWith({ - capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, - lookup: (cacheKey: StatusUpstreamRefreshCacheKey) => - Effect.gen(function* () { - yield* fetchUpstreamRefForStatus(cacheKey.cwd, { - upstreamRef: cacheKey.upstreamRef, - remoteName: cacheKey.remoteName, - upstreamBranch: cacheKey.upstreamBranch, - }); - return true as const; - }), - // Keep successful refreshes warm; drop failures immediately so next request can retry. - timeToLive: (exit) => - Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero, - }); - - const refreshStatusUpstreamIfStale = (cwd: string): Effect.Effect => - Effect.gen(function* () { - const upstream = yield* resolveCurrentUpstream(cwd); - if (!upstream) return; - yield* Cache.get( - statusUpstreamRefreshCache, - new StatusUpstreamRefreshCacheKey({ - cwd, - upstreamRef: upstream.upstreamRef, - remoteName: upstream.remoteName, - upstreamBranch: upstream.upstreamBranch, - }), - ); - }); - - const refreshCheckedOutBranchUpstream = (cwd: string): Effect.Effect => - Effect.gen(function* () { - const upstream = yield* resolveCurrentUpstream(cwd); - if (!upstream) return; - yield* fetchUpstreamRef(cwd, upstream); - }); - - const resolveDefaultBranchName = ( - cwd: string, - remoteName: string, - ): Effect.Effect => - executeGit( - "GitCore.resolveDefaultBranchName", - cwd, - ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], - { allowNonZeroExit: true }, - ).pipe( - Effect.map((result) => { - if (result.code !== 0) { - return null; - } - return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); - }), - ); - - const remoteBranchExists = ( - cwd: string, - remoteName: string, - branch: string, - ): Effect.Effect => - executeGit( - "GitCore.remoteBranchExists", - cwd, - ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], - { - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)); - - const originRemoteExists = (cwd: string): Effect.Effect => - executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { - allowNonZeroExit: true, - }).pipe(Effect.map((result) => result.code === 0)); - - const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => - runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( - Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), - ); - - const resolvePrimaryRemoteName = (cwd: string): Effect.Effect => - Effect.gen(function* () { - if (yield* originRemoteExists(cwd)) { - return "origin"; - } - const remotes = yield* listRemoteNames(cwd); - const [firstRemote] = remotes; - if (firstRemote) { - return firstRemote; - } - return yield* createGitCommandError( - "GitCore.resolvePrimaryRemoteName", - cwd, - ["remote"], - "No git remote is configured for this repository.", - ); - }); - - const resolvePushRemoteName = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const branchPushRemote = yield* runGitStdout( - "GitCore.resolvePushRemoteName.branchPushRemote", - cwd, - ["config", "--get", `branch.${branch}.pushRemote`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (branchPushRemote.length > 0) { - return branchPushRemote; - } - - const pushDefaultRemote = yield* runGitStdout( - "GitCore.resolvePushRemoteName.remotePushDefault", - cwd, - ["config", "--get", "remote.pushDefault"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (pushDefaultRemote.length > 0) { - return pushDefaultRemote; - } - - return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); - }); - - const ensureRemote: GitCoreShape["ensureRemote"] = (input) => - Effect.gen(function* () { - const preferredName = sanitizeRemoteName(input.preferredName); - const normalizedTargetUrl = normalizeRemoteUrl(input.url); - const remoteFetchUrls = yield* runGitStdout( - "GitCore.ensureRemote.listRemoteUrls", - input.cwd, - ["remote", "-v"], - ).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); - - for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { - if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { - return remoteName; - } - } - - let remoteName = preferredName; - let suffix = 1; - while (remoteFetchUrls.has(remoteName)) { - remoteName = `${preferredName}-${suffix}`; - suffix += 1; - } - - yield* runGit("GitCore.ensureRemote.add", input.cwd, [ - "remote", - "add", - remoteName, - input.url, - ]); - return remoteName; - }); - - const resolveBaseBranchForNoUpstream = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const configuredBaseBranch = yield* runGitStdout( - "GitCore.resolveBaseBranchForNoUpstream.config", - cwd, - ["config", "--get", `branch.${branch}.gh-merge-base`], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - const defaultBranch = - primaryRemoteName === null - ? null - : yield* resolveDefaultBranchName(cwd, primaryRemoteName); - const candidates = [ - configuredBaseBranch.length > 0 ? configuredBaseBranch : null, - defaultBranch, - ...DEFAULT_BASE_BRANCH_CANDIDATES, - ]; - - for (const candidate of candidates) { - if (!candidate) { - continue; - } - - const remotePrefix = - primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; - const normalizedCandidate = candidate.startsWith("origin/") - ? candidate.slice("origin/".length) - : remotePrefix && candidate.startsWith(remotePrefix) - ? candidate.slice(remotePrefix.length) - : candidate; - if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { - continue; - } - - if (yield* branchExists(cwd, normalizedCandidate)) { - return normalizedCandidate; - } - - if ( - primaryRemoteName && - (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) - ) { - return `${primaryRemoteName}/${normalizedCandidate}`; - } - } - - return null; - }); - - const computeAheadCountAgainstBase = ( - cwd: string, - branch: string, - ): Effect.Effect => - Effect.gen(function* () { - const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); - if (!baseBranch) { - return 0; - } - - const result = yield* executeGit( - "GitCore.computeAheadCountAgainstBase", - cwd, - ["rev-list", "--count", `${baseBranch}..HEAD`], - { allowNonZeroExit: true }, - ); - if (result.code !== 0) { - return 0; - } - - const parsed = Number.parseInt(result.stdout.trim(), 10); - return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; - }); - - const readBranchRecency = (cwd: string): Effect.Effect, GitCommandError> => - Effect.gen(function* () { - const branchRecency = yield* executeGit( - "GitCore.readBranchRecency", - cwd, - [ - "for-each-ref", - "--format=%(refname:short)%09%(committerdate:unix)", - "refs/heads", - "refs/remotes", - ], - { - timeoutMs: 15_000, - allowNonZeroExit: true, - }, - ); - - const branchLastCommit = new Map(); - if (branchRecency.code !== 0) { - return branchLastCommit; - } - - for (const line of branchRecency.stdout.split("\n")) { - if (line.length === 0) { - continue; - } - const [name, lastCommitRaw] = line.split("\t"); - if (!name) { - continue; - } - const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); - branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); - } - - return branchLastCommit; - }); - - const statusDetails: GitCoreShape["statusDetails"] = (cwd) => - Effect.gen(function* () { - yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); - - const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( - [ - runGitStdout("GitCore.statusDetails.status", cwd, [ - "status", - "--porcelain=2", - "--branch", - ]), - runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), - runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [ - "diff", - "--cached", - "--numstat", - ]), ], { concurrency: "unbounded" }, ); + yield* trace2Monitor.flush; - let branch: string | null = null; - let upstreamRef: string | null = null; - let aheadCount = 0; - let behindCount = 0; - let hasWorkingTreeChanges = false; - const changedFilesWithoutNumstat = new Set(); - - for (const line of statusStdout.split(/\r?\n/g)) { - if (line.startsWith("# branch.head ")) { - const value = line.slice("# branch.head ".length).trim(); - branch = value.startsWith("(") ? null : value; - continue; - } - if (line.startsWith("# branch.upstream ")) { - const value = line.slice("# branch.upstream ".length).trim(); - upstreamRef = value.length > 0 ? value : null; - continue; - } - if (line.startsWith("# branch.ab ")) { - const value = line.slice("# branch.ab ".length).trim(); - const parsed = parseBranchAb(value); - aheadCount = parsed.ahead; - behindCount = parsed.behind; - continue; - } - if (line.trim().length > 0 && !line.startsWith("#")) { - hasWorkingTreeChanges = true; - const pathValue = parsePorcelainPath(line); - if (pathValue) changedFilesWithoutNumstat.add(pathValue); - } + if (!input.allowNonZeroExit && exitCode !== 0) { + const trimmedStderr = stderr.trim(); + return yield* new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: + trimmedStderr.length > 0 + ? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}` + : `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`, + }); } - if (!upstreamRef && branch) { - aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(0)), - ); - behindCount = 0; - } - - const stagedEntries = parseNumstatEntries(stagedNumstatStdout); - const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); - const fileStatMap = new Map(); - for (const entry of [...stagedEntries, ...unstagedEntries]) { - const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; - existing.insertions += entry.insertions; - existing.deletions += entry.deletions; - fileStatMap.set(entry.path, existing); - } - - let insertions = 0; - let deletions = 0; - const files = Array.from(fileStatMap.entries()) - .map(([filePath, stat]) => { - insertions += stat.insertions; - deletions += stat.deletions; - return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; - }) - .toSorted((a, b) => a.path.localeCompare(b.path)); - - for (const filePath of changedFilesWithoutNumstat) { - if (fileStatMap.has(filePath)) continue; - files.push({ path: filePath, insertions: 0, deletions: 0 }); - } - files.sort((a, b) => a.path.localeCompare(b.path)); - - return { - branch, - upstreamRef, - hasWorkingTreeChanges, - workingTree: { - files, - insertions, - deletions, - }, - hasUpstream: upstreamRef !== null, - aheadCount, - behindCount, - }; + return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; }); - const status: GitCoreShape["status"] = (input) => - statusDetails(input.cwd).pipe( - Effect.map((details) => ({ - branch: details.branch, - hasWorkingTreeChanges: details.hasWorkingTreeChanges, - workingTree: details.workingTree, - hasUpstream: details.hasUpstream, - aheadCount: details.aheadCount, - behindCount: details.behindCount, - pr: null, - })), + return yield* runGitCommand().pipe( + Effect.scoped, + Effect.timeoutOption(timeoutMs), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => + Effect.fail( + new GitCommandError({ + operation: commandInput.operation, + command: quoteGitCommand(commandInput.args), + cwd: commandInput.cwd, + detail: `${quoteGitCommand(commandInput.args)} timed out.`, + }), + ), + onSome: Effect.succeed, + }), + ), ); + }); + } - const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) => - Effect.gen(function* () { - if (filePaths && filePaths.length > 0) { - yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( - Effect.catch(() => Effect.void), - ); - yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ - "add", - "-A", - "--", - ...filePaths, - ]); - } else { - yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); + const executeGit = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => + execute({ + operation, + cwd, + args, + allowNonZeroExit: true, + ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), + ...(options.truncateOutputAtMaxBytes !== undefined + ? { truncateOutputAtMaxBytes: options.truncateOutputAtMaxBytes } + : {}), + ...(options.progress ? { progress: options.progress } : {}), + }).pipe( + Effect.flatMap((result) => { + if (options.allowNonZeroExit || result.code === 0) { + return Effect.succeed(result); } + const stderr = result.stderr.trim(); + if (stderr.length > 0) { + return Effect.fail(createGitCommandError(operation, cwd, args, stderr)); + } + if (options.fallbackErrorMessage) { + return Effect.fail( + createGitCommandError(operation, cwd, args, options.fallbackErrorMessage), + ); + } + return Effect.fail( + createGitCommandError( + operation, + cwd, + args, + `${commandLabel(args)} failed: code=${result.code ?? "null"}`, + ), + ); + }), + ); - const stagedSummary = yield* runGitStdout( - "GitCore.prepareCommitContext.stagedSummary", - cwd, - ["diff", "--cached", "--name-status"], - ).pipe(Effect.map((stdout) => stdout.trim())); - if (stagedSummary.length === 0) { + const runGit = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe(Effect.asVoid); + + const runGitStdout = ( + operation: string, + cwd: string, + args: readonly string[], + allowNonZeroExit = false, + ): Effect.Effect => + executeGit(operation, cwd, args, { allowNonZeroExit }).pipe( + Effect.map((result) => result.stdout), + ); + + const runGitStdoutWithOptions = ( + operation: string, + cwd: string, + args: readonly string[], + options: ExecuteGitOptions = {}, + ): Effect.Effect => + executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); + + const branchExists = (cwd: string, branch: string): Effect.Effect => + executeGit( + "GitCore.branchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`], + { + allowNonZeroExit: true, + timeoutMs: 5_000, + }, + ).pipe(Effect.map((result) => result.code === 0)); + + const resolveAvailableBranchName = Effect.fn("resolveAvailableBranchName")(function* ( + cwd: string, + desiredBranch: string, + ) { + const isDesiredTaken = yield* branchExists(cwd, desiredBranch); + if (!isDesiredTaken) { + return desiredBranch; + } + + for (let suffix = 1; suffix <= 100; suffix += 1) { + const candidate = `${desiredBranch}-${suffix}`; + const isCandidateTaken = yield* branchExists(cwd, candidate); + if (!isCandidateTaken) { + return candidate; + } + } + + return yield* createGitCommandError( + "GitCore.renameBranch", + cwd, + ["branch", "-m", "--", desiredBranch], + `Could not find an available branch name for '${desiredBranch}'.`, + ); + }); + + const resolveCurrentUpstream = Effect.fn("resolveCurrentUpstream")(function* (cwd: string) { + const upstreamRef = yield* runGitStdout( + "GitCore.resolveCurrentUpstream", + cwd, + ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + if (upstreamRef.length === 0 || upstreamRef === "@{upstream}") { + return null; + } + + const separatorIndex = upstreamRef.indexOf("/"); + if (separatorIndex <= 0) { + return null; + } + const remoteName = upstreamRef.slice(0, separatorIndex); + const upstreamBranch = upstreamRef.slice(separatorIndex + 1); + if (remoteName.length === 0 || upstreamBranch.length === 0) { + return null; + } + + return { + upstreamRef, + remoteName, + upstreamBranch, + }; + }); + + const fetchUpstreamRef = ( + cwd: string, + upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, + ): Effect.Effect => { + const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + return runGit( + "GitCore.fetchUpstreamRef", + cwd, + ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + true, + ); + }; + + const fetchUpstreamRefForStatus = ( + cwd: string, + upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string }, + ): Effect.Effect => { + const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`; + return executeGit( + "GitCore.fetchUpstreamRefForStatus", + cwd, + ["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec], + { + allowNonZeroExit: true, + timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), + }, + ).pipe(Effect.asVoid); + }; + + const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* ( + cacheKey: StatusUpstreamRefreshCacheKey, + ) { + yield* fetchUpstreamRefForStatus(cacheKey.cwd, { + upstreamRef: cacheKey.upstreamRef, + remoteName: cacheKey.remoteName, + upstreamBranch: cacheKey.upstreamBranch, + }); + return true as const; + }); + + const statusUpstreamRefreshCache = yield* Cache.makeWith({ + capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY, + lookup: refreshStatusUpstreamCacheEntry, + // Keep successful refreshes warm; drop failures immediately so next request can retry. + timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero), + }); + + const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( + cwd: string, + ) { + const upstream = yield* resolveCurrentUpstream(cwd); + if (!upstream) return; + yield* Cache.get( + statusUpstreamRefreshCache, + new StatusUpstreamRefreshCacheKey({ + cwd, + upstreamRef: upstream.upstreamRef, + remoteName: upstream.remoteName, + upstreamBranch: upstream.upstreamBranch, + }), + ); + }); + + const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* ( + cwd: string, + ) { + const upstream = yield* resolveCurrentUpstream(cwd); + if (!upstream) return; + yield* fetchUpstreamRef(cwd, upstream); + }); + + const resolveDefaultBranchName = ( + cwd: string, + remoteName: string, + ): Effect.Effect => + executeGit( + "GitCore.resolveDefaultBranchName", + cwd, + ["symbolic-ref", `refs/remotes/${remoteName}/HEAD`], + { allowNonZeroExit: true }, + ).pipe( + Effect.map((result) => { + if (result.code !== 0) { return null; } + return parseDefaultBranchFromRemoteHeadRef(result.stdout, remoteName); + }), + ); - const stagedPatch = yield* runGitStdoutWithOptions( - "GitCore.prepareCommitContext.stagedPatch", + const remoteBranchExists = ( + cwd: string, + remoteName: string, + branch: string, + ): Effect.Effect => + executeGit( + "GitCore.remoteBranchExists", + cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${remoteName}/${branch}`], + { + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)); + + const originRemoteExists = (cwd: string): Effect.Effect => + executeGit("GitCore.originRemoteExists", cwd, ["remote", "get-url", "origin"], { + allowNonZeroExit: true, + }).pipe(Effect.map((result) => result.code === 0)); + + const listRemoteNames = (cwd: string): Effect.Effect, GitCommandError> => + runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe( + Effect.map((stdout) => parseRemoteNames(stdout).toReversed()), + ); + + const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { + if (yield* originRemoteExists(cwd)) { + return "origin"; + } + const remotes = yield* listRemoteNames(cwd); + const [firstRemote] = remotes; + if (firstRemote) { + return firstRemote; + } + return yield* createGitCommandError( + "GitCore.resolvePrimaryRemoteName", + cwd, + ["remote"], + "No git remote is configured for this repository.", + ); + }); + + const resolvePushRemoteName = Effect.fn("resolvePushRemoteName")(function* ( + cwd: string, + branch: string, + ) { + const branchPushRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.branchPushRemote", + cwd, + ["config", "--get", `branch.${branch}.pushRemote`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (branchPushRemote.length > 0) { + return branchPushRemote; + } + + const pushDefaultRemote = yield* runGitStdout( + "GitCore.resolvePushRemoteName.remotePushDefault", + cwd, + ["config", "--get", "remote.pushDefault"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + if (pushDefaultRemote.length > 0) { + return pushDefaultRemote; + } + + return yield* resolvePrimaryRemoteName(cwd).pipe(Effect.catch(() => Effect.succeed(null))); + }); + + const ensureRemote: GitCoreShape["ensureRemote"] = Effect.fn("ensureRemote")(function* (input) { + const preferredName = sanitizeRemoteName(input.preferredName); + const normalizedTargetUrl = normalizeRemoteUrl(input.url); + const remoteFetchUrls = yield* runGitStdout("GitCore.ensureRemote.listRemoteUrls", input.cwd, [ + "remote", + "-v", + ]).pipe(Effect.map((stdout) => parseRemoteFetchUrls(stdout))); + + for (const [remoteName, remoteUrl] of remoteFetchUrls.entries()) { + if (normalizeRemoteUrl(remoteUrl) === normalizedTargetUrl) { + return remoteName; + } + } + + let remoteName = preferredName; + let suffix = 1; + while (remoteFetchUrls.has(remoteName)) { + remoteName = `${preferredName}-${suffix}`; + suffix += 1; + } + + yield* runGit("GitCore.ensureRemote.add", input.cwd, ["remote", "add", remoteName, input.url]); + return remoteName; + }); + + const resolveBaseBranchForNoUpstream = Effect.fn("resolveBaseBranchForNoUpstream")(function* ( + cwd: string, + branch: string, + ) { + const configuredBaseBranch = yield* runGitStdout( + "GitCore.resolveBaseBranchForNoUpstream.config", + cwd, + ["config", "--get", `branch.${branch}.gh-merge-base`], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + + const primaryRemoteName = yield* resolvePrimaryRemoteName(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + const defaultBranch = + primaryRemoteName === null ? null : yield* resolveDefaultBranchName(cwd, primaryRemoteName); + const candidates = [ + configuredBaseBranch.length > 0 ? configuredBaseBranch : null, + defaultBranch, + ...DEFAULT_BASE_BRANCH_CANDIDATES, + ]; + + for (const candidate of candidates) { + if (!candidate) { + continue; + } + + const remotePrefix = + primaryRemoteName && primaryRemoteName !== "origin" ? `${primaryRemoteName}/` : null; + const normalizedCandidate = candidate.startsWith("origin/") + ? candidate.slice("origin/".length) + : remotePrefix && candidate.startsWith(remotePrefix) + ? candidate.slice(remotePrefix.length) + : candidate; + if (normalizedCandidate.length === 0 || normalizedCandidate === branch) { + continue; + } + + if (yield* branchExists(cwd, normalizedCandidate)) { + return normalizedCandidate; + } + + if ( + primaryRemoteName && + (yield* remoteBranchExists(cwd, primaryRemoteName, normalizedCandidate)) + ) { + return `${primaryRemoteName}/${normalizedCandidate}`; + } + } + + return null; + }); + + const computeAheadCountAgainstBase = Effect.fn("computeAheadCountAgainstBase")(function* ( + cwd: string, + branch: string, + ) { + const baseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch); + if (!baseBranch) { + return 0; + } + + const result = yield* executeGit( + "GitCore.computeAheadCountAgainstBase", + cwd, + ["rev-list", "--count", `${baseBranch}..HEAD`], + { allowNonZeroExit: true }, + ); + if (result.code !== 0) { + return 0; + } + + const parsed = Number.parseInt(result.stdout.trim(), 10); + return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; + }); + + const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) { + const branchRecency = yield* executeGit( + "GitCore.readBranchRecency", + cwd, + [ + "for-each-ref", + "--format=%(refname:short)%09%(committerdate:unix)", + "refs/heads", + "refs/remotes", + ], + { + timeoutMs: 15_000, + allowNonZeroExit: true, + }, + ); + + const branchLastCommit = new Map(); + if (branchRecency.code !== 0) { + return branchLastCommit; + } + + for (const line of branchRecency.stdout.split("\n")) { + if (line.length === 0) { + continue; + } + const [name, lastCommitRaw] = line.split("\t"); + if (!name) { + continue; + } + const lastCommit = Number.parseInt(lastCommitRaw ?? "0", 10); + branchLastCommit.set(name, Number.isFinite(lastCommit) ? lastCommit : 0); + } + + return branchLastCommit; + }); + + const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true })); + + const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all( + [ + runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]), + runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]), + runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]), + ], + { concurrency: "unbounded" }, + ); + + let branch: string | null = null; + let upstreamRef: string | null = null; + let aheadCount = 0; + let behindCount = 0; + let hasWorkingTreeChanges = false; + const changedFilesWithoutNumstat = new Set(); + + for (const line of statusStdout.split(/\r?\n/g)) { + if (line.startsWith("# branch.head ")) { + const value = line.slice("# branch.head ".length).trim(); + branch = value.startsWith("(") ? null : value; + continue; + } + if (line.startsWith("# branch.upstream ")) { + const value = line.slice("# branch.upstream ".length).trim(); + upstreamRef = value.length > 0 ? value : null; + continue; + } + if (line.startsWith("# branch.ab ")) { + const value = line.slice("# branch.ab ".length).trim(); + const parsed = parseBranchAb(value); + aheadCount = parsed.ahead; + behindCount = parsed.behind; + continue; + } + if (line.trim().length > 0 && !line.startsWith("#")) { + hasWorkingTreeChanges = true; + const pathValue = parsePorcelainPath(line); + if (pathValue) changedFilesWithoutNumstat.add(pathValue); + } + } + + if (!upstreamRef && branch) { + aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(0)), + ); + behindCount = 0; + } + + const stagedEntries = parseNumstatEntries(stagedNumstatStdout); + const unstagedEntries = parseNumstatEntries(unstagedNumstatStdout); + const fileStatMap = new Map(); + for (const entry of [...stagedEntries, ...unstagedEntries]) { + const existing = fileStatMap.get(entry.path) ?? { insertions: 0, deletions: 0 }; + existing.insertions += entry.insertions; + existing.deletions += entry.deletions; + fileStatMap.set(entry.path, existing); + } + + let insertions = 0; + let deletions = 0; + const files = Array.from(fileStatMap.entries()) + .map(([filePath, stat]) => { + insertions += stat.insertions; + deletions += stat.deletions; + return { path: filePath, insertions: stat.insertions, deletions: stat.deletions }; + }) + .toSorted((a, b) => a.path.localeCompare(b.path)); + + for (const filePath of changedFilesWithoutNumstat) { + if (fileStatMap.has(filePath)) continue; + files.push({ path: filePath, insertions: 0, deletions: 0 }); + } + files.sort((a, b) => a.path.localeCompare(b.path)); + + return { + branch, + upstreamRef, + hasWorkingTreeChanges, + workingTree: { + files, + insertions, + deletions, + }, + hasUpstream: upstreamRef !== null, + aheadCount, + behindCount, + }; + }); + + const status: GitCoreShape["status"] = (input) => + statusDetails(input.cwd).pipe( + Effect.map((details) => ({ + branch: details.branch, + hasWorkingTreeChanges: details.hasWorkingTreeChanges, + workingTree: details.workingTree, + hasUpstream: details.hasUpstream, + aheadCount: details.aheadCount, + behindCount: details.behindCount, + pr: null, + })), + ); + + const prepareCommitContext: GitCoreShape["prepareCommitContext"] = Effect.fn( + "prepareCommitContext", + )(function* (cwd, filePaths) { + if (filePaths && filePaths.length > 0) { + yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe( + Effect.catch(() => Effect.void), + ); + yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [ + "add", + "-A", + "--", + ...filePaths, + ]); + } else { + yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]); + } + + const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [ + "diff", + "--cached", + "--name-status", + ]).pipe(Effect.map((stdout) => stdout.trim())); + if (stagedSummary.length === 0) { + return null; + } + + const stagedPatch = yield* runGitStdoutWithOptions( + "GitCore.prepareCommitContext.stagedPatch", + cwd, + ["diff", "--cached", "--patch", "--minimal"], + { + maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + return { + stagedSummary, + stagedPatch, + }; + }); + + const commit: GitCoreShape["commit"] = Effect.fn("commit")(function* ( + cwd, + subject, + body, + options?: GitCommitOptions, + ) { + const args = ["commit", "-m", subject]; + const trimmedBody = body.trim(); + if (trimmedBody.length > 0) { + args.push("-m", trimmedBody); + } + const progress = + options?.progress?.onOutputLine === undefined + ? options?.progress + : { + ...options.progress, + onStdoutLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? Effect.void, + onStderrLine: (line: string) => + options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? Effect.void, + }; + yield* executeGit("GitCore.commit.commit", cwd, args, { + ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), + ...(progress ? { progress } : {}), + }).pipe(Effect.asVoid); + const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ + "rev-parse", + "HEAD", + ]).pipe(Effect.map((stdout) => stdout.trim())); + + return { commitSha }; + }); + + const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = Effect.fn("pushCurrentBranch")( + function* (cwd, fallbackBranch) { + const details = yield* statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pushCurrentBranch", cwd, - ["diff", "--cached", "--patch", "--minimal"], - { - maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, + ["push"], + "Cannot push from detached HEAD.", ); + } - return { - stagedSummary, - stagedPatch, - }; - }); - - const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) => - Effect.gen(function* () { - const args = ["commit", "-m", subject]; - const trimmedBody = body.trim(); - if (trimmedBody.length > 0) { - args.push("-m", trimmedBody); + const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; + if (hasNoLocalDelta) { + if (details.hasUpstream) { + return { + status: "skipped_up_to_date" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + }; } - const progress = options?.progress - ? { - ...(options.progress.onOutputLine - ? { - onStdoutLine: (line: string) => - options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ?? - Effect.void, - onStderrLine: (line: string) => - options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ?? - Effect.void, - } - : {}), - ...(options.progress.onHookStarted - ? { onHookStarted: options.progress.onHookStarted } - : {}), - ...(options.progress.onHookFinished - ? { onHookFinished: options.progress.onHookFinished } - : {}), - } - : null; - yield* executeGit("GitCore.commit.commit", cwd, args, { - ...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), - ...(progress ? { progress } : {}), - }).pipe(Effect.asVoid); - const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [ - "rev-parse", - "HEAD", - ]).pipe(Effect.map((stdout) => stdout.trim())); - return { commitSha }; - }); + const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (comparableBaseBranch) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (!publishRemoteName) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } - const pushCurrentBranch: GitCoreShape["pushCurrentBranch"] = (cwd, fallbackBranch) => - Effect.gen(function* () { - const details = yield* statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { + const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( + Effect.catch(() => Effect.succeed(false)), + ); + if (hasRemoteBranch) { + return { + status: "skipped_up_to_date" as const, + branch, + }; + } + } + } + + if (!details.hasUpstream) { + const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); + if (!publishRemoteName) { return yield* createGitCommandError( "GitCore.pushCurrentBranch", cwd, ["push"], - "Cannot push from detached HEAD.", + "Cannot push because no git remote is configured for this repository.", ); } - - const hasNoLocalDelta = details.aheadCount === 0 && details.behindCount === 0; - if (hasNoLocalDelta) { - if (details.hasUpstream) { - return { - status: "skipped_up_to_date" as const, - branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), - }; - } - - const comparableBaseBranch = yield* resolveBaseBranchForNoUpstream(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (comparableBaseBranch) { - const publishRemoteName = yield* resolvePushRemoteName(cwd, branch).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (!publishRemoteName) { - return { - status: "skipped_up_to_date" as const, - branch, - }; - } - - const hasRemoteBranch = yield* remoteBranchExists(cwd, publishRemoteName, branch).pipe( - Effect.catch(() => Effect.succeed(false)), - ); - if (hasRemoteBranch) { - return { - status: "skipped_up_to_date" as const, - branch, - }; - } - } - } - - if (!details.hasUpstream) { - const publishRemoteName = yield* resolvePushRemoteName(cwd, branch); - if (!publishRemoteName) { - return yield* createGitCommandError( - "GitCore.pushCurrentBranch", - cwd, - ["push"], - "Cannot push because no git remote is configured for this repository.", - ); - } - yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ - "push", - "-u", - publishRemoteName, - branch, - ]); - return { - status: "pushed" as const, - branch, - upstreamBranch: `${publishRemoteName}/${branch}`, - setUpstream: true, - }; - } - - const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( - Effect.catch(() => Effect.succeed(null)), - ); - if (currentUpstream) { - yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ - "push", - currentUpstream.remoteName, - `HEAD:${currentUpstream.upstreamBranch}`, - ]); - return { - status: "pushed" as const, - branch, - upstreamBranch: currentUpstream.upstreamRef, - setUpstream: false, - }; - } - - yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); + yield* runGit("GitCore.pushCurrentBranch.pushWithUpstream", cwd, [ + "push", + "-u", + publishRemoteName, + branch, + ]); return { status: "pushed" as const, branch, - ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + upstreamBranch: `${publishRemoteName}/${branch}`, + setUpstream: true, + }; + } + + const currentUpstream = yield* resolveCurrentUpstream(cwd).pipe( + Effect.catch(() => Effect.succeed(null)), + ); + if (currentUpstream) { + yield* runGit("GitCore.pushCurrentBranch.pushUpstream", cwd, [ + "push", + currentUpstream.remoteName, + `HEAD:${currentUpstream.upstreamBranch}`, + ]); + return { + status: "pushed" as const, + branch, + upstreamBranch: currentUpstream.upstreamRef, setUpstream: false, }; - }); + } - const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = (cwd) => - Effect.gen(function* () { - const details = yield* statusDetails(cwd); - const branch = details.branch; - if (!branch) { - return yield* createGitCommandError( - "GitCore.pullCurrentBranch", - cwd, - ["pull", "--ff-only"], - "Cannot pull from detached HEAD.", - ); - } - if (!details.hasUpstream) { - return yield* createGitCommandError( - "GitCore.pullCurrentBranch", - cwd, - ["pull", "--ff-only"], - "Current branch has no upstream configured. Push with upstream first.", - ); - } - const beforeSha = yield* runGitStdout( - "GitCore.pullCurrentBranch.beforeSha", + yield* runGit("GitCore.pushCurrentBranch.push", cwd, ["push"]); + return { + status: "pushed" as const, + branch, + ...(details.upstreamRef ? { upstreamBranch: details.upstreamRef } : {}), + setUpstream: false, + }; + }, + ); + + const pullCurrentBranch: GitCoreShape["pullCurrentBranch"] = Effect.fn("pullCurrentBranch")( + function* (cwd) { + const details = yield* statusDetails(cwd); + const branch = details.branch; + if (!branch) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", cwd, - ["rev-parse", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { - timeoutMs: 30_000, - fallbackErrorMessage: "git pull failed", - }); - const afterSha = yield* runGitStdout( - "GitCore.pullCurrentBranch.afterSha", - cwd, - ["rev-parse", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - - const refreshed = yield* statusDetails(cwd); - return { - status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", - branch, - upstreamBranch: refreshed.upstreamRef, - }; - }); - - const readRangeContext: GitCoreShape["readRangeContext"] = (cwd, baseBranch) => - Effect.gen(function* () { - const range = `${baseBranch}..HEAD`; - const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( - [ - runGitStdoutWithOptions( - "GitCore.readRangeContext.log", - cwd, - ["log", "--oneline", range], - { - maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, - ), - runGitStdoutWithOptions( - "GitCore.readRangeContext.diffStat", - cwd, - ["diff", "--stat", range], - { - maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, - ), - runGitStdoutWithOptions( - "GitCore.readRangeContext.diffPatch", - cwd, - ["diff", "--patch", "--minimal", range], - { - maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, - truncateOutputAtMaxBytes: true, - }, - ), - ], - { concurrency: "unbounded" }, + ["pull", "--ff-only"], + "Cannot pull from detached HEAD.", ); - - return { - commitSummary, - diffSummary, - diffPatch, - }; + } + if (!details.hasUpstream) { + return yield* createGitCommandError( + "GitCore.pullCurrentBranch", + cwd, + ["pull", "--ff-only"], + "Current branch has no upstream configured. Push with upstream first.", + ); + } + const beforeSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.beforeSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); + yield* executeGit("GitCore.pullCurrentBranch.pull", cwd, ["pull", "--ff-only"], { + timeoutMs: 30_000, + fallbackErrorMessage: "git pull failed", }); + const afterSha = yield* runGitStdout( + "GitCore.pullCurrentBranch.afterSha", + cwd, + ["rev-parse", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim())); - const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => - runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( - Effect.map((stdout) => stdout.trim()), - Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + const refreshed = yield* statusDetails(cwd); + return { + status: beforeSha.length > 0 && beforeSha === afterSha ? "skipped_up_to_date" : "pulled", + branch, + upstreamBranch: refreshed.upstreamRef, + }; + }, + ); + + const readRangeContext: GitCoreShape["readRangeContext"] = Effect.fn("readRangeContext")( + function* (cwd, baseBranch) { + const range = `${baseBranch}..HEAD`; + const [commitSummary, diffSummary, diffPatch] = yield* Effect.all( + [ + runGitStdoutWithOptions( + "GitCore.readRangeContext.log", + cwd, + ["log", "--oneline", range], + { + maxOutputBytes: RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffStat", + cwd, + ["diff", "--stat", range], + { + maxOutputBytes: RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + runGitStdoutWithOptions( + "GitCore.readRangeContext.diffPatch", + cwd, + ["diff", "--patch", "--minimal", range], + { + maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ), + ], + { concurrency: "unbounded" }, ); - const listBranches: GitCoreShape["listBranches"] = (input) => - Effect.gen(function* () { - const branchRecencyPromise = readBranchRecency(input.cwd).pipe( - Effect.catch(() => Effect.succeed(new Map())), - ); - const localBranchResult = yield* executeGit( - "GitCore.listBranches.branchNoColor", - input.cwd, - ["branch", "--no-color"], - { - timeoutMs: 10_000, - allowNonZeroExit: true, - }, - ); + return { + commitSummary, + diffSummary, + diffPatch, + }; + }, + ); - if (localBranchResult.code !== 0) { - const stderr = localBranchResult.stderr.trim(); - if (stderr.toLowerCase().includes("not a git repository")) { - return { branches: [], isRepo: false, hasOriginRemote: false }; - } - return yield* createGitCommandError( - "GitCore.listBranches", + const readConfigValue: GitCoreShape["readConfigValue"] = (cwd, key) => + runGitStdout("GitCore.readConfigValue", cwd, ["config", "--get", key], true).pipe( + Effect.map((stdout) => stdout.trim()), + Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), + ); + + const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { + const branchRecencyPromise = readBranchRecency(input.cwd).pipe( + Effect.catch(() => Effect.succeed(new Map())), + ); + const localBranchResult = yield* executeGit( + "GitCore.listBranches.branchNoColor", + input.cwd, + ["branch", "--no-color"], + { + timeoutMs: 10_000, + allowNonZeroExit: true, + }, + ); + + if (localBranchResult.code !== 0) { + const stderr = localBranchResult.stderr.trim(); + if (stderr.toLowerCase().includes("not a git repository")) { + return { branches: [], isRepo: false, hasOriginRemote: false }; + } + return yield* createGitCommandError( + "GitCore.listBranches", + input.cwd, + ["branch", "--no-color"], + stderr || "git branch failed", + ); + } + + const remoteBranchResultEffect = executeGit( + "GitCore.listBranches.remoteBranches", + input.cwd, + ["branch", "--no-color", "--remotes"], + { + timeoutMs: 10_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); + + const remoteNamesResultEffect = executeGit( + "GitCore.listBranches.remoteNames", + input.cwd, + ["remote"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.catch((error) => + Effect.logWarning( + `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, + ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ), + ); + + const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = + yield* Effect.all( + [ + executeGit( + "GitCore.listBranches.defaultRef", input.cwd, - ["branch", "--no-color"], - stderr || "git branch failed", - ); - } - - const remoteBranchResultEffect = executeGit( - "GitCore.listBranches.remoteBranches", - input.cwd, - ["branch", "--no-color", "--remotes"], - { - timeoutMs: 10_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.catch((error) => - Effect.logWarning( - `GitCore.listBranches: remote branch lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote branch list.`, - ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + ["symbolic-ref", "refs/remotes/origin/HEAD"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, ), - ); - - const remoteNamesResultEffect = executeGit( - "GitCore.listBranches.remoteNames", - input.cwd, - ["remote"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.catch((error) => - Effect.logWarning( - `GitCore.listBranches: remote name lookup failed for ${input.cwd}: ${error.message}. Falling back to an empty remote name list.`, - ).pipe(Effect.as({ code: 1, stdout: "", stderr: "" })), + executeGit( + "GitCore.listBranches.worktreeList", + input.cwd, + ["worktree", "list", "--porcelain"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, ), - ); - - const [defaultRef, worktreeList, remoteBranchResult, remoteNamesResult, branchLastCommit] = - yield* Effect.all( - [ - executeGit( - "GitCore.listBranches.defaultRef", - input.cwd, - ["symbolic-ref", "refs/remotes/origin/HEAD"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), - executeGit( - "GitCore.listBranches.worktreeList", - input.cwd, - ["worktree", "list", "--porcelain"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ), - remoteBranchResultEffect, - remoteNamesResultEffect, - branchRecencyPromise, - ], - { concurrency: "unbounded" }, - ); - - const remoteNames = - remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; - if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { - yield* Effect.logWarning( - `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, - ); - } - if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { - yield* Effect.logWarning( - `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, - ); - } - - const defaultBranch = - defaultRef.code === 0 - ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") - : null; - - const worktreeMap = new Map(); - if (worktreeList.code === 0) { - let currentPath: string | null = null; - for (const line of worktreeList.stdout.split("\n")) { - if (line.startsWith("worktree ")) { - const candidatePath = line.slice("worktree ".length); - const exists = yield* fileSystem.stat(candidatePath).pipe( - Effect.map(() => true), - Effect.catch(() => Effect.succeed(false)), - ); - currentPath = exists ? candidatePath : null; - } else if (line.startsWith("branch refs/heads/") && currentPath) { - worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); - } else if (line === "") { - currentPath = null; - } - } - } - - const localBranches = localBranchResult.stdout - .split("\n") - .map(parseBranchLine) - .filter((branch): branch is { name: string; current: boolean } => branch !== null) - .map((branch) => ({ - name: branch.name, - current: branch.current, - isRemote: false, - isDefault: branch.name === defaultBranch, - worktreePath: worktreeMap.get(branch.name) ?? null, - })) - .toSorted((a, b) => { - const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; - const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; - if (aPriority !== bPriority) return aPriority - bPriority; - - const aLastCommit = branchLastCommit.get(a.name) ?? 0; - const bLastCommit = branchLastCommit.get(b.name) ?? 0; - if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; - return a.name.localeCompare(b.name); - }); - - const remoteBranches = - remoteBranchResult.code === 0 - ? remoteBranchResult.stdout - .split("\n") - .map(parseBranchLine) - .filter((branch): branch is { name: string; current: boolean } => branch !== null) - .map((branch) => { - const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); - const remoteBranch: { - name: string; - current: boolean; - isRemote: boolean; - remoteName?: string; - isDefault: boolean; - worktreePath: string | null; - } = { - name: branch.name, - current: false, - isRemote: true, - isDefault: false, - worktreePath: null, - }; - if (parsedRemoteRef) { - remoteBranch.remoteName = parsedRemoteRef.remoteName; - } - return remoteBranch; - }) - .toSorted((a, b) => { - const aLastCommit = branchLastCommit.get(a.name) ?? 0; - const bLastCommit = branchLastCommit.get(b.name) ?? 0; - if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; - return a.name.localeCompare(b.name); - }) - : []; - - const branches = [...localBranches, ...remoteBranches]; - - return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; - }); - - const createWorktree: GitCoreShape["createWorktree"] = (input) => - Effect.gen(function* () { - const targetBranch = input.newBranch ?? input.branch; - const sanitizedBranch = targetBranch.replace(/\//g, "-"); - const repoName = path.basename(input.cwd); - const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); - const args = input.newBranch - ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] - : ["worktree", "add", worktreePath, input.branch]; - - yield* executeGit("GitCore.createWorktree", input.cwd, args, { - fallbackErrorMessage: "git worktree add failed", - }); - - return { - worktree: { - path: worktreePath, - branch: targetBranch, - }, - }; - }); - - const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = (input) => - Effect.gen(function* () { - const remoteName = yield* resolvePrimaryRemoteName(input.cwd); - yield* executeGit( - "GitCore.fetchPullRequestBranch", - input.cwd, - [ - "fetch", - "--quiet", - "--no-tags", - remoteName, - `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, - ], - { - fallbackErrorMessage: "git fetch pull request branch failed", - }, - ); - }).pipe(Effect.asVoid); - - const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = (input) => - Effect.gen(function* () { - yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ - "fetch", - "--quiet", - "--no-tags", - input.remoteName, - `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, - ]); - - const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); - const targetRef = `${input.remoteName}/${input.remoteBranch}`; - yield* runGit( - "GitCore.fetchRemoteBranch.materialize", - input.cwd, - localBranchAlreadyExists - ? ["branch", "--force", input.localBranch, targetRef] - : ["branch", input.localBranch, targetRef], - ); - }).pipe(Effect.asVoid); - - const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => - runGit("GitCore.setBranchUpstream", input.cwd, [ - "branch", - "--set-upstream-to", - `${input.remoteName}/${input.remoteBranch}`, - input.branch, - ]); - - const removeWorktree: GitCoreShape["removeWorktree"] = (input) => - Effect.gen(function* () { - const args = ["worktree", "remove"]; - if (input.force) { - args.push("--force"); - } - args.push(input.path); - yield* executeGit("GitCore.removeWorktree", input.cwd, args, { - timeoutMs: 15_000, - fallbackErrorMessage: "git worktree remove failed", - }).pipe( - Effect.mapError((error) => - createGitCommandError( - "GitCore.removeWorktree", - input.cwd, - args, - `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, - error, - ), - ), - ); - }); - - const renameBranch: GitCoreShape["renameBranch"] = (input) => - Effect.gen(function* () { - if (input.oldBranch === input.newBranch) { - return { branch: input.newBranch }; - } - const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); - - yield* executeGit( - "GitCore.renameBranch", - input.cwd, - ["branch", "-m", "--", input.oldBranch, targetBranch], - { - timeoutMs: 10_000, - fallbackErrorMessage: "git branch rename failed", - }, - ); - - return { branch: targetBranch }; - }); - - const createBranch: GitCoreShape["createBranch"] = (input) => - executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { - timeoutMs: 10_000, - fallbackErrorMessage: "git branch create failed", - }).pipe(Effect.asVoid); - - const checkoutBranch: GitCoreShape["checkoutBranch"] = (input) => - Effect.gen(function* () { - const [localInputExists, remoteExists] = yield* Effect.all( - [ - executeGit( - "GitCore.checkoutBranch.localInputExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)), - executeGit( - "GitCore.checkoutBranch.remoteExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)), - ], - { concurrency: "unbounded" }, - ); - - const localTrackingBranch = remoteExists - ? yield* executeGit( - "GitCore.checkoutBranch.localTrackingBranch", - input.cwd, - ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe( - Effect.map((result) => - result.code === 0 - ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) - : null, - ), - ) - : null; - - const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); - const localTrackedBranchTargetExists = - remoteExists && localTrackedBranchCandidate - ? yield* executeGit( - "GitCore.checkoutBranch.localTrackedBranchTargetExists", - input.cwd, - ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], - { - timeoutMs: 5_000, - allowNonZeroExit: true, - }, - ).pipe(Effect.map((result) => result.code === 0)) - : false; - - const checkoutArgs = localInputExists - ? ["checkout", input.branch] - : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists - ? ["checkout", input.branch] - : remoteExists && !localTrackingBranch - ? ["checkout", "--track", input.branch] - : remoteExists && localTrackingBranch - ? ["checkout", localTrackingBranch] - : ["checkout", input.branch]; - - yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { - timeoutMs: 10_000, - fallbackErrorMessage: "git checkout failed", - }); - - // Refresh upstream refs in the background so checkout remains responsive. - yield* Effect.forkScoped( - refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), - ); - }); - - const initRepo: GitCoreShape["initRepo"] = (input) => - executeGit("GitCore.initRepo", input.cwd, ["init"], { - timeoutMs: 10_000, - fallbackErrorMessage: "git init failed", - }).pipe(Effect.asVoid); - - const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => - runGitStdout("GitCore.listLocalBranchNames", cwd, [ - "branch", - "--list", - "--format=%(refname:short)", - ]).pipe( - Effect.map((stdout) => - stdout - .split("\n") - .map((line) => line.trim()) - .filter((line) => line.length > 0), - ), + remoteBranchResultEffect, + remoteNamesResultEffect, + branchRecencyPromise, + ], + { concurrency: "unbounded" }, ); - return { - execute, - status, - statusDetails, - prepareCommitContext, - commit, - pushCurrentBranch, - pullCurrentBranch, - readRangeContext, - readConfigValue, - listBranches, - createWorktree, - fetchPullRequestBranch, - ensureRemote, - fetchRemoteBranch, - setBranchUpstream, - removeWorktree, - renameBranch, - createBranch, - checkoutBranch, - initRepo, - listLocalBranchNames, - } satisfies GitCoreShape; + const remoteNames = + remoteNamesResult.code === 0 ? parseRemoteNames(remoteNamesResult.stdout) : []; + if (remoteBranchResult.code !== 0 && remoteBranchResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote branch lookup returned code ${remoteBranchResult.code} for ${input.cwd}: ${remoteBranchResult.stderr.trim()}. Falling back to an empty remote branch list.`, + ); + } + if (remoteNamesResult.code !== 0 && remoteNamesResult.stderr.trim().length > 0) { + yield* Effect.logWarning( + `GitCore.listBranches: remote name lookup returned code ${remoteNamesResult.code} for ${input.cwd}: ${remoteNamesResult.stderr.trim()}. Falling back to an empty remote name list.`, + ); + } + + const defaultBranch = + defaultRef.code === 0 + ? defaultRef.stdout.trim().replace(/^refs\/remotes\/origin\//, "") + : null; + + const worktreeMap = new Map(); + if (worktreeList.code === 0) { + let currentPath: string | null = null; + for (const line of worktreeList.stdout.split("\n")) { + if (line.startsWith("worktree ")) { + const candidatePath = line.slice("worktree ".length); + const exists = yield* fileSystem.stat(candidatePath).pipe( + Effect.map(() => true), + Effect.catch(() => Effect.succeed(false)), + ); + currentPath = exists ? candidatePath : null; + } else if (line.startsWith("branch refs/heads/") && currentPath) { + worktreeMap.set(line.slice("branch refs/heads/".length), currentPath); + } else if (line === "") { + currentPath = null; + } + } + } + + const localBranches = localBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => ({ + name: branch.name, + current: branch.current, + isRemote: false, + isDefault: branch.name === defaultBranch, + worktreePath: worktreeMap.get(branch.name) ?? null, + })) + .toSorted((a, b) => { + const aPriority = a.current ? 0 : a.isDefault ? 1 : 2; + const bPriority = b.current ? 0 : b.isDefault ? 1 : 2; + if (aPriority !== bPriority) return aPriority - bPriority; + + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }); + + const remoteBranches = + remoteBranchResult.code === 0 + ? remoteBranchResult.stdout + .split("\n") + .map(parseBranchLine) + .filter((branch): branch is { name: string; current: boolean } => branch !== null) + .map((branch) => { + const parsedRemoteRef = parseRemoteRefWithRemoteNames(branch.name, remoteNames); + const remoteBranch: { + name: string; + current: boolean; + isRemote: boolean; + remoteName?: string; + isDefault: boolean; + worktreePath: string | null; + } = { + name: branch.name, + current: false, + isRemote: true, + isDefault: false, + worktreePath: null, + }; + if (parsedRemoteRef) { + remoteBranch.remoteName = parsedRemoteRef.remoteName; + } + return remoteBranch; + }) + .toSorted((a, b) => { + const aLastCommit = branchLastCommit.get(a.name) ?? 0; + const bLastCommit = branchLastCommit.get(b.name) ?? 0; + if (aLastCommit !== bLastCommit) return bLastCommit - aLastCommit; + return a.name.localeCompare(b.name); + }) + : []; + + const branches = [...localBranches, ...remoteBranches]; + + return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") }; }); + const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")( + function* (input) { + const targetBranch = input.newBranch ?? input.branch; + const sanitizedBranch = targetBranch.replace(/\//g, "-"); + const repoName = path.basename(input.cwd); + const worktreePath = input.path ?? path.join(worktreesDir, repoName, sanitizedBranch); + const args = input.newBranch + ? ["worktree", "add", "-b", input.newBranch, worktreePath, input.branch] + : ["worktree", "add", worktreePath, input.branch]; + + yield* executeGit("GitCore.createWorktree", input.cwd, args, { + fallbackErrorMessage: "git worktree add failed", + }); + + return { + worktree: { + path: worktreePath, + branch: targetBranch, + }, + }; + }, + ); + + const fetchPullRequestBranch: GitCoreShape["fetchPullRequestBranch"] = Effect.fn( + "fetchPullRequestBranch", + )(function* (input) { + const remoteName = yield* resolvePrimaryRemoteName(input.cwd); + yield* executeGit( + "GitCore.fetchPullRequestBranch", + input.cwd, + [ + "fetch", + "--quiet", + "--no-tags", + remoteName, + `+refs/pull/${input.prNumber}/head:refs/heads/${input.branch}`, + ], + { + fallbackErrorMessage: "git fetch pull request branch failed", + }, + ); + }); + + const fetchRemoteBranch: GitCoreShape["fetchRemoteBranch"] = Effect.fn("fetchRemoteBranch")( + function* (input) { + yield* runGit("GitCore.fetchRemoteBranch.fetch", input.cwd, [ + "fetch", + "--quiet", + "--no-tags", + input.remoteName, + `+refs/heads/${input.remoteBranch}:refs/remotes/${input.remoteName}/${input.remoteBranch}`, + ]); + + const localBranchAlreadyExists = yield* branchExists(input.cwd, input.localBranch); + const targetRef = `${input.remoteName}/${input.remoteBranch}`; + yield* runGit( + "GitCore.fetchRemoteBranch.materialize", + input.cwd, + localBranchAlreadyExists + ? ["branch", "--force", input.localBranch, targetRef] + : ["branch", input.localBranch, targetRef], + ); + }, + ); + + const setBranchUpstream: GitCoreShape["setBranchUpstream"] = (input) => + runGit("GitCore.setBranchUpstream", input.cwd, [ + "branch", + "--set-upstream-to", + `${input.remoteName}/${input.remoteBranch}`, + input.branch, + ]); + + const removeWorktree: GitCoreShape["removeWorktree"] = Effect.fn("removeWorktree")( + function* (input) { + const args = ["worktree", "remove"]; + if (input.force) { + args.push("--force"); + } + args.push(input.path); + yield* executeGit("GitCore.removeWorktree", input.cwd, args, { + timeoutMs: 15_000, + fallbackErrorMessage: "git worktree remove failed", + }).pipe( + Effect.mapError((error) => + createGitCommandError( + "GitCore.removeWorktree", + input.cwd, + args, + `${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`, + error, + ), + ), + ); + }, + ); + + const renameBranch: GitCoreShape["renameBranch"] = Effect.fn("renameBranch")(function* (input) { + if (input.oldBranch === input.newBranch) { + return { branch: input.newBranch }; + } + const targetBranch = yield* resolveAvailableBranchName(input.cwd, input.newBranch); + + yield* executeGit( + "GitCore.renameBranch", + input.cwd, + ["branch", "-m", "--", input.oldBranch, targetBranch], + { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch rename failed", + }, + ); + + return { branch: targetBranch }; + }); + + const createBranch: GitCoreShape["createBranch"] = (input) => + executeGit("GitCore.createBranch", input.cwd, ["branch", input.branch], { + timeoutMs: 10_000, + fallbackErrorMessage: "git branch create failed", + }).pipe(Effect.asVoid); + + const checkoutBranch: GitCoreShape["checkoutBranch"] = Effect.fn("checkoutBranch")( + function* (input) { + const [localInputExists, remoteExists] = yield* Effect.all( + [ + executeGit( + "GitCore.checkoutBranch.localInputExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + executeGit( + "GitCore.checkoutBranch.remoteExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/remotes/${input.branch}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)), + ], + { concurrency: "unbounded" }, + ); + + const localTrackingBranch = remoteExists + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackingBranch", + input.cwd, + ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe( + Effect.map((result) => + result.code === 0 + ? parseTrackingBranchByUpstreamRef(result.stdout, input.branch) + : null, + ), + ) + : null; + + const localTrackedBranchCandidate = deriveLocalBranchNameFromRemoteRef(input.branch); + const localTrackedBranchTargetExists = + remoteExists && localTrackedBranchCandidate + ? yield* executeGit( + "GitCore.checkoutBranch.localTrackedBranchTargetExists", + input.cwd, + ["show-ref", "--verify", "--quiet", `refs/heads/${localTrackedBranchCandidate}`], + { + timeoutMs: 5_000, + allowNonZeroExit: true, + }, + ).pipe(Effect.map((result) => result.code === 0)) + : false; + + const checkoutArgs = localInputExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch && localTrackedBranchTargetExists + ? ["checkout", input.branch] + : remoteExists && !localTrackingBranch + ? ["checkout", "--track", input.branch] + : remoteExists && localTrackingBranch + ? ["checkout", localTrackingBranch] + : ["checkout", input.branch]; + + yield* executeGit("GitCore.checkoutBranch.checkout", input.cwd, checkoutArgs, { + timeoutMs: 10_000, + fallbackErrorMessage: "git checkout failed", + }); + + // Refresh upstream refs in the background so checkout remains responsive. + yield* Effect.forkScoped( + refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })), + ); + }, + ); + + const initRepo: GitCoreShape["initRepo"] = (input) => + executeGit("GitCore.initRepo", input.cwd, ["init"], { + timeoutMs: 10_000, + fallbackErrorMessage: "git init failed", + }).pipe(Effect.asVoid); + + const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) => + runGitStdout("GitCore.listLocalBranchNames", cwd, [ + "branch", + "--list", + "--format=%(refname:short)", + ]).pipe( + Effect.map((stdout) => + stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0), + ), + ); + + return { + execute, + status, + statusDetails, + prepareCommitContext, + commit, + pushCurrentBranch, + pullCurrentBranch, + readRangeContext, + readConfigValue, + listBranches, + createWorktree, + fetchPullRequestBranch, + ensureRemote, + fetchRemoteBranch, + setBranchUpstream, + removeWorktree, + renameBranch, + createBranch, + checkoutBranch, + initRepo, + listLocalBranchNames, + } satisfies GitCoreShape; +}); + export const GitCoreLive = Layer.effect(GitCore, makeGitCore()); diff --git a/apps/server/src/git/Layers/GitManager.test.ts b/apps/server/src/git/Layers/GitManager.test.ts index d13c389fc8..db82ea4c72 100644 --- a/apps/server/src/git/Layers/GitManager.test.ts +++ b/apps/server/src/git/Layers/GitManager.test.ts @@ -525,7 +525,7 @@ function makeManager(input?: { serverSettingsLayer, ).pipe(Layer.provideMerge(NodeServices.layer)); - return makeGitManager.pipe( + return makeGitManager().pipe( Effect.provide(managerLayer), Effect.map((manager) => ({ manager, ghCalls })), ); diff --git a/apps/server/src/git/Layers/GitManager.ts b/apps/server/src/git/Layers/GitManager.ts index 6fd86e1d58..dc082674b7 100644 --- a/apps/server/src/git/Layers/GitManager.ts +++ b/apps/server/src/git/Layers/GitManager.ts @@ -1,8 +1,13 @@ import { randomUUID } from "node:crypto"; import { realpathSync } from "node:fs"; -import { Effect, FileSystem, Layer, Path } from "effect"; -import { GitActionProgressEvent, GitActionProgressPhase, ModelSelection } from "@t3tools/contracts"; +import { Effect, FileSystem, Layer, Option, Path, Ref } from "effect"; +import { + GitActionProgressEvent, + GitActionProgressPhase, + GitRunStackedActionResult, + ModelSelection, +} from "@t3tools/contracts"; import { resolveAutoFeatureBranchName, sanitizeBranchFragment, @@ -20,6 +25,7 @@ import { GitCore } from "../Services/GitCore.ts"; import { GitHubCli } from "../Services/GitHubCli.ts"; import { TextGeneration } from "../Services/TextGeneration.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; +import type { GitManagerServiceError } from "../Errors.ts"; const COMMIT_TIMEOUT_MS = 10 * 60_000; const MAX_PROGRESS_TEXT_LENGTH = 500; @@ -355,7 +361,7 @@ function toPullRequestHeadRemoteInfo(pr: { }; } -export const makeGitManager = Effect.gen(function* () { +export const makeGitManager = Effect.fn("makeGitManager")(function* () { const gitCore = yield* GitCore; const gitHubCli = yield* GitHubCli; const textGeneration = yield* TextGeneration; @@ -384,12 +390,12 @@ export const makeGitManager = Effect.gen(function* () { }; }; - const configurePullRequestHeadUpstream = ( - cwd: string, - pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, - localBranch = pullRequest.headBranch, - ) => - Effect.gen(function* () { + const configurePullRequestHeadUpstreamBase = Effect.fn("configurePullRequestHeadUpstream")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; if (repositoryNameWithOwner.length === 0) { return; @@ -417,7 +423,15 @@ export const makeGitManager = Effect.gen(function* () { remoteName, remoteBranch: pullRequest.headBranch, }); - }).pipe( + }, + ); + + const configurePullRequestHeadUpstream = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + configurePullRequestHeadUpstreamBase(cwd, pullRequest, localBranch).pipe( Effect.catch((error) => Effect.logWarning( `GitManager.configurePullRequestHeadUpstream: failed to configure upstream for ${localBranch} -> ${pullRequest.headBranch} in ${cwd}: ${error.message}`, @@ -425,12 +439,12 @@ export const makeGitManager = Effect.gen(function* () { ), ); - const materializePullRequestHeadBranch = ( - cwd: string, - pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, - localBranch = pullRequest.headBranch, - ) => - Effect.gen(function* () { + const materializePullRequestHeadBranchBase = Effect.fn("materializePullRequestHeadBranch")( + function* ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) { const repositoryNameWithOwner = resolveHeadRepositoryNameWithOwner(pullRequest) ?? ""; if (repositoryNameWithOwner.length === 0) { @@ -470,7 +484,15 @@ export const makeGitManager = Effect.gen(function* () { remoteName, remoteBranch: pullRequest.headBranch, }); - }).pipe( + }, + ); + + const materializePullRequestHeadBranch = ( + cwd: string, + pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo, + localBranch = pullRequest.headBranch, + ) => + materializePullRequestHeadBranchBase(cwd, pullRequest, localBranch).pipe( Effect.catch(() => gitCore.fetchPullRequestBranch({ cwd, @@ -487,208 +509,211 @@ export const makeGitManager = Effect.gen(function* () { const readConfigValueNullable = (cwd: string, key: string) => gitCore.readConfigValue(cwd, key).pipe(Effect.catch(() => Effect.succeed(null))); - const resolveRemoteRepositoryContext = (cwd: string, remoteName: string | null) => - Effect.gen(function* () { - if (!remoteName) { - return { - repositoryNameWithOwner: null, - ownerLogin: null, - }; - } - - const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`); - const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl); + const resolveRemoteRepositoryContext = Effect.fn("resolveRemoteRepositoryContext")(function* ( + cwd: string, + remoteName: string | null, + ) { + if (!remoteName) { return { - repositoryNameWithOwner, - ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner), + repositoryNameWithOwner: null, + ownerLogin: null, }; - }); + } - const resolveBranchHeadContext = ( + const remoteUrl = yield* readConfigValueNullable(cwd, `remote.${remoteName}.url`); + const repositoryNameWithOwner = parseGitHubRepositoryNameWithOwnerFromRemoteUrl(remoteUrl); + return { + repositoryNameWithOwner, + ownerLogin: parseRepositoryOwnerLogin(repositoryNameWithOwner), + }; + }); + + const resolveBranchHeadContext = Effect.fn("resolveBranchHeadContext")(function* ( cwd: string, details: { branch: string; upstreamRef: string | null }, - ) => - Effect.gen(function* () { - const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); - const headBranchFromUpstream = details.upstreamRef - ? extractBranchFromRef(details.upstreamRef) - : ""; - const headBranch = - headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; + ) { + const remoteName = yield* readConfigValueNullable(cwd, `branch.${details.branch}.remote`); + const headBranchFromUpstream = details.upstreamRef + ? extractBranchFromRef(details.upstreamRef) + : ""; + const headBranch = headBranchFromUpstream.length > 0 ? headBranchFromUpstream : details.branch; - const [remoteRepository, originRepository] = yield* Effect.all( - [ - resolveRemoteRepositoryContext(cwd, remoteName), - resolveRemoteRepositoryContext(cwd, "origin"), - ], - { concurrency: "unbounded" }, - ); + const [remoteRepository, originRepository] = yield* Effect.all( + [ + resolveRemoteRepositoryContext(cwd, remoteName), + resolveRemoteRepositoryContext(cwd, "origin"), + ], + { concurrency: "unbounded" }, + ); - const isCrossRepository = - remoteRepository.repositoryNameWithOwner !== null && - originRepository.repositoryNameWithOwner !== null - ? remoteRepository.repositoryNameWithOwner.toLowerCase() !== - originRepository.repositoryNameWithOwner.toLowerCase() - : remoteName !== null && - remoteName !== "origin" && - remoteRepository.repositoryNameWithOwner !== null; + const isCrossRepository = + remoteRepository.repositoryNameWithOwner !== null && + originRepository.repositoryNameWithOwner !== null + ? remoteRepository.repositoryNameWithOwner.toLowerCase() !== + originRepository.repositoryNameWithOwner.toLowerCase() + : remoteName !== null && + remoteName !== "origin" && + remoteRepository.repositoryNameWithOwner !== null; - const ownerHeadSelector = - remoteRepository.ownerLogin && headBranch.length > 0 - ? `${remoteRepository.ownerLogin}:${headBranch}` - : null; - const remoteAliasHeadSelector = - remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null; - const shouldProbeRemoteOwnedSelectors = - isCrossRepository || (remoteName !== null && remoteName !== "origin"); + const ownerHeadSelector = + remoteRepository.ownerLogin && headBranch.length > 0 + ? `${remoteRepository.ownerLogin}:${headBranch}` + : null; + const remoteAliasHeadSelector = + remoteName && headBranch.length > 0 ? `${remoteName}:${headBranch}` : null; + const shouldProbeRemoteOwnedSelectors = + isCrossRepository || (remoteName !== null && remoteName !== "origin"); - const headSelectors: string[] = []; - if (isCrossRepository && shouldProbeRemoteOwnedSelectors) { - appendUnique(headSelectors, ownerHeadSelector); - appendUnique( - headSelectors, - remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, - ); - } - appendUnique(headSelectors, details.branch); - appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); - if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { - appendUnique(headSelectors, ownerHeadSelector); - appendUnique( - headSelectors, - remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, - ); - } - - return { - localBranch: details.branch, - headBranch, + const headSelectors: string[] = []; + if (isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( headSelectors, - preferredHeadSelector: - ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch, - remoteName, - headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner, - headRepositoryOwnerLogin: remoteRepository.ownerLogin, - isCrossRepository, - } satisfies BranchHeadContext; - }); + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } + appendUnique(headSelectors, details.branch); + appendUnique(headSelectors, headBranch !== details.branch ? headBranch : null); + if (!isCrossRepository && shouldProbeRemoteOwnedSelectors) { + appendUnique(headSelectors, ownerHeadSelector); + appendUnique( + headSelectors, + remoteAliasHeadSelector !== ownerHeadSelector ? remoteAliasHeadSelector : null, + ); + } - const findOpenPr = (cwd: string, headSelectors: ReadonlyArray) => - Effect.gen(function* () { - for (const headSelector of headSelectors) { - const pullRequests = yield* gitHubCli.listOpenPullRequests({ - cwd, - headSelector, - limit: 1, - }); + return { + localBranch: details.branch, + headBranch, + headSelectors, + preferredHeadSelector: + ownerHeadSelector && isCrossRepository ? ownerHeadSelector : headBranch, + remoteName, + headRepositoryNameWithOwner: remoteRepository.repositoryNameWithOwner, + headRepositoryOwnerLogin: remoteRepository.ownerLogin, + isCrossRepository, + } satisfies BranchHeadContext; + }); - const [firstPullRequest] = pullRequests; - if (firstPullRequest) { - return { - number: firstPullRequest.number, - title: firstPullRequest.title, - url: firstPullRequest.url, - baseRefName: firstPullRequest.baseRefName, - headRefName: firstPullRequest.headRefName, - state: "open", - updatedAt: null, - } satisfies PullRequestInfo; - } - } - - return null; - }); - - const findLatestPr = (cwd: string, details: { branch: string; upstreamRef: string | null }) => - Effect.gen(function* () { - const headContext = yield* resolveBranchHeadContext(cwd, details); - const parsedByNumber = new Map(); - - for (const headSelector of headContext.headSelectors) { - const stdout = yield* gitHubCli - .execute({ - cwd, - args: [ - "pr", - "list", - "--head", - headSelector, - "--state", - "all", - "--limit", - "20", - "--json", - "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", - ], - }) - .pipe(Effect.map((result) => result.stdout)); - - const raw = stdout.trim(); - if (raw.length === 0) { - continue; - } - - const parsedJson = yield* Effect.try({ - try: () => JSON.parse(raw) as unknown, - catch: (cause) => - gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), - }); - - for (const pr of parsePullRequestList(parsedJson)) { - parsedByNumber.set(pr.number, pr); - } - } - - const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => { - const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; - const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; - return right - left; + const findOpenPr = Effect.fn("findOpenPr")(function* ( + cwd: string, + headSelectors: ReadonlyArray, + ) { + for (const headSelector of headSelectors) { + const pullRequests = yield* gitHubCli.listOpenPullRequests({ + cwd, + headSelector, + limit: 1, }); - const latestOpenPr = parsed.find((pr) => pr.state === "open"); - if (latestOpenPr) { - return latestOpenPr; + const [firstPullRequest] = pullRequests; + if (firstPullRequest) { + return { + number: firstPullRequest.number, + title: firstPullRequest.title, + url: firstPullRequest.url, + baseRefName: firstPullRequest.baseRefName, + headRefName: firstPullRequest.headRefName, + state: "open", + updatedAt: null, + } satisfies PullRequestInfo; } - return parsed[0] ?? null; + } + + return null; + }); + + const findLatestPr = Effect.fn("findLatestPr")(function* ( + cwd: string, + details: { branch: string; upstreamRef: string | null }, + ) { + const headContext = yield* resolveBranchHeadContext(cwd, details); + const parsedByNumber = new Map(); + + for (const headSelector of headContext.headSelectors) { + const stdout = yield* gitHubCli + .execute({ + cwd, + args: [ + "pr", + "list", + "--head", + headSelector, + "--state", + "all", + "--limit", + "20", + "--json", + "number,title,url,baseRefName,headRefName,state,mergedAt,updatedAt", + ], + }) + .pipe(Effect.map((result) => result.stdout)); + + const raw = stdout.trim(); + if (raw.length === 0) { + continue; + } + + const parsedJson = yield* Effect.try({ + try: () => JSON.parse(raw) as unknown, + catch: (cause) => + gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause), + }); + + for (const pr of parsePullRequestList(parsedJson)) { + parsedByNumber.set(pr.number, pr); + } + } + + const parsed = Array.from(parsedByNumber.values()).toSorted((a, b) => { + const left = a.updatedAt ? Date.parse(a.updatedAt) : 0; + const right = b.updatedAt ? Date.parse(b.updatedAt) : 0; + return right - left; }); - const resolveBaseBranch = ( + const latestOpenPr = parsed.find((pr) => pr.state === "open"); + if (latestOpenPr) { + return latestOpenPr; + } + return parsed[0] ?? null; + }); + + const resolveBaseBranch = Effect.fn("resolveBaseBranch")(function* ( cwd: string, branch: string, upstreamRef: string | null, headContext: Pick, - ) => - Effect.gen(function* () { - const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); - if (configured) return configured; + ) { + const configured = yield* gitCore.readConfigValue(cwd, `branch.${branch}.gh-merge-base`); + if (configured) return configured; - if (upstreamRef && !headContext.isCrossRepository) { - const upstreamBranch = extractBranchFromRef(upstreamRef); - if (upstreamBranch.length > 0 && upstreamBranch !== branch) { - return upstreamBranch; - } + if (upstreamRef && !headContext.isCrossRepository) { + const upstreamBranch = extractBranchFromRef(upstreamRef); + if (upstreamBranch.length > 0 && upstreamBranch !== branch) { + return upstreamBranch; } + } - const defaultFromGh = yield* gitHubCli - .getDefaultBranch({ cwd }) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (defaultFromGh) { - return defaultFromGh; - } + const defaultFromGh = yield* gitHubCli + .getDefaultBranch({ cwd }) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (defaultFromGh) { + return defaultFromGh; + } - return "main"; - }); + return "main"; + }); - const resolveCommitAndBranchSuggestion = (input: { - cwd: string; - branch: string | null; - commitMessage?: string; - /** When true, also produce a semantic feature branch name. */ - includeBranch?: boolean; - filePaths?: readonly string[]; - modelSelection: ModelSelection; - }) => - Effect.gen(function* () { + const resolveCommitAndBranchSuggestion = Effect.fn("resolveCommitAndBranchSuggestion")( + function* (input: { + cwd: string; + branch: string | null; + commitMessage?: string; + /** When true, also produce a semantic feature branch name. */ + includeBranch?: boolean; + filePaths?: readonly string[]; + modelSelection: ModelSelection; + }) { const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths); if (!context) { return null; @@ -723,9 +748,10 @@ export const makeGitManager = Effect.gen(function* () { ...(generated.branch !== undefined ? { branch: generated.branch } : {}), commitMessage: formatCommitMessage(generated.subject, generated.body), }; - }); + }, + ); - const runCommitStep = ( + const runCommitStep = Effect.fn("runCommitStep")(function* ( modelSelection: ModelSelection, cwd: string, action: "commit" | "commit_push" | "commit_push_pr", @@ -735,196 +761,198 @@ export const makeGitManager = Effect.gen(function* () { filePaths?: readonly string[], progressReporter?: GitActionProgressReporter, actionId?: string, - ) => - Effect.gen(function* () { - const emit = (event: GitActionProgressPayload) => - progressReporter && actionId - ? progressReporter.publish({ - actionId, - cwd, - action, - ...event, - } as GitActionProgressEvent) - : Effect.void; + ) { + const emit = (event: GitActionProgressPayload) => + progressReporter && actionId + ? progressReporter.publish({ + actionId, + cwd, + action, + ...event, + } as GitActionProgressEvent) + : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; - if (!suggestion) { - const needsGeneration = !commitMessage?.trim(); - if (needsGeneration) { - yield* emit({ - kind: "phase_started", - phase: "commit", - label: "Generating commit message...", - }); - } - suggestion = yield* resolveCommitAndBranchSuggestion({ - cwd, - branch, - ...(commitMessage ? { commitMessage } : {}), - ...(filePaths ? { filePaths } : {}), - modelSelection, + let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + if (!suggestion) { + const needsGeneration = !commitMessage?.trim(); + if (needsGeneration) { + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Generating commit message...", }); } - if (!suggestion) { - return { status: "skipped_no_changes" as const }; - } - - yield* emit({ - kind: "phase_started", - phase: "commit", - label: "Committing...", + suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + modelSelection, }); + } + if (!suggestion) { + return { status: "skipped_no_changes" as const }; + } - let currentHookName: string | null = null; - const commitProgress = - progressReporter && actionId - ? { - onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => { - const sanitized = sanitizeProgressText(text); - if (!sanitized) { - return Effect.void; - } - return emit({ - kind: "hook_output", - hookName: currentHookName, - stream, - text: sanitized, - }); - }, - onHookStarted: (hookName: string) => { - currentHookName = hookName; - return emit({ - kind: "hook_started", - hookName, - }); - }, - onHookFinished: ({ + yield* emit({ + kind: "phase_started", + phase: "commit", + label: "Committing...", + }); + + let currentHookName: string | null = null; + const commitProgress = + progressReporter && actionId + ? { + onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => { + const sanitized = sanitizeProgressText(text); + if (!sanitized) { + return Effect.void; + } + return emit({ + kind: "hook_output", + hookName: currentHookName, + stream, + text: sanitized, + }); + }, + onHookStarted: (hookName: string) => { + currentHookName = hookName; + return emit({ + kind: "hook_started", + hookName, + }); + }, + onHookFinished: ({ + hookName, + exitCode, + durationMs, + }: { + hookName: string; + exitCode: number | null; + durationMs: number | null; + }) => { + if (currentHookName === hookName) { + currentHookName = null; + } + return emit({ + kind: "hook_finished", hookName, exitCode, durationMs, - }: { - hookName: string; - exitCode: number | null; - durationMs: number | null; - }) => { - if (currentHookName === hookName) { - currentHookName = null; - } - return emit({ - kind: "hook_finished", - hookName, - exitCode, - durationMs, - }); - }, - } - : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - ...(commitProgress ? { progress: commitProgress } : {}), + }); + }, + } + : null; + const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + ...(commitProgress ? { progress: commitProgress } : {}), + }); + if (currentHookName !== null) { + yield* emit({ + kind: "hook_finished", + hookName: currentHookName, + exitCode: 0, + durationMs: null, }); - if (currentHookName !== null) { - yield* emit({ - kind: "hook_finished", - hookName: currentHookName, - exitCode: 0, - durationMs: null, - }); - currentHookName = null; - } - return { - status: "created" as const, - commitSha, - subject: suggestion.subject, - }; + currentHookName = null; + } + return { + status: "created" as const, + commitSha, + subject: suggestion.subject, + }; + }); + + const runPrStep = Effect.fn("runPrStep")(function* ( + modelSelection: ModelSelection, + cwd: string, + fallbackBranch: string | null, + ) { + const details = yield* gitCore.statusDetails(cwd); + const branch = details.branch ?? fallbackBranch; + if (!branch) { + return yield* gitManagerError( + "runPrStep", + "Cannot create a pull request from detached HEAD.", + ); + } + if (!details.hasUpstream) { + return yield* gitManagerError( + "runPrStep", + "Current branch has not been pushed. Push before creating a PR.", + ); + } + + const headContext = yield* resolveBranchHeadContext(cwd, { + branch, + upstreamRef: details.upstreamRef, }); - const runPrStep = (modelSelection: ModelSelection, cwd: string, fallbackBranch: string | null) => - Effect.gen(function* () { - const details = yield* gitCore.statusDetails(cwd); - const branch = details.branch ?? fallbackBranch; - if (!branch) { - return yield* gitManagerError( - "runPrStep", - "Cannot create a pull request from detached HEAD.", - ); - } - if (!details.hasUpstream) { - return yield* gitManagerError( - "runPrStep", - "Current branch has not been pushed. Push before creating a PR.", - ); - } + const existing = yield* findOpenPr(cwd, headContext.headSelectors); + if (existing) { + return { + status: "opened_existing" as const, + url: existing.url, + number: existing.number, + baseBranch: existing.baseRefName, + headBranch: existing.headRefName, + title: existing.title, + }; + } - const headContext = yield* resolveBranchHeadContext(cwd, { - branch, - upstreamRef: details.upstreamRef, - }); + const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); + const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); - const existing = yield* findOpenPr(cwd, headContext.headSelectors); - if (existing) { - return { - status: "opened_existing" as const, - url: existing.url, - number: existing.number, - baseBranch: existing.baseRefName, - headBranch: existing.headRefName, - title: existing.title, - }; - } + const generated = yield* textGeneration.generatePrContent({ + cwd, + baseBranch, + headBranch: headContext.headBranch, + commitSummary: limitContext(rangeContext.commitSummary, 20_000), + diffSummary: limitContext(rangeContext.diffSummary, 20_000), + diffPatch: limitContext(rangeContext.diffPatch, 60_000), + modelSelection, + }); - const baseBranch = yield* resolveBaseBranch(cwd, branch, details.upstreamRef, headContext); - const rangeContext = yield* gitCore.readRangeContext(cwd, baseBranch); - - const generated = yield* textGeneration.generatePrContent({ + const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`); + yield* fileSystem + .writeFileString(bodyFile, generated.body) + .pipe( + Effect.mapError((cause) => + gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), + ), + ); + yield* gitHubCli + .createPullRequest({ cwd, baseBranch, - headBranch: headContext.headBranch, - commitSummary: limitContext(rangeContext.commitSummary, 20_000), - diffSummary: limitContext(rangeContext.diffSummary, 20_000), - diffPatch: limitContext(rangeContext.diffPatch, 60_000), - modelSelection, - }); - - const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`); - yield* fileSystem - .writeFileString(bodyFile, generated.body) - .pipe( - Effect.mapError((cause) => - gitManagerError("runPrStep", "Failed to write pull request body temp file.", cause), - ), - ); - yield* gitHubCli - .createPullRequest({ - cwd, - baseBranch, - headSelector: headContext.preferredHeadSelector, - title: generated.title, - bodyFile, - }) - .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); - - const created = yield* findOpenPr(cwd, headContext.headSelectors); - if (!created) { - return { - status: "created" as const, - baseBranch, - headBranch: headContext.headBranch, - title: generated.title, - }; - } + headSelector: headContext.preferredHeadSelector, + title: generated.title, + bodyFile, + }) + .pipe(Effect.ensuring(fileSystem.remove(bodyFile).pipe(Effect.catch(() => Effect.void)))); + const created = yield* findOpenPr(cwd, headContext.headSelectors); + if (!created) { return { status: "created" as const, - url: created.url, - number: created.number, - baseBranch: created.baseRefName, - headBranch: created.headRefName, - title: created.title, + baseBranch, + headBranch: headContext.headBranch, + title: generated.title, }; - }); + } - const status: GitManagerShape["status"] = Effect.fnUntraced(function* (input) { + return { + status: "created" as const, + url: created.url, + number: created.number, + baseBranch: created.baseRefName, + headBranch: created.headRefName, + title: created.title, + }; + }); + + const status: GitManagerShape["status"] = Effect.fn("status")(function* (input) { const details = yield* gitCore.statusDetails(input.cwd); const pr = @@ -949,7 +977,7 @@ export const makeGitManager = Effect.gen(function* () { }; }); - const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fnUntraced( + const resolvePullRequest: GitManagerShape["resolvePullRequest"] = Effect.fn("resolvePullRequest")( function* (input) { const pullRequest = yield* gitHubCli .getPullRequest({ @@ -962,185 +990,185 @@ export const makeGitManager = Effect.gen(function* () { }, ); - const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fnUntraced( - function* (input) { - const normalizedReference = normalizePullRequestReference(input.reference); - const rootWorktreePath = canonicalizeExistingPath(input.cwd); - const pullRequestSummary = yield* gitHubCli.getPullRequest({ + const preparePullRequestThread: GitManagerShape["preparePullRequestThread"] = Effect.fn( + "preparePullRequestThread", + )(function* (input) { + const normalizedReference = normalizePullRequestReference(input.reference); + const rootWorktreePath = canonicalizeExistingPath(input.cwd); + const pullRequestSummary = yield* gitHubCli.getPullRequest({ + cwd: input.cwd, + reference: normalizedReference, + }); + const pullRequest = toResolvedPullRequest(pullRequestSummary); + + if (input.mode === "local") { + yield* gitHubCli.checkoutPullRequest({ cwd: input.cwd, reference: normalizedReference, + force: true, }); - const pullRequest = toResolvedPullRequest(pullRequestSummary); - - if (input.mode === "local") { - yield* gitHubCli.checkoutPullRequest({ - cwd: input.cwd, - reference: normalizedReference, - force: true, - }); - const details = yield* gitCore.statusDetails(input.cwd); - yield* configurePullRequestHeadUpstream( - input.cwd, - { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - }, - details.branch ?? pullRequest.headBranch, - ); - return { - pullRequest, - branch: details.branch ?? pullRequest.headBranch, - worktreePath: null, - }; - } - - const ensureExistingWorktreeUpstream = (worktreePath: string) => - Effect.gen(function* () { - const details = yield* gitCore.statusDetails(worktreePath); - yield* configurePullRequestHeadUpstream( - worktreePath, - { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - }, - details.branch ?? pullRequest.headBranch, - ); - }); - - const pullRequestWithRemoteInfo = { - ...pullRequest, - ...toPullRequestHeadRemoteInfo(pullRequestSummary), - } as const; - const localPullRequestBranch = - resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo); - - const findLocalHeadBranch = (cwd: string) => - gitCore.listBranches({ cwd }).pipe( - Effect.map((result) => { - const localBranch = result.branches.find( - (branch) => !branch.isRemote && branch.name === localPullRequestBranch, - ); - if (localBranch) { - return localBranch; - } - if (localPullRequestBranch === pullRequest.headBranch) { - return null; - } - return ( - result.branches.find( - (branch) => - !branch.isRemote && - branch.name === pullRequest.headBranch && - branch.worktreePath !== null && - canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath, - ) ?? null - ); - }), - ); - - const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd); - const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath - ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath) - : null; - if ( - existingBranchBeforeFetch?.worktreePath && - existingBranchBeforeFetchPath !== rootWorktreePath - ) { - yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath); - return { - pullRequest, - branch: localPullRequestBranch, - worktreePath: existingBranchBeforeFetch.worktreePath, - }; - } - if (existingBranchBeforeFetchPath === rootWorktreePath) { - return yield* gitManagerError( - "preparePullRequestThread", - "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", - ); - } - - yield* materializePullRequestHeadBranch( + const details = yield* gitCore.statusDetails(input.cwd); + yield* configurePullRequestHeadUpstream( input.cwd, - pullRequestWithRemoteInfo, - localPullRequestBranch, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, ); - - const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd); - const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath - ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath) - : null; - if ( - existingBranchAfterFetch?.worktreePath && - existingBranchAfterFetchPath !== rootWorktreePath - ) { - yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath); - return { - pullRequest, - branch: localPullRequestBranch, - worktreePath: existingBranchAfterFetch.worktreePath, - }; - } - if (existingBranchAfterFetchPath === rootWorktreePath) { - return yield* gitManagerError( - "preparePullRequestThread", - "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", - ); - } - - const worktree = yield* gitCore.createWorktree({ - cwd: input.cwd, - branch: localPullRequestBranch, - path: null, - }); - yield* ensureExistingWorktreeUpstream(worktree.worktree.path); - return { pullRequest, - branch: worktree.worktree.branch, - worktreePath: worktree.worktree.path, + branch: details.branch ?? pullRequest.headBranch, + worktreePath: null, }; - }, - ); + } - const runFeatureBranchStep = ( + const ensureExistingWorktreeUpstream = Effect.fn("ensureExistingWorktreeUpstream")(function* ( + worktreePath: string, + ) { + const details = yield* gitCore.statusDetails(worktreePath); + yield* configurePullRequestHeadUpstream( + worktreePath, + { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + }, + details.branch ?? pullRequest.headBranch, + ); + }); + + const pullRequestWithRemoteInfo = { + ...pullRequest, + ...toPullRequestHeadRemoteInfo(pullRequestSummary), + } as const; + const localPullRequestBranch = + resolvePullRequestWorktreeLocalBranchName(pullRequestWithRemoteInfo); + + const findLocalHeadBranch = (cwd: string) => + gitCore.listBranches({ cwd }).pipe( + Effect.map((result) => { + const localBranch = result.branches.find( + (branch) => !branch.isRemote && branch.name === localPullRequestBranch, + ); + if (localBranch) { + return localBranch; + } + if (localPullRequestBranch === pullRequest.headBranch) { + return null; + } + return ( + result.branches.find( + (branch) => + !branch.isRemote && + branch.name === pullRequest.headBranch && + branch.worktreePath !== null && + canonicalizeExistingPath(branch.worktreePath) !== rootWorktreePath, + ) ?? null + ); + }), + ); + + const existingBranchBeforeFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchBeforeFetchPath = existingBranchBeforeFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchBeforeFetch.worktreePath) + : null; + if ( + existingBranchBeforeFetch?.worktreePath && + existingBranchBeforeFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchBeforeFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchBeforeFetch.worktreePath, + }; + } + if (existingBranchBeforeFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + yield* materializePullRequestHeadBranch( + input.cwd, + pullRequestWithRemoteInfo, + localPullRequestBranch, + ); + + const existingBranchAfterFetch = yield* findLocalHeadBranch(input.cwd); + const existingBranchAfterFetchPath = existingBranchAfterFetch?.worktreePath + ? canonicalizeExistingPath(existingBranchAfterFetch.worktreePath) + : null; + if ( + existingBranchAfterFetch?.worktreePath && + existingBranchAfterFetchPath !== rootWorktreePath + ) { + yield* ensureExistingWorktreeUpstream(existingBranchAfterFetch.worktreePath); + return { + pullRequest, + branch: localPullRequestBranch, + worktreePath: existingBranchAfterFetch.worktreePath, + }; + } + if (existingBranchAfterFetchPath === rootWorktreePath) { + return yield* gitManagerError( + "preparePullRequestThread", + "This PR branch is already checked out in the main repo. Use Local, or switch the main repo off that branch before creating a worktree thread.", + ); + } + + const worktree = yield* gitCore.createWorktree({ + cwd: input.cwd, + branch: localPullRequestBranch, + path: null, + }); + yield* ensureExistingWorktreeUpstream(worktree.worktree.path); + + return { + pullRequest, + branch: worktree.worktree.branch, + worktreePath: worktree.worktree.path, + }; + }); + + const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* ( modelSelection: ModelSelection, cwd: string, branch: string | null, commitMessage?: string, filePaths?: readonly string[], - ) => - Effect.gen(function* () { - const suggestion = yield* resolveCommitAndBranchSuggestion({ - cwd, - branch, - ...(commitMessage ? { commitMessage } : {}), - ...(filePaths ? { filePaths } : {}), - includeBranch: true, - modelSelection, - }); - if (!suggestion) { - return yield* gitManagerError( - "runFeatureBranchStep", - "Cannot create a feature branch because there are no changes to commit.", - ); - } - - const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject); - const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd); - const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch); - - yield* gitCore.createBranch({ cwd, branch: resolvedBranch }); - yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch })); - - return { - branchStep: { status: "created" as const, name: resolvedBranch }, - resolvedCommitMessage: suggestion.commitMessage, - resolvedCommitSuggestion: suggestion, - }; + ) { + const suggestion = yield* resolveCommitAndBranchSuggestion({ + cwd, + branch, + ...(commitMessage ? { commitMessage } : {}), + ...(filePaths ? { filePaths } : {}), + includeBranch: true, + modelSelection, }); + if (!suggestion) { + return yield* gitManagerError( + "runFeatureBranchStep", + "Cannot create a feature branch because there are no changes to commit.", + ); + } - const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced( + const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject); + const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd); + const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch); + + yield* gitCore.createBranch({ cwd, branch: resolvedBranch }); + yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch })); + + return { + branchStep: { status: "created" as const, name: resolvedBranch }, + resolvedCommitMessage: suggestion.commitMessage, + resolvedCommitSuggestion: suggestion, + }; + }); + + const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fn("runStackedAction")( function* (input, options) { const progress = createProgressEmitter(input, options); const phases: GitActionProgressPhase[] = [ @@ -1149,9 +1177,12 @@ export const makeGitManager = Effect.gen(function* () { ...(input.action !== "commit" ? (["push"] as const) : []), ...(input.action === "commit_push_pr" ? (["pr"] as const) : []), ]; - let currentPhase: GitActionProgressPhase | null = null; + const currentPhase = yield* Ref.make>(Option.none()); - const runAction = Effect.gen(function* () { + const runAction = Effect.fn("runStackedAction.runAction")(function* (): Effect.fn.Return< + GitRunStackedActionResult, + GitManagerServiceError + > { yield* progress.emit({ kind: "action_started", phases, @@ -1183,7 +1214,7 @@ export const makeGitManager = Effect.gen(function* () { ); if (input.featureBranch) { - currentPhase = "branch"; + yield* Ref.set(currentPhase, Option.some("branch")); yield* progress.emit({ kind: "phase_started", phase: "branch", @@ -1205,7 +1236,7 @@ export const makeGitManager = Effect.gen(function* () { const currentBranch = branchStep.name ?? initialStatus.branch; - currentPhase = "commit"; + yield* Ref.set(currentPhase, Option.some("commit")); const commit = yield* runCommitStep( modelSelection, input.cwd, @@ -1226,12 +1257,8 @@ export const makeGitManager = Effect.gen(function* () { label: "Pushing...", }) .pipe( - Effect.flatMap(() => - Effect.gen(function* () { - currentPhase = "push"; - return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch); - }), - ), + Effect.tap(() => Ref.set(currentPhase, Option.some("push"))), + Effect.flatMap(() => gitCore.pushCurrentBranch(input.cwd, currentBranch)), ) : { status: "skipped_not_requested" as const }; @@ -1243,12 +1270,8 @@ export const makeGitManager = Effect.gen(function* () { label: "Creating PR...", }) .pipe( - Effect.flatMap(() => - Effect.gen(function* () { - currentPhase = "pr"; - return yield* runPrStep(modelSelection, input.cwd, currentBranch); - }), - ), + Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))), + Effect.flatMap(() => runPrStep(modelSelection, input.cwd, currentBranch)), ) : { status: "skipped_not_requested" as const }; @@ -1266,15 +1289,15 @@ export const makeGitManager = Effect.gen(function* () { return result; }); - return yield* runAction.pipe( - Effect.catch((error) => - progress - .emit({ + return yield* runAction().pipe( + Effect.tapError((error) => + Effect.flatMap(Ref.get(currentPhase), (phase) => + progress.emit({ kind: "action_failed", - phase: currentPhase, + phase: Option.getOrNull(phase), message: error.message, - }) - .pipe(Effect.flatMap(() => Effect.fail(error))), + }), + ), ), ); }, @@ -1288,4 +1311,4 @@ export const makeGitManager = Effect.gen(function* () { } satisfies GitManagerShape; }); -export const GitManagerLive = Layer.effect(GitManager, makeGitManager); +export const GitManagerLive = Layer.effect(GitManager, makeGitManager()); diff --git a/docs/effect-fn-checklist.md b/docs/effect-fn-checklist.md index 0d28171aa2..e8e5be1554 100644 --- a/docs/effect-fn-checklist.md +++ b/docs/effect-fn-checklist.md @@ -24,6 +24,17 @@ const new = Effect.fn('functionName')(function* () { }) ``` +- Use `Effect.fn('name')(function* (input: Input): Effect.fn.Return {})` to annotate the return type of the function if needed. + +- The 2nd argument works as a pipe, and it gets the effect and input as arguments: + +```ts +Effect.fn("name")( + function* (input: Input): Effect.fn.Return {}, + (effect, input) => Effect.catch(effect, (reason) => Effect.logWarning("Err", { input, reason })), +); +``` + ## Summary - Total non-test candidates: `322` @@ -32,9 +43,9 @@ const new = Effect.fn('functionName')(function* () { - [ ] `apps/server/src/provider/Layers/ProviderService.ts` - [x] `apps/server/src/provider/Layers/ClaudeAdapter.ts` -- [ ] `apps/server/src/provider/Layers/CodexAdapter.ts` -- [ ] `apps/server/src/git/Layers/GitCore.ts` -- [ ] `apps/server/src/git/Layers/GitManager.ts` +- [x] `apps/server/src/provider/Layers/CodexAdapter.ts` +- [x] `apps/server/src/git/Layers/GitCore.ts` +- [x] `apps/server/src/git/Layers/GitManager.ts` - [ ] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` - [ ] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` - [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` @@ -57,25 +68,25 @@ const new = Effect.fn('functionName')(function* () { ### `apps/server/src/git/Layers/GitCore.ts` (`58`) -- [ ] [makeGitCore](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L495) -- [ ] [handleTraceLine](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L317) -- [ ] [emitCompleteLines](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L449) -- [ ] [commit](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1178) -- [ ] [pushCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1217) -- [ ] [pullCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1316) -- [ ] [checkoutBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1697) -- [ ] Service methods and callback wrappers in this file +- [x] [makeGitCore](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L513) +- [x] [handleTraceLine](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L324) +- [x] [emitCompleteLines](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L455) +- [x] [commit](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1190) +- [x] [pushCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1223) +- [x] [pullCurrentBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1323) +- [x] [checkoutBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitCore.ts#L1727) +- [x] Service methods and callback wrappers in this file ### `apps/server/src/git/Layers/GitManager.ts` (`28`) -- [ ] [configurePullRequestHeadUpstream](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L387) -- [ ] [materializePullRequestHeadBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L428) -- [ ] [findOpenPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L576) -- [ ] [findLatestPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L602) -- [ ] [runCommitStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L728) -- [ ] [runPrStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L842) -- [ ] [runFeatureBranchStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L1106) -- [ ] Remaining helpers and nested callback wrappers in this file +- [x] [configurePullRequestHeadUpstream](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L387) +- [x] [materializePullRequestHeadBranch](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L428) +- [x] [findOpenPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L576) +- [x] [findLatestPr](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L602) +- [x] [runCommitStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L728) +- [x] [runPrStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L842) +- [x] [runFeatureBranchStep](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/GitManager.ts#L1106) +- [x] Remaining helpers and nested callback wrappers in this file ### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`) @@ -113,11 +124,11 @@ const new = Effect.fn('functionName')(function* () { ### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`) -- [ ] [makeCodexAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1317) -- [ ] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1399) -- [ ] [writeNativeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1546) -- [ ] [listener](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1555) -- [ ] Remaining nested callback wrappers in this file +- [x] [makeCodexAdapter](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1317) +- [x] [sendTurn](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1399) +- [x] [writeNativeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1546) +- [x] [listener](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/Layers/CodexAdapter.ts#L1555) +- [x] Remaining nested callback wrappers in this file ### `apps/server/src/checkpointing/Layers/CheckpointStore.ts` (`10`) @@ -181,3 +192,7 @@ const new = Effect.fn('functionName')(function* () { - [ ] [apps/server/src/git/Layers/ClaudeTextGeneration.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/git/Layers/ClaudeTextGeneration.ts) (`2`) - [ ] [apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts) (`2`) - [ ] [apps/server/src/provider/makeManagedServerProvider.ts](/Users/julius/Development/Work/codething-mvp/apps/server/src/provider/makeManagedServerProvider.ts) (`1`) + +``` + +``` From 00f3efb95b485a40380af8295a5119b03095858b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 22:52:39 -0700 Subject: [PATCH 36/66] Make DrainableWorker drain off outstanding count (#1514) --- packages/shared/src/DrainableWorker.ts | 56 +++++++++++--------------- 1 file changed, 24 insertions(+), 32 deletions(-) diff --git a/packages/shared/src/DrainableWorker.ts b/packages/shared/src/DrainableWorker.ts index 7eb311ca57..55483f33e8 100644 --- a/packages/shared/src/DrainableWorker.ts +++ b/packages/shared/src/DrainableWorker.ts @@ -1,13 +1,15 @@ /** - * DrainableWorker - A queue-based worker with deterministic `drain()`. + * DrainableWorker - A queue-based worker that exposes a `drain()` effect. * - * Tracks outstanding work in STM so `drain()` resolves only when no items - * are queued or in flight. Useful in tests instead of timing-based waits. + * Wraps the common `Queue.unbounded` + `Effect.forever` pattern and adds + * a signal that resolves when the queue is empty **and** the current item + * has finished processing. This lets tests replace timing-sensitive + * `Effect.sleep` calls with deterministic `drain()`. * * @module DrainableWorker */ -import { Effect, TxQueue, TxRef } from "effect"; import type { Scope } from "effect"; +import { Effect, TxQueue, TxRef } from "effect"; export interface DrainableWorker
{ /** @@ -37,40 +39,30 @@ export const makeDrainableWorker = ( process: (item: A) => Effect.Effect, ): Effect.Effect, never, Scope.Scope | R> => Effect.gen(function* () { - const ref = yield* TxRef.make(0); + const queue = yield* Effect.acquireRelease(TxQueue.unbounded(), TxQueue.shutdown); + const outstanding = yield* TxRef.make(0); - const queue = yield* Effect.acquireRelease(TxQueue.unbounded(), (queue) => - TxQueue.shutdown(queue), - ); - - const takeItem = Effect.tx( - Effect.gen(function* () { - const item = yield* TxQueue.take(queue); - yield* TxRef.update(ref, (n) => n + 1); - return item; - }), - ); - - yield* takeItem.pipe( - Effect.flatMap((item) => - process(item).pipe(Effect.ensuring(TxRef.update(ref, (n) => n - 1))), + yield* TxQueue.take(queue).pipe( + Effect.tap((a) => + Effect.ensuring( + process(a), + TxRef.update(outstanding, (n) => n - 1), + ), ), Effect.forever, Effect.forkScoped, ); - const drain: DrainableWorker["drain"] = Effect.tx( - Effect.gen(function* () { - const inFlight = yield* TxRef.get(ref); - const isEmpty = yield* TxQueue.isEmpty(queue); - if (inFlight > 0 || !isEmpty) { - return yield* Effect.txRetry; - } - }), + const drain: DrainableWorker["drain"] = TxRef.get(outstanding).pipe( + Effect.tap((n) => (n > 0 ? Effect.txRetry : Effect.void)), + Effect.tx, ); - return { - enqueue: (item) => TxQueue.offer(queue, item), - drain, - } satisfies DrainableWorker; + const enqueue = (element: A): Effect.Effect => + TxQueue.offer(queue, element).pipe( + Effect.tap(() => TxRef.update(outstanding, (n) => n + 1)), + Effect.tx, + ); + + return { enqueue, drain } satisfies DrainableWorker; }); From a1c428b6e266434e33b43d2e40d81d6851c1bb3c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 22:54:37 -0700 Subject: [PATCH 37/66] Refactor projection pipeline side effects (#1512) --- .../Layers/ProjectionPipeline.ts | 447 +++++++++--------- docs/effect-fn-checklist.md | 16 +- 2 files changed, 238 insertions(+), 225 deletions(-) diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 7d85d1e38c..f0f2ccabee 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -77,7 +77,7 @@ interface AttachmentSideEffects { readonly prunedThreadRelativePaths: Map>; } -const materializeAttachmentsForProjection = Effect.fn( +const materializeAttachmentsForProjection = Effect.fn("materializeAttachmentsForProjection")( (input: { readonly attachments: ReadonlyArray }) => Effect.succeed(input.attachments.length === 0 ? [] : input.attachments), ); @@ -238,124 +238,145 @@ function collectThreadAttachmentRelativePaths( return relativePaths; } -const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSideEffects) { +const runAttachmentSideEffects = Effect.fn("runAttachmentSideEffects")(function* ( + sideEffects: AttachmentSideEffects, +) { const serverConfig = yield* Effect.service(ServerConfig); const fileSystem = yield* Effect.service(FileSystem.FileSystem); const path = yield* Effect.service(Path.Path); const attachmentsRootDir = serverConfig.attachmentsDir; + const readAttachmentRootEntries = fileSystem + .readDirectory(attachmentsRootDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - sideEffects.deletedThreadIds, - (threadId) => - Effect.gen(function* () { - const threadSegment = toSafeThreadAttachmentSegment(threadId); - if (!threadSegment) { - yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", { - threadId, - }); - return; - } - const entries = yield* fileSystem - .readDirectory(attachmentsRootDir, { recursive: false }) - .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - entries, - (entry) => - Effect.gen(function* () { - const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); - if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) { - return; - } - const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry); - if (!attachmentId) { - return; - } - const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); - if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { - return; - } - yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), { - force: true, - }); - }), - { concurrency: 1 }, - ); - }), - { concurrency: 1 }, + const removeDeletedThreadAttachmentEntry = Effect.fn("removeDeletedThreadAttachmentEntry")( + function* (threadSegment: string, entry: string) { + const normalizedEntry = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (normalizedEntry.length === 0 || normalizedEntry.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(normalizedEntry); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + yield* fileSystem.remove(path.join(attachmentsRootDir, normalizedEntry), { + force: true, + }); + }, ); + const deleteThreadAttachments = Effect.fn("deleteThreadAttachments")(function* ( + threadId: string, + ) { + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment cleanup for unsafe thread id", { + threadId, + }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => removeDeletedThreadAttachmentEntry(threadSegment, entry), + { + concurrency: 1, + }, + ); + }); + + const pruneThreadAttachmentEntry = Effect.fn("pruneThreadAttachmentEntry")(function* ( + threadSegment: string, + keptThreadRelativePaths: Set, + entry: string, + ) { + const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); + if (relativePath.length === 0 || relativePath.includes("/")) { + return; + } + const attachmentId = parseAttachmentIdFromRelativePath(relativePath); + if (!attachmentId) { + return; + } + const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); + if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { + return; + } + + const absolutePath = path.join(attachmentsRootDir, relativePath); + const fileInfo = yield* fileSystem + .stat(absolutePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!fileInfo || fileInfo.type !== "File") { + return; + } + + if (!keptThreadRelativePaths.has(relativePath)) { + yield* fileSystem.remove(absolutePath, { force: true }); + } + }); + + const pruneThreadAttachments = Effect.fn("pruneThreadAttachments")(function* ( + threadId: string, + keptThreadRelativePaths: Set, + ) { + if (sideEffects.deletedThreadIds.has(threadId)) { + return; + } + + const threadSegment = toSafeThreadAttachmentSegment(threadId); + if (!threadSegment) { + yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId }); + return; + } + + const entries = yield* readAttachmentRootEntries; + yield* Effect.forEach( + entries, + (entry) => pruneThreadAttachmentEntry(threadSegment, keptThreadRelativePaths, entry), + { concurrency: 1 }, + ); + }); + + yield* Effect.forEach(sideEffects.deletedThreadIds, deleteThreadAttachments, { + concurrency: 1, + }); + yield* Effect.forEach( sideEffects.prunedThreadRelativePaths.entries(), - ([threadId, keptThreadRelativePaths]) => { - if (sideEffects.deletedThreadIds.has(threadId)) { - return Effect.void; - } - return Effect.gen(function* () { - const threadSegment = toSafeThreadAttachmentSegment(threadId); - if (!threadSegment) { - yield* Effect.logWarning("skipping attachment prune for unsafe thread id", { threadId }); - return; - } - const entries = yield* fileSystem - .readDirectory(attachmentsRootDir, { recursive: false }) - .pipe(Effect.catch(() => Effect.succeed([] as Array))); - yield* Effect.forEach( - entries, - (entry) => - Effect.gen(function* () { - const relativePath = entry.replace(/^[/\\]+/, "").replace(/\\/g, "/"); - if (relativePath.length === 0 || relativePath.includes("/")) { - return; - } - const attachmentId = parseAttachmentIdFromRelativePath(relativePath); - if (!attachmentId) { - return; - } - const attachmentThreadSegment = parseThreadSegmentFromAttachmentId(attachmentId); - if (!attachmentThreadSegment || attachmentThreadSegment !== threadSegment) { - return; - } - - const absolutePath = path.join(attachmentsRootDir, relativePath); - const fileInfo = yield* fileSystem - .stat(absolutePath) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!fileInfo || fileInfo.type !== "File") { - return; - } - - if (!keptThreadRelativePaths.has(relativePath)) { - yield* fileSystem.remove(absolutePath, { force: true }); - } - }), - { concurrency: 1 }, - ); - }); - }, + ([threadId, keptThreadRelativePaths]) => + pruneThreadAttachments(threadId, keptThreadRelativePaths), { concurrency: 1 }, ); }); -const makeOrchestrationProjectionPipeline = Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const eventStore = yield* OrchestrationEventStore; - const projectionStateRepository = yield* ProjectionStateRepository; - const projectionProjectRepository = yield* ProjectionProjectRepository; - const projectionThreadRepository = yield* ProjectionThreadRepository; - const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository; - const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository; - const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository; - const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository; - const projectionTurnRepository = yield* ProjectionTurnRepository; - const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository; +const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjectionPipeline")( + function* () { + const sql = yield* SqlClient.SqlClient; + const eventStore = yield* OrchestrationEventStore; + const projectionStateRepository = yield* ProjectionStateRepository; + const projectionProjectRepository = yield* ProjectionProjectRepository; + const projectionThreadRepository = yield* ProjectionThreadRepository; + const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository; + const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository; + const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository; + const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository; + const projectionTurnRepository = yield* ProjectionTurnRepository; + const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository; - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const serverConfig = yield* ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; - const applyProjectsProjection: ProjectorDefinition["apply"] = (event, _attachmentSideEffects) => - Effect.gen(function* () { + const applyProjectsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyProjectsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "project.created": yield* projectionProjectRepository.upsert({ @@ -412,8 +433,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadsProjection: ProjectorDefinition["apply"] = (event, attachmentSideEffects) => - Effect.gen(function* () { + const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadsProjection", + )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.created": yield* projectionThreadRepository.upsert({ @@ -597,11 +619,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadMessagesProjection: ProjectorDefinition["apply"] = ( - event, - attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadMessagesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadMessagesProjection", + )(function* (event, attachmentSideEffects) { switch (event.type) { case "thread.message-sent": { const existingRows = yield* projectionThreadMessageRepository.listByThreadId({ @@ -674,11 +694,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadProposedPlansProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.proposed-plan-upserted": yield* projectionThreadProposedPlanRepository.upsert({ @@ -727,11 +745,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadActivitiesProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.activity-appended": yield* projectionThreadActivityRepository.upsert({ @@ -781,11 +797,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyThreadSessionsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadSessionsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadSessionsProjection", + )(function* (event, _attachmentSideEffects) { if (event.type !== "thread.session-set") { return; } @@ -800,11 +814,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { }); }); - const applyThreadTurnsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyThreadTurnsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.turn-start-requested": { yield* projectionTurnRepository.replacePendingTurnStart({ @@ -1058,13 +1070,11 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void; + const applyCheckpointsProjection: ProjectorDefinition["apply"] = () => Effect.void; - const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = ( - event, - _attachmentSideEffects, - ) => - Effect.gen(function* () { + const applyPendingApprovalsProjection: ProjectorDefinition["apply"] = Effect.fn( + "applyPendingApprovalsProjection", + )(function* (event, _attachmentSideEffects) { switch (event.type) { case "thread.activity-appended": { const requestId = @@ -1150,47 +1160,49 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { } }); - const projectors: ReadonlyArray = [ - { - name: ORCHESTRATION_PROJECTOR_NAMES.projects, - apply: applyProjectsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, - apply: applyThreadMessagesProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, - apply: applyThreadProposedPlansProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities, - apply: applyThreadActivitiesProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions, - apply: applyThreadSessionsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns, - apply: applyThreadTurnsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints, - apply: applyCheckpointsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals, - apply: applyPendingApprovalsProjection, - }, - { - name: ORCHESTRATION_PROJECTOR_NAMES.threads, - apply: applyThreadsProjection, - }, - ]; + const projectors: ReadonlyArray = [ + { + name: ORCHESTRATION_PROJECTOR_NAMES.projects, + apply: applyProjectsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages, + apply: applyThreadMessagesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans, + apply: applyThreadProposedPlansProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities, + apply: applyThreadActivitiesProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions, + apply: applyThreadSessionsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns, + apply: applyThreadTurnsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.checkpoints, + apply: applyCheckpointsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.pendingApprovals, + apply: applyPendingApprovalsProjection, + }, + { + name: ORCHESTRATION_PROJECTOR_NAMES.threads, + apply: applyThreadsProjection, + }, + ]; - const runProjectorForEvent = (projector: ProjectorDefinition, event: OrchestrationEvent) => - Effect.gen(function* () { + const runProjectorForEvent = Effect.fn("runProjectorForEvent")(function* ( + projector: ProjectorDefinition, + event: OrchestrationEvent, + ) { const attachmentSideEffects: AttachmentSideEffects = { deletedThreadIds: new Set(), prunedThreadRelativePaths: new Map>(), @@ -1220,63 +1232,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () { ); }); - const bootstrapProjector = (projector: ProjectorDefinition) => - projectionStateRepository - .getByProjector({ - projector: projector.name, - }) - .pipe( - Effect.flatMap((stateRow) => - Stream.runForEach( - eventStore.readFromSequence( - Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0, + const bootstrapProjector = (projector: ProjectorDefinition) => + projectionStateRepository + .getByProjector({ + projector: projector.name, + }) + .pipe( + Effect.flatMap((stateRow) => + Stream.runForEach( + eventStore.readFromSequence( + Option.isSome(stateRow) ? stateRow.value.lastAppliedSequence : 0, + ), + (event) => runProjectorForEvent(projector, event), ), - (event) => runProjectorForEvent(projector, event), ), + ); + + const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => + Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), { + concurrency: 1, + }).pipe( + Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(Path.Path, path), + Effect.provideService(ServerConfig, serverConfig), + Effect.asVoid, + Effect.catchTag("SqlError", (sqlError) => + Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)), ), ); - const projectEvent: OrchestrationProjectionPipelineShape["projectEvent"] = (event) => - Effect.forEach(projectors, (projector) => runProjectorForEvent(projector, event), { - concurrency: 1, - }).pipe( + const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach( + projectors, + bootstrapProjector, + { concurrency: 1 }, + ).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), Effect.provideService(ServerConfig, serverConfig), Effect.asVoid, + Effect.tap(() => + Effect.log("orchestration projection pipeline bootstrapped").pipe( + Effect.annotateLogs({ projectors: projectors.length }), + ), + ), Effect.catchTag("SqlError", (sqlError) => - Effect.fail(toPersistenceSqlError("ProjectionPipeline.projectEvent:query")(sqlError)), + Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)), ), ); - const bootstrap: OrchestrationProjectionPipelineShape["bootstrap"] = Effect.forEach( - projectors, - bootstrapProjector, - { concurrency: 1 }, - ).pipe( - Effect.provideService(FileSystem.FileSystem, fileSystem), - Effect.provideService(Path.Path, path), - Effect.provideService(ServerConfig, serverConfig), - Effect.asVoid, - Effect.tap(() => - Effect.log("orchestration projection pipeline bootstrapped").pipe( - Effect.annotateLogs({ projectors: projectors.length }), - ), - ), - Effect.catchTag("SqlError", (sqlError) => - Effect.fail(toPersistenceSqlError("ProjectionPipeline.bootstrap:query")(sqlError)), - ), - ); - - return { - bootstrap, - projectEvent, - } satisfies OrchestrationProjectionPipelineShape; -}); + return { + bootstrap, + projectEvent, + } satisfies OrchestrationProjectionPipelineShape; + }, +); export const OrchestrationProjectionPipelineLive = Layer.effect( OrchestrationProjectionPipeline, - makeOrchestrationProjectionPipeline, + makeOrchestrationProjectionPipeline(), ).pipe( Layer.provideMerge(NodeServices.layer), Layer.provideMerge(ProjectionProjectRepositoryLive), diff --git a/docs/effect-fn-checklist.md b/docs/effect-fn-checklist.md index e8e5be1554..d986594849 100644 --- a/docs/effect-fn-checklist.md +++ b/docs/effect-fn-checklist.md @@ -47,7 +47,7 @@ Effect.fn("name")( - [x] `apps/server/src/git/Layers/GitCore.ts` - [x] `apps/server/src/git/Layers/GitManager.ts` - [ ] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` -- [ ] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` +- [x] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` - [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` - [ ] `apps/server/src/provider/Layers/EventNdjsonLogger.ts` - [ ] `Everything else` @@ -90,13 +90,13 @@ Effect.fn("name")( ### `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` (`25`) -- [ ] [runProjectorForEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161) -- [ ] [applyProjectsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357) -- [ ] [applyThreadsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415) -- [ ] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250` -- [ ] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264` -- [ ] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305` -- [ ] Remaining apply helpers in this file +- [x] [runProjectorForEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L1161) +- [x] [applyProjectsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L357) +- [x] [applyThreadsProjection](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProjectionPipeline.ts#L415) +- [x] `Effect.forEach(..., threadId => Effect.gen(...))` callbacks around `L250` +- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L264` +- [x] `Effect.forEach(..., entry => Effect.gen(...))` callbacks around `L305` +- [x] Remaining apply helpers in this file ### `apps/server/src/provider/Layers/ProviderService.ts` (`24`) From bc1024caf09aa349f18dd72aaf823588f3ff1fec Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 22:55:18 -0700 Subject: [PATCH 38/66] Inline sqlite error classification (#1515) --- .../server/src/persistence/NodeSqliteClient.ts | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/apps/server/src/persistence/NodeSqliteClient.ts b/apps/server/src/persistence/NodeSqliteClient.ts index 5577ac5b01..78dbe8a1a9 100644 --- a/apps/server/src/persistence/NodeSqliteClient.ts +++ b/apps/server/src/persistence/NodeSqliteClient.ts @@ -29,9 +29,6 @@ export const TypeId: TypeId = "~local/sqlite-node/SqliteClient"; export type TypeId = "~local/sqlite-node/SqliteClient"; -const classifyError = (cause: unknown, message: string, operation: string) => - classifySqliteError(cause, { message, operation }); - /** * SqliteClient - Effect service tag for the sqlite SQL client. */ @@ -114,7 +111,10 @@ const makeWithDatabase = ( try: () => db.prepare(sql), catch: (cause) => new SqlError({ - reason: classifyError(cause, "Failed to prepare statement", "prepare"), + reason: classifySqliteError(cause, { + message: "Failed to prepare statement", + operation: "prepare", + }), }), }), }); @@ -135,7 +135,10 @@ const makeWithDatabase = ( } catch (cause) { return Effect.fail( new SqlError({ - reason: classifyError(cause, "Failed to execute statement", "execute"), + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), }), ); } @@ -162,7 +165,10 @@ const makeWithDatabase = ( }, catch: (cause) => new SqlError({ - reason: classifyError(cause, "Failed to execute statement", "execute"), + reason: classifySqliteError(cause, { + message: "Failed to execute statement", + operation: "execute", + }), }), }), (statement) => From a60daa1c764a97e88f2eef63bbac960b79274ed6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sat, 28 Mar 2026 22:57:32 -0700 Subject: [PATCH 39/66] Wrap orchestration reactor starts in Effect.fn (#1513) --- .../OrchestrationEngineHarness.integration.ts | 2 +- .../Layers/CheckpointReactor.test.ts | 2 +- .../orchestration/Layers/CheckpointReactor.ts | 2 +- .../Layers/OrchestrationReactor.test.ts | 17 +- .../Layers/OrchestrationReactor.ts | 8 +- .../Layers/ProviderCommandReactor.test.ts | 2 +- .../Layers/ProviderCommandReactor.ts | 26 +- .../Layers/ProviderRuntimeIngestion.test.ts | 2 +- .../Layers/ProviderRuntimeIngestion.ts | 815 +++++++++--------- .../Services/CheckpointReactor.ts | 2 +- .../Services/OrchestrationReactor.ts | 2 +- .../Services/ProviderCommandReactor.ts | 2 +- .../Services/ProviderRuntimeIngestion.ts | 2 +- apps/server/src/wsServer.ts | 2 +- docs/effect-fn-checklist.md | 14 +- 15 files changed, 449 insertions(+), 451 deletions(-) diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index 1a8f802d73..e66a214fb7 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -360,7 +360,7 @@ export const makeOrchestrationIntegrationHarness = ( const scope = yield* Scope.make("sequential"); yield* tryRuntimePromise("start OrchestrationReactor", () => - runtime.runPromise(reactor.start.pipe(Scope.provide(scope))), + runtime.runPromise(reactor.start().pipe(Scope.provide(scope))), ).pipe(Effect.orDie); const receiptHistory = yield* Ref.make>([]); yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) => diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 69360ebf6a..075f62f889 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -271,7 +271,7 @@ describe("CheckpointReactor", () => { const reactor = await runtime.runPromise(Effect.service(CheckpointReactor)); const checkpointStore = await runtime.runPromise(Effect.service(CheckpointStore)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(reactor.drain); const createdAt = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index e4a673342c..561626b8de 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -766,7 +766,7 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processInputSafely); - const start: CheckpointReactorShape["start"] = Effect.gen(function* () { + const start: CheckpointReactorShape["start"] = Effect.fn("start")(function* () { yield* Effect.forkScoped( Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { if ( diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts index 1514bef595..d60f0cf722 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.test.ts @@ -24,25 +24,28 @@ describe("OrchestrationReactor", () => { Layer.effect(OrchestrationReactor, makeOrchestrationReactor).pipe( Layer.provideMerge( Layer.succeed(ProviderRuntimeIngestionService, { - start: Effect.sync(() => { + start: () => { started.push("provider-runtime-ingestion"); - }), + return Effect.void; + }, drain: Effect.void, }), ), Layer.provideMerge( Layer.succeed(ProviderCommandReactor, { - start: Effect.sync(() => { + start: () => { started.push("provider-command-reactor"); - }), + return Effect.void; + }, drain: Effect.void, }), ), Layer.provideMerge( Layer.succeed(CheckpointReactor, { - start: Effect.sync(() => { + start: () => { started.push("checkpoint-reactor"); - }), + return Effect.void; + }, drain: Effect.void, }), ), @@ -51,7 +54,7 @@ describe("OrchestrationReactor", () => { const reactor = await runtime.runPromise(Effect.service(OrchestrationReactor)); const scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); expect(started).toEqual([ "provider-runtime-ingestion", diff --git a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts index 1e498885a0..99d30c57a2 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationReactor.ts @@ -13,10 +13,10 @@ export const makeOrchestrationReactor = Effect.gen(function* () { const providerCommandReactor = yield* ProviderCommandReactor; const checkpointReactor = yield* CheckpointReactor; - const start: OrchestrationReactorShape["start"] = Effect.gen(function* () { - yield* providerRuntimeIngestion.start; - yield* providerCommandReactor.start; - yield* checkpointReactor.start; + const start: OrchestrationReactorShape["start"] = Effect.fn("start")(function* () { + yield* providerRuntimeIngestion.start(); + yield* providerCommandReactor.start(); + yield* checkpointReactor.start(); }); return { diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 4e87390eb1..ed7037695f 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -235,7 +235,7 @@ describe("ProviderCommandReactor", () => { const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); const reactor = await runtime.runPromise(Effect.service(ProviderCommandReactor)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(reactor.start.pipe(Scope.provide(scope))); + await Effect.runPromise(reactor.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(reactor.drain); await Effect.runPromise( diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index f65137f4b5..d4f13ec727 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -773,22 +773,24 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processDomainEventSafely); - const start: ProviderCommandReactorShape["start"] = Effect.forkScoped( - Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => { + const start: ProviderCommandReactorShape["start"] = Effect.fn("start")(function* () { + const processEvent = Effect.fn("processEvent")(function* (event: OrchestrationEvent) { if ( - event.type !== "thread.runtime-mode-set" && - event.type !== "thread.turn-start-requested" && - event.type !== "thread.turn-interrupt-requested" && - event.type !== "thread.approval-response-requested" && - event.type !== "thread.user-input-response-requested" && - event.type !== "thread.session-stop-requested" + event.type === "thread.runtime-mode-set" || + event.type === "thread.turn-start-requested" || + event.type === "thread.turn-interrupt-requested" || + event.type === "thread.approval-response-requested" || + event.type === "thread.user-input-response-requested" || + event.type === "thread.session-stop-requested" ) { - return Effect.void; + return yield* worker.enqueue(event); } + }); - return worker.enqueue(event); - }), - ).pipe(Effect.asVoid); + yield* Effect.forkScoped( + Stream.runForEach(orchestrationEngine.streamDomainEvents, processEvent), + ); + }); return { start, diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 3eaeb2cd1d..529eae2444 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -214,7 +214,7 @@ describe("ProviderRuntimeIngestion", () => { const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService)); const ingestion = await runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)); scope = await Effect.runPromise(Scope.make("sequential")); - await Effect.runPromise(ingestion.start.pipe(Scope.provide(scope))); + await Effect.runPromise(ingestion.start().pipe(Scope.provide(scope))); const drain = () => Effect.runPromise(ingestion.drain); const createdAt = new Date().toISOString(); diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index b42e5f1566..b479d1c28a 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -500,7 +500,7 @@ function runtimeEventToActivities( return []; } -const make = Effect.gen(function* () { +const make = Effect.fn("make")(function* () { const orchestrationEngine = yield* OrchestrationEngineService; const providerService = yield* ProviderService; const projectionTurnRepository = yield* ProjectionTurnRepository; @@ -587,8 +587,8 @@ const make = Effect.gen(function* () { const appendBufferedAssistantText = (messageId: MessageId, delta: string) => Cache.getOption(bufferedAssistantTextByMessageId, messageId).pipe( - Effect.flatMap((existingText) => - Effect.gen(function* () { + Effect.flatMap( + Effect.fn("appendBufferedAssistantText")(function* (existingText) { const nextText = Option.match(existingText, { onNone: () => delta, onSome: (text) => `${text}${delta}`, @@ -644,7 +644,7 @@ const make = Effect.gen(function* () { const clearAssistantMessageState = (messageId: MessageId) => clearBufferedAssistantText(messageId); - const finalizeAssistantMessage = (input: { + const finalizeAssistantMessage = Effect.fn("finalizeAssistantMessage")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; messageId: MessageId; @@ -653,40 +653,39 @@ const make = Effect.gen(function* () { commandTag: string; finalDeltaCommandTag: string; fallbackText?: string; - }) => - Effect.gen(function* () { - const bufferedText = yield* takeBufferedAssistantText(input.messageId); - const text = - bufferedText.length > 0 - ? bufferedText - : (input.fallbackText?.trim().length ?? 0) > 0 - ? input.fallbackText! - : ""; - - if (text.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: providerCommandId(input.event, input.finalDeltaCommandTag), - threadId: input.threadId, - messageId: input.messageId, - delta: text, - ...(input.turnId ? { turnId: input.turnId } : {}), - createdAt: input.createdAt, - }); - } + }) { + const bufferedText = yield* takeBufferedAssistantText(input.messageId); + const text = + bufferedText.length > 0 + ? bufferedText + : (input.fallbackText?.trim().length ?? 0) > 0 + ? input.fallbackText! + : ""; + if (text.length > 0) { yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.complete", - commandId: providerCommandId(input.event, input.commandTag), + type: "thread.message.assistant.delta", + commandId: providerCommandId(input.event, input.finalDeltaCommandTag), threadId: input.threadId, messageId: input.messageId, + delta: text, ...(input.turnId ? { turnId: input.turnId } : {}), createdAt: input.createdAt, }); - yield* clearAssistantMessageState(input.messageId); - }); + } - const upsertProposedPlan = (input: { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.complete", + commandId: providerCommandId(input.event, input.commandTag), + threadId: input.threadId, + messageId: input.messageId, + ...(input.turnId ? { turnId: input.turnId } : {}), + createdAt: input.createdAt, + }); + yield* clearAssistantMessageState(input.messageId); + }); + + const upsertProposedPlan = Effect.fn("upsertProposedPlan")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; threadProposedPlans: ReadonlyArray<{ @@ -700,32 +699,31 @@ const make = Effect.gen(function* () { planMarkdown: string | undefined; createdAt: string; updatedAt: string; - }) => - Effect.gen(function* () { - const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); - if (!planMarkdown) { - return; - } + }) { + const planMarkdown = normalizeProposedPlanMarkdown(input.planMarkdown); + if (!planMarkdown) { + return; + } - const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId); - yield* orchestrationEngine.dispatch({ - type: "thread.proposed-plan.upsert", - commandId: providerCommandId(input.event, "proposed-plan-upsert"), - threadId: input.threadId, - proposedPlan: { - id: input.planId, - turnId: input.turnId ?? null, - planMarkdown, - implementedAt: existingPlan?.implementedAt ?? null, - implementationThreadId: existingPlan?.implementationThreadId ?? null, - createdAt: existingPlan?.createdAt ?? input.createdAt, - updatedAt: input.updatedAt, - }, - createdAt: input.updatedAt, - }); + const existingPlan = input.threadProposedPlans.find((entry) => entry.id === input.planId); + yield* orchestrationEngine.dispatch({ + type: "thread.proposed-plan.upsert", + commandId: providerCommandId(input.event, "proposed-plan-upsert"), + threadId: input.threadId, + proposedPlan: { + id: input.planId, + turnId: input.turnId ?? null, + planMarkdown, + implementedAt: existingPlan?.implementedAt ?? null, + implementationThreadId: existingPlan?.implementationThreadId ?? null, + createdAt: existingPlan?.createdAt ?? input.createdAt, + updatedAt: input.updatedAt, + }, + createdAt: input.updatedAt, }); + }); - const finalizeBufferedProposedPlan = (input: { + const finalizeBufferedProposedPlan = Effect.fn("finalizeBufferedProposedPlan")(function* (input: { event: ProviderRuntimeEvent; threadId: ThreadId; threadProposedPlans: ReadonlyArray<{ @@ -738,66 +736,65 @@ const make = Effect.gen(function* () { turnId?: TurnId; fallbackMarkdown?: string; updatedAt: string; - }) => - Effect.gen(function* () { - const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); - const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); - const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); - const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; - if (!planMarkdown) { - return; - } + }) { + const bufferedPlan = yield* takeBufferedProposedPlan(input.planId); + const bufferedMarkdown = normalizeProposedPlanMarkdown(bufferedPlan?.text); + const fallbackMarkdown = normalizeProposedPlanMarkdown(input.fallbackMarkdown); + const planMarkdown = bufferedMarkdown ?? fallbackMarkdown; + if (!planMarkdown) { + return; + } - yield* upsertProposedPlan({ - event: input.event, - threadId: input.threadId, - threadProposedPlans: input.threadProposedPlans, - planId: input.planId, - ...(input.turnId ? { turnId: input.turnId } : {}), - planMarkdown, - createdAt: - bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 - ? bufferedPlan.createdAt - : input.updatedAt, - updatedAt: input.updatedAt, - }); - yield* clearBufferedProposedPlan(input.planId); + yield* upsertProposedPlan({ + event: input.event, + threadId: input.threadId, + threadProposedPlans: input.threadProposedPlans, + planId: input.planId, + ...(input.turnId ? { turnId: input.turnId } : {}), + planMarkdown, + createdAt: + bufferedPlan?.createdAt && bufferedPlan.createdAt.length > 0 + ? bufferedPlan.createdAt + : input.updatedAt, + updatedAt: input.updatedAt, }); + yield* clearBufferedProposedPlan(input.planId); + }); - const clearTurnStateForSession = (threadId: ThreadId) => - Effect.gen(function* () { - const prefix = `${threadId}:`; - const proposedPlanPrefix = `plan:${threadId}:`; - const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); - const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); - yield* Effect.forEach( - turnKeys, - (key) => - Effect.gen(function* () { - if (!key.startsWith(prefix)) { - return; - } + const clearTurnStateForSession = Effect.fn("clearTurnStateForSession")(function* ( + threadId: ThreadId, + ) { + const prefix = `${threadId}:`; + const proposedPlanPrefix = `plan:${threadId}:`; + const turnKeys = Array.from(yield* Cache.keys(turnMessageIdsByTurnKey)); + const proposedPlanKeys = Array.from(yield* Cache.keys(bufferedProposedPlanById)); + yield* Effect.forEach( + turnKeys, + Effect.fn(function* (key) { + if (!key.startsWith(prefix)) { + return; + } - const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); - if (Option.isSome(messageIds)) { - yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { - concurrency: 1, - }).pipe(Effect.asVoid); - } + const messageIds = yield* Cache.getOption(turnMessageIdsByTurnKey, key); + if (Option.isSome(messageIds)) { + yield* Effect.forEach(messageIds.value, clearAssistantMessageState, { + concurrency: 1, + }).pipe(Effect.asVoid); + } - yield* Cache.invalidate(turnMessageIdsByTurnKey, key); - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* Effect.forEach( - proposedPlanKeys, - (key) => - key.startsWith(proposedPlanPrefix) - ? Cache.invalidate(bufferedProposedPlanById, key) - : Effect.void, - { concurrency: 1 }, - ).pipe(Effect.asVoid); - }); + yield* Cache.invalidate(turnMessageIdsByTurnKey, key); + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* Effect.forEach( + proposedPlanKeys, + (key) => + key.startsWith(proposedPlanPrefix) + ? Cache.invalidate(bufferedProposedPlanById, key) + : Effect.void, + { concurrency: 1 }, + ).pipe(Effect.asVoid); + }); const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* ( threadId: ThreadId, @@ -872,359 +869,355 @@ const make = Effect.gen(function* () { }); }); - const processRuntimeEvent = (event: ProviderRuntimeEvent) => - Effect.gen(function* () { - const readModel = yield* orchestrationEngine.getReadModel(); - const thread = readModel.threads.find((entry) => entry.id === event.threadId); - if (!thread) return; + const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* ( + event: ProviderRuntimeEvent, + ) { + const readModel = yield* orchestrationEngine.getReadModel(); + const thread = readModel.threads.find((entry) => entry.id === event.threadId); + if (!thread) return; - const now = event.createdAt; - const eventTurnId = toTurnId(event.turnId); - const activeTurnId = thread.session?.activeTurnId ?? null; + const now = event.createdAt; + const eventTurnId = toTurnId(event.turnId); + const activeTurnId = thread.session?.activeTurnId ?? null; - const conflictsWithActiveTurn = - activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); - const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; + const conflictsWithActiveTurn = + activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); + const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined; - const shouldApplyThreadLifecycle = (() => { - if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { + const shouldApplyThreadLifecycle = (() => { + if (!STRICT_PROVIDER_LIFECYCLE_GUARD) { + return true; + } + switch (event.type) { + case "session.exited": return true; - } + case "session.started": + case "thread.started": + return true; + case "turn.started": + return !conflictsWithActiveTurn; + case "turn.completed": + if (conflictsWithActiveTurn || missingTurnForActiveTurn) { + return false; + } + // Only the active turn may close the lifecycle state. + if (activeTurnId !== null && eventTurnId !== undefined) { + return sameId(activeTurnId, eventTurnId); + } + // If no active turn is tracked, accept completion scoped to this thread. + return true; + default: + return true; + } + })(); + const acceptedTurnStartedSourcePlan = + event.type === "turn.started" && shouldApplyThreadLifecycle + ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) + : null; + + if ( + event.type === "session.started" || + event.type === "session.state.changed" || + event.type === "session.exited" || + event.type === "thread.started" || + event.type === "turn.started" || + event.type === "turn.completed" + ) { + const nextActiveTurnId = + event.type === "turn.started" + ? (eventTurnId ?? null) + : event.type === "turn.completed" || event.type === "session.exited" + ? null + : activeTurnId; + const status = (() => { switch (event.type) { + case "session.state.changed": + return orchestrationSessionStatusFromRuntimeState(event.payload.state); + case "turn.started": + return "running"; case "session.exited": - return true; + return "stopped"; + case "turn.completed": + return normalizeRuntimeTurnState(event.payload.state) === "failed" ? "error" : "ready"; case "session.started": case "thread.started": - return true; - case "turn.started": - return !conflictsWithActiveTurn; - case "turn.completed": - if (conflictsWithActiveTurn || missingTurnForActiveTurn) { - return false; - } - // Only the active turn may close the lifecycle state. - if (activeTurnId !== null && eventTurnId !== undefined) { - return sameId(activeTurnId, eventTurnId); - } - // If no active turn is tracked, accept completion scoped to this thread. - return true; - default: - return true; + // Provider thread/session start notifications can arrive during an + // active turn; preserve turn-running state in that case. + return activeTurnId !== null ? "running" : "ready"; } })(); - const acceptedTurnStartedSourcePlan = - event.type === "turn.started" && shouldApplyThreadLifecycle - ? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId) - : null; - - if ( - event.type === "session.started" || - event.type === "session.state.changed" || - event.type === "session.exited" || - event.type === "thread.started" || - event.type === "turn.started" || - event.type === "turn.completed" - ) { - const nextActiveTurnId = - event.type === "turn.started" - ? (eventTurnId ?? null) - : event.type === "turn.completed" || event.type === "session.exited" + const lastError = + event.type === "session.state.changed" && event.payload.state === "error" + ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") + : event.type === "turn.completed" && + normalizeRuntimeTurnState(event.payload.state) === "failed" + ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") + : status === "ready" ? null - : activeTurnId; - const status = (() => { - switch (event.type) { - case "session.state.changed": - return orchestrationSessionStatusFromRuntimeState(event.payload.state); - case "turn.started": - return "running"; - case "session.exited": - return "stopped"; - case "turn.completed": - return normalizeRuntimeTurnState(event.payload.state) === "failed" - ? "error" - : "ready"; - case "session.started": - case "thread.started": - // Provider thread/session start notifications can arrive during an - // active turn; preserve turn-running state in that case. - return activeTurnId !== null ? "running" : "ready"; - } - })(); - const lastError = - event.type === "session.state.changed" && event.payload.state === "error" - ? (event.payload.reason ?? thread.session?.lastError ?? "Provider session error") - : event.type === "turn.completed" && - normalizeRuntimeTurnState(event.payload.state) === "failed" - ? (event.payload.errorMessage ?? thread.session?.lastError ?? "Turn failed") - : status === "ready" - ? null - : (thread.session?.lastError ?? null); + : (thread.session?.lastError ?? null); - if (shouldApplyThreadLifecycle) { - if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { - yield* markSourceProposedPlanImplemented( - acceptedTurnStartedSourcePlan.sourceThreadId, - acceptedTurnStartedSourcePlan.sourcePlanId, - thread.id, - now, - ).pipe( - Effect.catchCause((cause) => - Effect.logWarning( - "provider runtime ingestion failed to mark source proposed plan", - { - eventId: event.eventId, - eventType: event.type, - cause: Cause.pretty(cause), - }, - ), - ), - ); - } - - yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: providerCommandId(event, "thread-session-set"), - threadId: thread.id, - session: { - threadId: thread.id, - status, - providerName: event.provider, - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: nextActiveTurnId, - lastError, - updatedAt: now, - }, - createdAt: now, - }); + if (shouldApplyThreadLifecycle) { + if (event.type === "turn.started" && acceptedTurnStartedSourcePlan !== null) { + yield* markSourceProposedPlanImplemented( + acceptedTurnStartedSourcePlan.sourceThreadId, + acceptedTurnStartedSourcePlan.sourcePlanId, + thread.id, + now, + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("provider runtime ingestion failed to mark source proposed plan", { + eventId: event.eventId, + eventType: event.type, + cause: Cause.pretty(cause), + }), + ), + ); } + + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "thread-session-set"), + threadId: thread.id, + session: { + threadId: thread.id, + status, + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: nextActiveTurnId, + lastError, + updatedAt: now, + }, + createdAt: now, + }); + } + } + + const assistantDelta = + event.type === "content.delta" && event.payload.streamKind === "assistant_text" + ? event.payload.delta + : undefined; + const proposedPlanDelta = + event.type === "turn.proposed.delta" ? event.payload.delta : undefined; + + if (assistantDelta && assistantDelta.length > 0) { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const turnId = toTurnId(event.turnId); + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); } - const assistantDelta = - event.type === "content.delta" && event.payload.streamKind === "assistant_text" - ? event.payload.delta - : undefined; - const proposedPlanDelta = - event.type === "turn.proposed.delta" ? event.payload.delta : undefined; - - if (assistantDelta && assistantDelta.length > 0) { - const assistantMessageId = MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ); - const turnId = toTurnId(event.turnId); - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( - serverSettingsService.getSettings, - (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), - ); - if (assistantDeliveryMode === "buffered") { - const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); - if (spillChunk.length > 0) { - yield* orchestrationEngine.dispatch({ - type: "thread.message.assistant.delta", - commandId: providerCommandId(event, "assistant-delta-buffer-spill"), - threadId: thread.id, - messageId: assistantMessageId, - delta: spillChunk, - ...(turnId ? { turnId } : {}), - createdAt: now, - }); - } - } else { + const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map( + serverSettingsService.getSettings, + (settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"), + ); + if (assistantDeliveryMode === "buffered") { + const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta); + if (spillChunk.length > 0) { yield* orchestrationEngine.dispatch({ type: "thread.message.assistant.delta", - commandId: providerCommandId(event, "assistant-delta"), + commandId: providerCommandId(event, "assistant-delta-buffer-spill"), threadId: thread.id, messageId: assistantMessageId, - delta: assistantDelta, + delta: spillChunk, ...(turnId ? { turnId } : {}), createdAt: now, }); } - } - - if (proposedPlanDelta && proposedPlanDelta.length > 0) { - const planId = proposedPlanIdFromEvent(event, thread.id); - yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); - } - - const assistantCompletion = - event.type === "item.completed" && event.payload.itemType === "assistant_message" - ? { - messageId: MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ), - fallbackText: event.payload.detail, - } - : undefined; - const proposedPlanCompletion = - event.type === "turn.proposed.completed" - ? { - planId: proposedPlanIdFromEvent(event, thread.id), - turnId: toTurnId(event.turnId), - planMarkdown: event.payload.planMarkdown, - } - : undefined; - - if (assistantCompletion) { - const assistantMessageId = assistantCompletion.messageId; - const turnId = toTurnId(event.turnId); - const existingAssistantMessage = thread.messages.find( - (entry) => entry.id === assistantMessageId, - ); - const shouldApplyFallbackCompletionText = - !existingAssistantMessage || existingAssistantMessage.text.length === 0; - if (turnId) { - yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); - } - - yield* finalizeAssistantMessage({ - event, + } else { + yield* orchestrationEngine.dispatch({ + type: "thread.message.assistant.delta", + commandId: providerCommandId(event, "assistant-delta"), threadId: thread.id, messageId: assistantMessageId, + delta: assistantDelta, ...(turnId ? { turnId } : {}), createdAt: now, - commandTag: "assistant-complete", - finalDeltaCommandTag: "assistant-delta-finalize", - ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText - ? { fallbackText: assistantCompletion.fallbackText } - : {}), }); + } + } - if (turnId) { - yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); - } + if (proposedPlanDelta && proposedPlanDelta.length > 0) { + const planId = proposedPlanIdFromEvent(event, thread.id); + yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now); + } + + const assistantCompletion = + event.type === "item.completed" && event.payload.itemType === "assistant_message" + ? { + messageId: MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ), + fallbackText: event.payload.detail, + } + : undefined; + const proposedPlanCompletion = + event.type === "turn.proposed.completed" + ? { + planId: proposedPlanIdFromEvent(event, thread.id), + turnId: toTurnId(event.turnId), + planMarkdown: event.payload.planMarkdown, + } + : undefined; + + if (assistantCompletion) { + const assistantMessageId = assistantCompletion.messageId; + const turnId = toTurnId(event.turnId); + const existingAssistantMessage = thread.messages.find( + (entry) => entry.id === assistantMessageId, + ); + const shouldApplyFallbackCompletionText = + !existingAssistantMessage || existingAssistantMessage.text.length === 0; + if (turnId) { + yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId); } - if (proposedPlanCompletion) { + yield* finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + ...(turnId ? { turnId } : {}), + createdAt: now, + commandTag: "assistant-complete", + finalDeltaCommandTag: "assistant-delta-finalize", + ...(assistantCompletion.fallbackText !== undefined && shouldApplyFallbackCompletionText + ? { fallbackText: assistantCompletion.fallbackText } + : {}), + }); + + if (turnId) { + yield* forgetAssistantMessageId(thread.id, turnId, assistantMessageId); + } + } + + if (proposedPlanCompletion) { + yield* finalizeBufferedProposedPlan({ + event, + threadId: thread.id, + threadProposedPlans: thread.proposedPlans, + planId: proposedPlanCompletion.planId, + ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), + fallbackMarkdown: proposedPlanCompletion.planMarkdown, + updatedAt: now, + }); + } + + if (event.type === "turn.completed") { + const turnId = toTurnId(event.turnId); + if (turnId) { + const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); + yield* Effect.forEach( + assistantMessageIds, + (assistantMessageId) => + finalizeAssistantMessage({ + event, + threadId: thread.id, + messageId: assistantMessageId, + turnId, + createdAt: now, + commandTag: "assistant-complete-finalize", + finalDeltaCommandTag: "assistant-delta-finalize-fallback", + }), + { concurrency: 1 }, + ).pipe(Effect.asVoid); + yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + yield* finalizeBufferedProposedPlan({ event, threadId: thread.id, threadProposedPlans: thread.proposedPlans, - planId: proposedPlanCompletion.planId, - ...(proposedPlanCompletion.turnId ? { turnId: proposedPlanCompletion.turnId } : {}), - fallbackMarkdown: proposedPlanCompletion.planMarkdown, + planId: proposedPlanIdForTurn(thread.id, turnId), + turnId, updatedAt: now, }); } + } - if (event.type === "turn.completed") { - const turnId = toTurnId(event.turnId); - if (turnId) { - const assistantMessageIds = yield* getAssistantMessageIdsForTurn(thread.id, turnId); - yield* Effect.forEach( - assistantMessageIds, - (assistantMessageId) => - finalizeAssistantMessage({ - event, - threadId: thread.id, - messageId: assistantMessageId, - turnId, - createdAt: now, - commandTag: "assistant-complete-finalize", - finalDeltaCommandTag: "assistant-delta-finalize-fallback", - }), - { concurrency: 1 }, - ).pipe(Effect.asVoid); - yield* clearAssistantMessageIdsForTurn(thread.id, turnId); + if (event.type === "session.exited") { + yield* clearTurnStateForSession(thread.id); + } - yield* finalizeBufferedProposedPlan({ - event, + if (event.type === "runtime.error") { + const runtimeErrorMessage = event.payload.message; + + const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD + ? true + : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); + + if (shouldApplyRuntimeError) { + yield* orchestrationEngine.dispatch({ + type: "thread.session.set", + commandId: providerCommandId(event, "runtime-error-session-set"), + threadId: thread.id, + session: { threadId: thread.id, - threadProposedPlans: thread.proposedPlans, - planId: proposedPlanIdForTurn(thread.id, turnId), - turnId, + status: "error", + providerName: event.provider, + runtimeMode: thread.session?.runtimeMode ?? "full-access", + activeTurnId: eventTurnId ?? null, + lastError: runtimeErrorMessage, updatedAt: now, - }); - } + }, + createdAt: now, + }); } + } - if (event.type === "session.exited") { - yield* clearTurnStateForSession(thread.id); - } + if (event.type === "thread.metadata.updated" && event.payload.name) { + yield* orchestrationEngine.dispatch({ + type: "thread.meta.update", + commandId: providerCommandId(event, "thread-meta-update"), + threadId: thread.id, + title: event.payload.name, + }); + } - if (event.type === "runtime.error") { - const runtimeErrorMessage = event.payload.message; - - const shouldApplyRuntimeError = !STRICT_PROVIDER_LIFECYCLE_GUARD - ? true - : activeTurnId === null || eventTurnId === undefined || sameId(activeTurnId, eventTurnId); - - if (shouldApplyRuntimeError) { + if (event.type === "turn.diff.updated") { + const turnId = toTurnId(event.turnId); + if (turnId && (yield* isGitRepoForThread(thread.id))) { + // Skip if a checkpoint already exists for this turn. A real + // (non-placeholder) capture from CheckpointReactor should not + // be clobbered, and dispatching a duplicate placeholder for the + // same turnId would produce an unstable checkpointTurnCount. + if (thread.checkpoints.some((c) => c.turnId === turnId)) { + // Already tracked; no-op. + } else { + const assistantMessageId = MessageId.makeUnsafe( + `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, + ); + const maxTurnCount = thread.checkpoints.reduce( + (max, c) => Math.max(max, c.checkpointTurnCount), + 0, + ); yield* orchestrationEngine.dispatch({ - type: "thread.session.set", - commandId: providerCommandId(event, "runtime-error-session-set"), + type: "thread.turn.diff.complete", + commandId: providerCommandId(event, "thread-turn-diff-complete"), threadId: thread.id, - session: { - threadId: thread.id, - status: "error", - providerName: event.provider, - runtimeMode: thread.session?.runtimeMode ?? "full-access", - activeTurnId: eventTurnId ?? null, - lastError: runtimeErrorMessage, - updatedAt: now, - }, + turnId, + completedAt: now, + checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), + status: "missing", + files: [], + assistantMessageId, + checkpointTurnCount: maxTurnCount + 1, createdAt: now, }); } } + } - if (event.type === "thread.metadata.updated" && event.payload.name) { - yield* orchestrationEngine.dispatch({ - type: "thread.meta.update", - commandId: providerCommandId(event, "thread-meta-update"), - threadId: thread.id, - title: event.payload.name, - }); - } - - if (event.type === "turn.diff.updated") { - const turnId = toTurnId(event.turnId); - if (turnId && (yield* isGitRepoForThread(thread.id))) { - // Skip if a checkpoint already exists for this turn. A real - // (non-placeholder) capture from CheckpointReactor should not - // be clobbered, and dispatching a duplicate placeholder for the - // same turnId would produce an unstable checkpointTurnCount. - if (thread.checkpoints.some((c) => c.turnId === turnId)) { - // Already tracked; no-op. - } else { - const assistantMessageId = MessageId.makeUnsafe( - `assistant:${event.itemId ?? event.turnId ?? event.eventId}`, - ); - const maxTurnCount = thread.checkpoints.reduce( - (max, c) => Math.max(max, c.checkpointTurnCount), - 0, - ); - yield* orchestrationEngine.dispatch({ - type: "thread.turn.diff.complete", - commandId: providerCommandId(event, "thread-turn-diff-complete"), - threadId: thread.id, - turnId, - completedAt: now, - checkpointRef: CheckpointRef.makeUnsafe(`provider-diff:${event.eventId}`), - status: "missing", - files: [], - assistantMessageId, - checkpointTurnCount: maxTurnCount + 1, - createdAt: now, - }); - } - } - } - - const activities = runtimeEventToActivities(event); - yield* Effect.forEach(activities, (activity) => - orchestrationEngine.dispatch({ - type: "thread.activity.append", - commandId: providerCommandId(event, "thread-activity-append"), - threadId: thread.id, - activity, - createdAt: activity.createdAt, - }), - ).pipe(Effect.asVoid); - }); + const activities = runtimeEventToActivities(event); + yield* Effect.forEach(activities, (activity) => + orchestrationEngine.dispatch({ + type: "thread.activity.append", + commandId: providerCommandId(event, "thread-activity-append"), + threadId: thread.id, + activity, + createdAt: activity.createdAt, + }), + ).pipe(Effect.asVoid); + }); const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void; @@ -1248,7 +1241,7 @@ const make = Effect.gen(function* () { const worker = yield* makeDrainableWorker(processInputSafely); - const start: ProviderRuntimeIngestionShape["start"] = Effect.gen(function* () { + const start: ProviderRuntimeIngestionShape["start"] = Effect.fn("start")(function* () { yield* Effect.forkScoped( Stream.runForEach(providerService.streamEvents, (event) => worker.enqueue({ source: "runtime", event }), @@ -1272,5 +1265,5 @@ const make = Effect.gen(function* () { export const ProviderRuntimeIngestionLive = Layer.effect( ProviderRuntimeIngestionService, - make, + make(), ).pipe(Layer.provide(ProjectionTurnRepositoryLive)); diff --git a/apps/server/src/orchestration/Services/CheckpointReactor.ts b/apps/server/src/orchestration/Services/CheckpointReactor.ts index 612bc22acb..539ac784cd 100644 --- a/apps/server/src/orchestration/Services/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Services/CheckpointReactor.ts @@ -22,7 +22,7 @@ export interface CheckpointReactorShape { * Consumes both orchestration-domain and provider-runtime events via an * internal queue. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/orchestration/Services/OrchestrationReactor.ts b/apps/server/src/orchestration/Services/OrchestrationReactor.ts index 258ef2d614..9b628eebda 100644 --- a/apps/server/src/orchestration/Services/OrchestrationReactor.ts +++ b/apps/server/src/orchestration/Services/OrchestrationReactor.ts @@ -19,7 +19,7 @@ export interface OrchestrationReactorShape { * The returned effect must be run in a scope so all worker fibers can be * finalized on shutdown. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; } /** diff --git a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts index 8f20571c15..8f96d8fb99 100644 --- a/apps/server/src/orchestration/Services/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Services/ProviderCommandReactor.ts @@ -22,7 +22,7 @@ export interface ProviderCommandReactorShape { * Filters orchestration domain events to provider-intent types before * processing. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts index 2bbb157f10..f1b95762a2 100644 --- a/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Services/ProviderRuntimeIngestion.ts @@ -22,7 +22,7 @@ export interface ProviderRuntimeIngestionShape { * Uses an internal queue and continues after non-interrupt failures by * logging warnings. */ - readonly start: Effect.Effect; + readonly start: () => Effect.Effect; /** * Resolves when the internal processing queue is empty and idle. diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 7290660cf4..c04d913d52 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -646,7 +646,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< }), ).pipe(Effect.forkIn(subscriptionsScope)); - yield* Scope.provide(orchestrationReactor.start, subscriptionsScope); + yield* Scope.provide(orchestrationReactor.start(), subscriptionsScope); yield* readiness.markOrchestrationSubscriptionsReady; let welcomeBootstrapProjectId: ProjectId | undefined; diff --git a/docs/effect-fn-checklist.md b/docs/effect-fn-checklist.md index d986594849..1addfdf4dd 100644 --- a/docs/effect-fn-checklist.md +++ b/docs/effect-fn-checklist.md @@ -46,7 +46,7 @@ Effect.fn("name")( - [x] `apps/server/src/provider/Layers/CodexAdapter.ts` - [x] `apps/server/src/git/Layers/GitCore.ts` - [x] `apps/server/src/git/Layers/GitManager.ts` -- [ ] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` +- [x] `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` - [x] `apps/server/src/orchestration/Layers/ProjectionPipeline.ts` - [ ] `apps/server/src/orchestration/Layers/OrchestrationEngine.ts` - [ ] `apps/server/src/provider/Layers/EventNdjsonLogger.ts` @@ -115,12 +115,12 @@ Effect.fn("name")( ### `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` (`14`) -- [ ] [finalizeAssistantMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680) -- [ ] [upsertProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722) -- [ ] [finalizeBufferedProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761) -- [ ] [clearTurnStateForSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800) -- [ ] [processRuntimeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908) -- [ ] Nested callback wrappers in this file +- [x] [finalizeAssistantMessage](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L680) +- [x] [upsertProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L722) +- [x] [finalizeBufferedProposedPlan](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L761) +- [x] [clearTurnStateForSession](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L800) +- [x] [processRuntimeEvent](/Users/julius/Development/Work/codething-mvp/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts#L908) +- [x] Nested callback wrappers in this file ### `apps/server/src/provider/Layers/CodexAdapter.ts` (`12`) From 40e7dbdae9cbb4b5b9cfdb0c8b9672709034b810 Mon Sep 17 00:00:00 2001 From: Alexander Vostres Date: Sun, 29 Mar 2026 21:27:20 +0300 Subject: [PATCH 40/66] Fix for broken Codex model selection for 'Text Generation Model' (#1543) --- apps/server/src/serverSettings.test.ts | 37 ++++++++++++++++++++++++++ apps/server/src/serverSettings.ts | 16 ++++++++--- 2 files changed, 50 insertions(+), 3 deletions(-) diff --git a/apps/server/src/serverSettings.test.ts b/apps/server/src/serverSettings.test.ts index f26fece246..c0aec009a0 100644 --- a/apps/server/src/serverSettings.test.ts +++ b/apps/server/src/serverSettings.test.ts @@ -104,6 +104,43 @@ it.layer(NodeServices.layer)("server settings", (it) => { }).pipe(Effect.provide(makeServerSettingsLayer())), ); + it.effect("preserves model when switching providers via textGenerationModelSelection", () => + Effect.gen(function* () { + const serverSettings = yield* ServerSettingsService; + + // Start with Claude text generation selection + yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "claudeAgent", + model: "claude-sonnet-4-6", + options: { + effort: "high", + }, + }, + }); + + // Switch to Codex — the stale Claude "effort" in options must not + // cause the update to lose the selected model. + const next = yield* serverSettings.updateSettings({ + textGenerationModelSelection: { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }, + }); + + assert.deepEqual(next.textGenerationModelSelection, { + provider: "codex", + model: "gpt-5.4", + options: { + reasoningEffort: "high", + }, + }); + }).pipe(Effect.provide(makeServerSettingsLayer())), + ); + it.effect("trims provider path settings when updates are applied", () => Effect.gen(function* () { const serverSettings = yield* ServerSettingsService; diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index f638e7fdfa..d5df84724e 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -27,6 +27,7 @@ import { FileSystem, Layer, Path, + Equal, PubSub, Ref, Schema, @@ -130,6 +131,9 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings }; } +// Values under these keys are compared as a whole — never stripped field-by-field. +const ATOMIC_SETTINGS_KEYS: ReadonlySet = new Set(["textGenerationModelSelection"]); + function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined { if (Array.isArray(current) || Array.isArray(defaults)) { return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current; @@ -146,9 +150,15 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow const next: Record = {}; for (const key of Object.keys(currentRecord)) { - const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]); - if (stripped !== undefined) { - next[key] = stripped; + if (ATOMIC_SETTINGS_KEYS.has(key)) { + if (!Equal.equals(currentRecord[key], defaultsRecord[key])) { + next[key] = currentRecord[key]; + } + } else { + const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]); + if (stripped !== undefined) { + next[key] = stripped; + } } } From d5f2333173f6b01e38d6488dd7a2f157b479195f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 29 Mar 2026 11:47:17 -0700 Subject: [PATCH 41/66] Show hidden thread status in sidebar (#1517) --- apps/web/src/components/Sidebar.logic.test.ts | 4 + apps/web/src/components/Sidebar.logic.ts | 5 + apps/web/src/components/Sidebar.tsx | 96 +++++++++++++------ 3 files changed, 77 insertions(+), 28 deletions(-) diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index b54ec1cb93..d7f93f371d 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -429,6 +429,9 @@ describe("getVisibleThreadsForProject", () => { ThreadId.makeUnsafe("thread-6"), ThreadId.makeUnsafe("thread-8"), ]); + expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([ + ThreadId.makeUnsafe("thread-7"), + ]); }); it("returns all threads when the list is expanded", () => { @@ -449,6 +452,7 @@ describe("getVisibleThreadsForProject", () => { expect(result.visibleThreads.map((thread) => thread.id)).toEqual( threads.map((thread) => thread.id), ); + expect(result.hiddenThreads).toEqual([]); }); }); diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 1e0871e0d2..f911775446 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -244,6 +244,7 @@ export function getVisibleThreadsForProject(input: { previewLimit: number; }): { hasHiddenThreads: boolean; + hiddenThreads: Thread[]; visibleThreads: Thread[]; } { const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input; @@ -252,6 +253,7 @@ export function getVisibleThreadsForProject(input: { if (!hasHiddenThreads || isThreadListExpanded) { return { hasHiddenThreads, + hiddenThreads: [], visibleThreads: [...threads], }; } @@ -260,6 +262,7 @@ export function getVisibleThreadsForProject(input: { if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) { return { hasHiddenThreads: true, + hiddenThreads: threads.slice(previewLimit), visibleThreads: previewThreads, }; } @@ -268,6 +271,7 @@ export function getVisibleThreadsForProject(input: { if (!activeThread) { return { hasHiddenThreads: true, + hiddenThreads: threads.slice(previewLimit), visibleThreads: previewThreads, }; } @@ -276,6 +280,7 @@ export function getVisibleThreadsForProject(input: { return { hasHiddenThreads: true, + hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)), visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)), }; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 100d0e3f47..02aa4fb827 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -151,6 +151,44 @@ interface PrStatusIndicator { type ThreadPr = GitStatusResult["pr"]; +function ThreadStatusLabel({ + status, + compact = false, +}: { + status: NonNullable>; + compact?: boolean; +}) { + if (compact) { + return ( + + + {status.label} + + ); + } + + return ( + + + {status.label} + + ); +} + function terminalStatusFromRunningIds( runningTerminalIds: string[], ): TerminalStatusIndicator | null { @@ -1023,14 +1061,18 @@ export default function Sidebar() { visibleThreads.filter((thread) => thread.projectId === project.id), appSettings.sidebarThreadSortOrder, ); - const projectStatus = resolveProjectStatusIndicator( - projectThreads.map((thread) => + const threadStatuses = new Map( + projectThreads.map((thread) => [ + thread.id, resolveThreadStatusPill({ thread, hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, }), - ), + ]), + ); + const projectStatus = resolveProjectStatusIndicator( + projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null), ); const activeThreadId = routeThreadId ?? undefined; const isThreadListExpanded = expandedThreadListsByProject.has(project.id); @@ -1039,13 +1081,19 @@ export default function Sidebar() { ? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null) : null; const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null; - const { hasHiddenThreads, visibleThreads: visibleProjectThreads } = - getVisibleThreadsForProject({ - threads: projectThreads, - activeThreadId, - isThreadListExpanded, - previewLimit: THREAD_PREVIEW_LIMIT, - }); + const { + hasHiddenThreads, + hiddenThreads, + visibleThreads: visibleProjectThreads, + } = getVisibleThreadsForProject({ + threads: projectThreads, + activeThreadId, + isThreadListExpanded, + previewLimit: THREAD_PREVIEW_LIMIT, + }); + const hiddenThreadStatus = resolveProjectStatusIndicator( + hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null), + ); const orderedProjectThreadIds = projectThreads.map((thread) => thread.id); const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] @@ -1053,10 +1101,12 @@ export default function Sidebar() { return { hasHiddenThreads, + hiddenThreadStatus, orderedProjectThreadIds, project, projectStatus, projectThreads, + threadStatuses, renderedThreads, shouldShowThreadPanel, isThreadListExpanded, @@ -1198,10 +1248,12 @@ export default function Sidebar() { ) { const { hasHiddenThreads, + hiddenThreadStatus, orderedProjectThreadIds, project, projectStatus, projectThreads, + threadStatuses, renderedThreads, shouldShowThreadPanel, isThreadListExpanded, @@ -1213,11 +1265,7 @@ export default function Sidebar() { const jumpLabel = threadJumpLabelById.get(thread.id) ?? null; const isThreadRunning = thread.session?.status === "running" && thread.session.activeTurnId != null; - const threadStatus = resolveThreadStatusPill({ - thread, - hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0, - hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0, - }); + const threadStatus = threadStatuses.get(thread.id) ?? null; const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null); const terminalStatus = terminalStatusFromRunningIds( selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds, @@ -1291,18 +1339,7 @@ export default function Sidebar() { {prStatus.tooltip} )} - {threadStatus && ( - - - {threadStatus.label} - - )} + {threadStatus && } {renamingThreadId === thread.id ? ( { @@ -1548,7 +1585,10 @@ export default function Sidebar() { expandThreadListForProject(project.id); }} > - Show more + + {hiddenThreadStatus && } + Show more + )} From 7b676b76de536b0a9e60fd8bc6e20404815d6294 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 30 Mar 2026 00:17:51 +0530 Subject: [PATCH 42/66] fix: show empty project thread state in sidebar (#1546) --- apps/web/src/components/ChatView.browser.tsx | 13 +++++++++++++ apps/web/src/components/Sidebar.tsx | 13 +++++++++++++ 2 files changed, 26 insertions(+) diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 06cbf0efbd..be9d5f9ac7 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -1041,6 +1041,19 @@ describe("ChatView timeline estimator parity (full app)", () => { }, ); + it("shows an explicit empty state for projects without threads in the sidebar", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createDraftOnlySnapshot(), + }); + + try { + await expect.element(page.getByText("No threads yet")).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + it("opens the project cwd for draft threads without a worktree path", async () => { setDraftThreadWithoutWorktree(); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 02aa4fb827..dbff140b49 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1098,6 +1098,7 @@ export default function Sidebar() { const renderedThreads = pinnedCollapsedThread ? [pinnedCollapsedThread] : visibleProjectThreads; + const showEmptyThreadState = project.expanded && projectThreads.length === 0; return { hasHiddenThreads, @@ -1108,6 +1109,7 @@ export default function Sidebar() { projectThreads, threadStatuses, renderedThreads, + showEmptyThreadState, shouldShowThreadPanel, isThreadListExpanded, }; @@ -1255,6 +1257,7 @@ export default function Sidebar() { projectThreads, threadStatuses, renderedThreads, + showEmptyThreadState, shouldShowThreadPanel, isThreadListExpanded, } = renderedProject; @@ -1572,6 +1575,16 @@ export default function Sidebar() { ref={attachThreadListAutoAnimateRef} className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0" > + {shouldShowThreadPanel && showEmptyThreadState ? ( + +
+ No threads yet +
+
+ ) : null} {shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))} {project.expanded && hasHiddenThreads && !isThreadListExpanded && ( From bf9c828aef6f5901d6be782364665557c07df92e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 29 Mar 2026 17:51:05 -0700 Subject: [PATCH 43/66] Make provider model lists dynamic based on auth context (#1556) Co-authored-by: Cursor Agent Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com> --- apps/server/src/codexAppServerManager.test.ts | 27 +- apps/server/src/codexAppServerManager.ts | 104 +--- .../src/provider/Layers/ClaudeProvider.ts | 589 +++++++++++++----- .../src/provider/Layers/CodexProvider.ts | 426 +++++++------ .../provider/Layers/ProviderRegistry.test.ts | 222 ++++++- apps/server/src/provider/codexAccount.ts | 123 ++++ apps/server/src/provider/codexAppServer.ts | 154 +++++ apps/server/src/provider/providerSnapshot.ts | 6 +- apps/server/src/wsServer.test.ts | 2 +- apps/web/src/components/ChatView.browser.tsx | 2 +- .../components/KeybindingsToast.browser.tsx | 2 +- .../chat/ProviderModelPicker.browser.tsx | 104 +++- .../components/chat/TraitsPicker.browser.tsx | 4 +- .../components/settings/SettingsPanels.tsx | 7 +- apps/web/src/wsNativeApi.test.ts | 2 +- packages/contracts/src/server.ts | 9 +- 16 files changed, 1312 insertions(+), 471 deletions(-) create mode 100644 apps/server/src/provider/codexAccount.ts create mode 100644 apps/server/src/provider/codexAppServer.ts diff --git a/apps/server/src/codexAppServerManager.test.ts b/apps/server/src/codexAppServerManager.test.ts index f614b92302..2f740a7407 100644 --- a/apps/server/src/codexAppServerManager.test.ts +++ b/apps/server/src/codexAppServerManager.test.ts @@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => { }); }); - it("keeps spark enabled for api key accounts", () => { + it("disables spark for api key accounts", () => { expect( readCodexAccountSnapshot({ type: "apiKey", @@ -318,7 +318,20 @@ describe("readCodexAccountSnapshot", () => { ).toEqual({ type: "apiKey", planType: null, - sparkEnabled: true, + sparkEnabled: false, + }); + }); + + it("disables spark for unknown chatgpt plans", () => { + expect( + readCodexAccountSnapshot({ + type: "chatgpt", + email: "unknown@example.com", + }), + ).toEqual({ + type: "chatgpt", + planType: "unknown", + sparkEnabled: false, }); }); }); @@ -343,6 +356,16 @@ describe("resolveCodexModelForAccount", () => { }), ).toBe("gpt-5.3-codex-spark"); }); + + it("falls back from spark to default for api key auth", () => { + expect( + resolveCodexModelForAccount("gpt-5.3-codex-spark", { + type: "apiKey", + planType: null, + sparkEnabled: false, + }), + ).toBe("gpt-5.3-codex"); + }); }); describe("startSession", () => { diff --git a/apps/server/src/codexAppServerManager.ts b/apps/server/src/codexAppServerManager.ts index 1f0abd6d73..3145038647 100644 --- a/apps/server/src/codexAppServerManager.ts +++ b/apps/server/src/codexAppServerManager.ts @@ -26,6 +26,15 @@ import { isCodexCliVersionSupported, parseCodexCliVersion, } from "./provider/codexCliVersion"; +import { + readCodexAccountSnapshot, + resolveCodexModelForAccount, + type CodexAccountSnapshot, +} from "./provider/codexAccount"; +import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer"; + +export { buildCodexInitializeParams } from "./provider/codexAppServer"; +export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount"; type PendingRequestKey = string; @@ -96,23 +105,6 @@ interface JsonRpcNotification { params?: unknown; } -type CodexPlanType = - | "free" - | "go" - | "plus" - | "pro" - | "team" - | "business" - | "enterprise" - | "edu" - | "unknown"; - -interface CodexAccountSnapshot { - readonly type: "apiKey" | "chatgpt" | "unknown"; - readonly planType: CodexPlanType | null; - readonly sparkEnabled: boolean; -} - export interface CodexAppServerSendTurnInput { readonly threadId: ThreadId; readonly input?: string; @@ -162,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [ "unknown thread", "does not exist", ]; -const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; -const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; -const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set(["free", "go", "plus"]); - -function asObject(value: unknown): Record | undefined { - if (!value || typeof value !== "object") { - return undefined; - } - return value as Record; -} - -function asString(value: unknown): string | undefined { - return typeof value === "string" ? value : undefined; -} - -export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot { - const record = asObject(response); - const account = asObject(record?.account) ?? record; - const accountType = asString(account?.type); - - if (accountType === "apiKey") { - return { - type: "apiKey", - planType: null, - sparkEnabled: true, - }; - } - - if (accountType === "chatgpt") { - const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; - return { - type: "chatgpt", - planType, - sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType), - }; - } - - return { - type: "unknown", - planType: null, - sparkEnabled: true, - }; -} - export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `# Plan Mode (Conversational) You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions. @@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): { }; } -export function resolveCodexModelForAccount( - model: string | undefined, - account: CodexAccountSnapshot, -): string | undefined { - if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { - return model; - } - - return CODEX_DEFAULT_MODEL; -} - /** * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe` * wrapper, leaving the actual command running. Use `taskkill /T` to kill the * entire process tree instead. */ function killChildTree(child: ChildProcessWithoutNullStreams): void { - if (process.platform === "win32" && child.pid !== undefined) { - try { - spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); - return; - } catch { - // fallback to direct kill - } - } - child.kill(); + killCodexChildProcess(child); } export function normalizeCodexModelSlug( @@ -402,19 +331,6 @@ export function normalizeCodexModelSlug( return normalized; } -export function buildCodexInitializeParams() { - return { - clientInfo: { - name: "t3code_desktop", - title: "T3 Code Desktop", - version: "0.1.0", - }, - capabilities: { - experimentalApi: true, - }, - } as const; -} - function buildCodexCollaborationMode(input: { readonly interactionMode?: "default" | "plan"; readonly model?: string; diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 75e5a46258..5a11af1c5f 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -4,12 +4,14 @@ import type { ModelCapabilities, ServerProvider, ServerProviderModel, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderState, } from "@t3tools/contracts"; -import { Effect, Equal, Layer, Option, Result, Stream } from "effect"; +import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model"; +import { decodeJsonResult } from "@t3tools/shared/schemaJson"; +import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk"; import { buildServerProvider, @@ -43,8 +45,8 @@ const BUILT_IN_MODELS: ReadonlyArray = [ supportsFastMode: true, supportsThinkingToggle: false, contextWindowOptions: [ - { value: "200k", label: "200k" }, - { value: "1m", label: "1M", isDefault: true }, + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, @@ -63,8 +65,8 @@ const BUILT_IN_MODELS: ReadonlyArray = [ supportsFastMode: false, supportsThinkingToggle: false, contextWindowOptions: [ - { value: "200k", label: "200k" }, - { value: "1m", label: "1M", isDefault: true }, + { value: "200k", label: "200k", isDefault: true }, + { value: "1m", label: "1M" }, ], promptInjectedEffortLevels: ["ultrathink"], } satisfies ModelCapabilities, @@ -117,7 +119,7 @@ export function normalizeClaudeModelOptions( export function parseClaudeAuthStatusFromOutput(result: CommandResult): { readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: Pick; readonly message?: string; } { const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); @@ -129,7 +131,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { ) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Claude Agent authentication status command is unavailable in this version of Claude.", }; @@ -144,7 +146,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { ) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Claude is not authenticated. Run `claude auth login` and try again.", }; } @@ -165,37 +167,286 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): { })(); if (parsedAuth.auth === true) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } if (parsedAuth.auth === false) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Claude is not authenticated. Run `claude auth login` and try again.", }; } if (parsedAuth.attemptedJsonParse) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Could not verify Claude authentication status from JSON output (missing auth marker).", }; } if (result.code === 0) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } const detail = detailFromResult(result); return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: detail ? `Could not verify Claude authentication status. ${detail}` : "Could not verify Claude authentication status.", }; } +// ── Subscription type detection ───────────────────────────────────── +// +// The SDK probe returns typed `AccountInfo.subscriptionType` directly. +// This walker is a best-effort fallback for the `claude auth status` +// JSON output whose shape is not guaranteed. + +/** Keys that directly hold a subscription/plan identifier. */ +const SUBSCRIPTION_TYPE_KEYS = [ + "subscriptionType", + "subscription_type", + "plan", + "tier", + "planType", + "plan_type", +] as const; + +/** Keys whose value may be a nested object containing subscription info. */ +const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const; +const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const; +const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const; + +/** Lift an unknown value into `Option` if it is a non-empty string. */ +const asNonEmptyString = (v: unknown): Option.Option => + typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none(); + +/** Lift an unknown value into `Option` if it is a plain object. */ +const asRecord = (v: unknown): Option.Option> => + typeof v === "object" && v !== null && !globalThis.Array.isArray(v) + ? Option.some(v as Record) + : Option.none(); + +/** + * Walk an unknown parsed JSON value looking for a subscription/plan + * identifier, returning the first match as an `Option`. + */ +function findSubscriptionType(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findSubscriptionType)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + SUBSCRIPTION_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)), + ), + ); + }), + ); +} + +function findAuthMethod(value: unknown): Option.Option { + if (globalThis.Array.isArray(value)) { + return Option.firstSomeOf(value.map(findAuthMethod)); + } + + return asRecord(value).pipe( + Option.flatMap((record) => { + const direct = Option.firstSomeOf( + AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])), + ); + if (Option.isSome(direct)) return direct; + + return Option.firstSomeOf( + AUTH_METHOD_CONTAINER_KEYS.map((key) => + asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)), + ), + ); + }), + ); +} + +/** + * Try to extract a subscription type from the `claude auth status` JSON + * output. This is a zero-cost operation on data we already have. + */ +const decodeUnknownJson = decodeJsonResult(Schema.Unknown); + +function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findSubscriptionType(parsed.success)); +} + +function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined { + const parsed = decodeUnknownJson(result.stdout.trim()); + if (Result.isFailure(parsed)) return undefined; + return Option.getOrUndefined(findAuthMethod(parsed.success)); +} + +// ── Dynamic model capability adjustment ───────────────────────────── + +/** Subscription types where the 1M context window is included in the plan. */ +const PREMIUM_SUBSCRIPTION_TYPES = new Set([ + "max", + "maxplan", + "max5", + "max20", + "enterprise", + "team", +]); + +function toTitleCaseWords(value: string): string { + return value + .split(/[\s_-]+/g) + .filter(Boolean) + .map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase()) + .join(" "); +} + +function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + + switch (normalized) { + case "max": + case "maxplan": + case "max5": + case "max20": + return "Max"; + case "enterprise": + return "Enterprise"; + case "team": + return "Team"; + case "pro": + return "Pro"; + case "free": + return "Free"; + default: + return toTitleCaseWords(subscriptionType!); + } +} + +function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined { + const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized) return undefined; + if (normalized === "apikey") return "apiKey"; + return undefined; +} + +function claudeAuthMetadata(input: { + readonly subscriptionType: string | undefined; + readonly authMethod: string | undefined; +}): { readonly type: string; readonly label: string } | undefined { + if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") { + return { + type: "apiKey", + label: "Claude API Key", + }; + } + + if (input.subscriptionType) { + const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType); + return { + type: input.subscriptionType, + label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`, + }; + } + + return undefined; +} + +/** + * Adjust the built-in model list based on the user's detected subscription. + * + * - Premium tiers (Max, Enterprise, Team): 1M context becomes the default. + * - Other tiers (Pro, free, unknown): 200k context stays the default; + * 1M remains available as a manual option so users can still enable it. + */ +export function adjustModelsForSubscription( + baseModels: ReadonlyArray, + subscriptionType: string | undefined, +): ReadonlyArray { + const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, ""); + if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) { + return baseModels; + } + + // Flip 1M to be the default for premium users + return baseModels.map((model) => { + const caps = model.capabilities; + if (!caps || caps.contextWindowOptions.length === 0) return model; + + return { + ...model, + capabilities: { + ...caps, + contextWindowOptions: caps.contextWindowOptions.map((opt) => + opt.value === "1m" + ? { value: opt.value, label: opt.label, isDefault: true as const } + : { value: opt.value, label: opt.label }, + ), + }, + }; + }); +} + +// ── SDK capability probe ──────────────────────────────────────────── + +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +/** + * Probe account information by spawning a lightweight Claude Agent SDK + * session and reading the initialization result. + * + * The prompt is never sent to the Anthropic API — we abort immediately + * after the local initialization phase completes. This gives us the + * user's subscription type without incurring any token cost. + * + * This is used as a fallback when `claude auth status` does not include + * subscription type information. + */ +const probeClaudeCapabilities = (binaryPath: string) => { + const abort = new AbortController(); + return Effect.tryPromise(async () => { + const q = claudeQuery({ + prompt: ".", + options: { + persistSession: false, + pathToClaudeCodeExecutable: binaryPath, + abortController: abort, + maxTurns: 0, + settingSources: [], + allowedTools: [], + stderr: () => {}, + }, + }); + const init = await q.initializationResult(); + return { subscriptionType: init.account?.subscriptionType }; + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (!abort.signal.aborted) abort.abort(); + }), + ), + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); +}; + const runClaudeCommand = (args: ReadonlyArray) => Effect.gen(function* () { const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( @@ -208,144 +459,81 @@ const runClaudeCommand = (args: ReadonlyArray) => return yield* spawnAndCollect(claudeSettings.binaryPath, command); }); -export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( - function* (): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService - > { - const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.claudeAgent), - ); - const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - claudeSettings.customModels, - ); +export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* ( + resolveSubscriptionType?: (binaryPath: string) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService +> { + const claudeSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.claudeAgent), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels); - if (!claudeSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - enabled: false, - checkedAt, - models, - probe: { - installed: false, - version: null, - status: "warning", - authStatus: "unknown", - message: "Claude is disabled in T3 Code settings.", - }, - }); - } + if (!claudeSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Claude is disabled in T3 Code settings.", + }, + }); + } - const versionProbe = yield* runClaudeCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); + const versionProbe = yield* runClaudeCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - authStatus: "unknown", - message: isCommandMissingCause(error) - ? "Claude Agent CLI (`claude`) is not installed or not on PATH." - : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, - }, - }); - } + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Claude Agent CLI (`claude`) is not installed or not on PATH." + : `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } - if (Option.isNone(versionProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: null, - status: "error", - authStatus: "unknown", - message: - "Claude Agent CLI is installed but failed to run. Timed out while running command.", - }, - }); - } + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: + "Claude Agent CLI is installed but failed to run. Timed out while running command.", + }, + }); + } - const version = versionProbe.success.value; - const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: detail - ? `Claude Agent CLI is installed but failed to run. ${detail}` - : "Claude Agent CLI is installed but failed to run.", - }, - }); - } - - const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - error instanceof Error - ? `Could not verify Claude authentication status: ${error.message}.` - : "Could not verify Claude authentication status.", - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: claudeSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - "Could not verify Claude authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); + const version = versionProbe.success.value; + const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); return buildServerProvider({ provider: PROVIDER, enabled: claudeSettings.enabled, @@ -354,13 +542,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")( probe: { installed: true, version: parsedVersion, - status: parsed.status, - authStatus: parsed.authStatus, - ...(parsed.message ? { message: parsed.message } : {}), + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Claude Agent CLI is installed but failed to run. ${detail}` + : "Claude Agent CLI is installed but failed to run.", }, }); - }, -); + } + + // ── Auth check + subscription detection ──────────────────────────── + + const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + + // Determine subscription type from multiple sources (cheapest first): + // 1. `claude auth status` JSON output (may or may not contain it) + // 2. Cached SDK probe (spawns a Claude process on miss, reads + // `initializationResult()` for account metadata, then aborts + // immediately — no API tokens are consumed) + + let subscriptionType: string | undefined; + let authMethod: string | undefined; + + if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) { + subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value); + authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value); + } + + if (!subscriptionType && resolveSubscriptionType) { + subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath); + } + + const resolvedModels = adjustModelsForSubscription(models, subscriptionType); + + // ── Handle auth results (same logic as before, adjusted models) ── + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Claude authentication status: ${error.message}.` + : "Could not verify Claude authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Claude authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value); + const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod }); + return buildServerProvider({ + provider: PROVIDER, + enabled: claudeSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authMetadata ? authMetadata : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); export const ClaudeProviderLive = Layer.effect( ClaudeProvider, @@ -368,7 +642,16 @@ export const ClaudeProviderLive = Layer.effect( const serverSettings = yield* ServerSettingsService; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const checkProvider = checkClaudeProviderStatus().pipe( + const subscriptionProbeCache = yield* Cache.make({ + capacity: 1, + timeToLive: Duration.minutes(5), + lookup: (binaryPath: string) => + probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)), + }); + + const checkProvider = checkClaudeProviderStatus((binaryPath) => + Cache.get(subscriptionProbeCache, binaryPath), + ).pipe( Effect.provideService(ServerSettingsService, serverSettings), Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), ); diff --git a/apps/server/src/provider/Layers/CodexProvider.ts b/apps/server/src/provider/Layers/CodexProvider.ts index 3335a59dab..e2f31c13f1 100644 --- a/apps/server/src/provider/Layers/CodexProvider.ts +++ b/apps/server/src/provider/Layers/CodexProvider.ts @@ -5,10 +5,21 @@ import type { CodexSettings, ServerProvider, ServerProviderModel, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderState, } from "@t3tools/contracts"; -import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect"; +import { + Cache, + Duration, + Effect, + Equal, + FileSystem, + Layer, + Option, + Path, + Result, + Stream, +} from "effect"; import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"; import { resolveEffort } from "@t3tools/shared/model"; @@ -29,6 +40,13 @@ import { isCodexCliVersionSupported, parseCodexCliVersion, } from "../codexCliVersion"; +import { + adjustCodexModelsForAccount, + codexAuthSubLabel, + codexAuthSubType, + type CodexAccountSnapshot, +} from "../codexAccount"; +import { probeCodexAccount } from "../codexAppServer"; import { CodexProvider } from "../Services/CodexProvider"; import { ServerSettingsError, ServerSettingsService } from "../../serverSettings"; @@ -170,7 +188,7 @@ export function normalizeCodexModelOptions( export function parseAuthStatusFromOutput(result: CommandResult): { readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: Pick; readonly message?: string; } { const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase(); @@ -182,7 +200,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): { ) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Codex CLI authentication status command is unavailable in this Codex version.", }; } @@ -196,7 +214,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): { ) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Codex CLI is not authenticated. Run `codex login` and try again.", }; } @@ -217,31 +235,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): { })(); if (parsedAuth.auth === true) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } if (parsedAuth.auth === false) { return { status: "error", - authStatus: "unauthenticated", + auth: { status: "unauthenticated" }, message: "Codex CLI is not authenticated. Run `codex login` and try again.", }; } if (parsedAuth.attemptedJsonParse) { return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: "Could not verify Codex authentication status from JSON output (missing auth marker).", }; } if (result.code === 0) { - return { status: "ready", authStatus: "authenticated" }; + return { status: "ready", auth: { status: "authenticated" } }; } const detail = detailFromResult(result); return { status: "warning", - authStatus: "unknown", + auth: { status: "unknown" }, message: detail ? `Could not verify Codex authentication status. ${detail}` : "Could not verify Codex authentication status.", @@ -290,6 +308,21 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe( Effect.orElseSucceed(() => false), ); +const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000; + +const probeCodexCapabilities = (input: { + readonly binaryPath: string; + readonly homePath?: string; +}) => + Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe( + Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS), + Effect.result, + Effect.map((result) => { + if (Result.isFailure(result)) return undefined; + return Option.isSome(result.success) ? result.success.value : undefined; + }), + ); + const runCodexCommand = (args: ReadonlyArray) => Effect.gen(function* () { const settingsService = yield* ServerSettingsService; @@ -306,179 +339,88 @@ const runCodexCommand = (args: ReadonlyArray) => return yield* spawnAndCollect(codexSettings.binaryPath, command); }); -export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")( - function* (): Effect.fn.Return< - ServerProvider, - ServerSettingsError, - | ChildProcessSpawner.ChildProcessSpawner - | FileSystem.FileSystem - | Path.Path - | ServerSettingsService - > { - const codexSettings = yield* Effect.service(ServerSettingsService).pipe( - Effect.flatMap((service) => service.getSettings), - Effect.map((settings) => settings.providers.codex), - ); - const checkedAt = new Date().toISOString(); - const models = providerModelsFromSettings( - BUILT_IN_MODELS, - PROVIDER, - codexSettings.customModels, - ); +export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* ( + resolveAccount?: (input: { + readonly binaryPath: string; + readonly homePath?: string; + }) => Effect.Effect, +): Effect.fn.Return< + ServerProvider, + ServerSettingsError, + | ChildProcessSpawner.ChildProcessSpawner + | FileSystem.FileSystem + | Path.Path + | ServerSettingsService +> { + const codexSettings = yield* Effect.service(ServerSettingsService).pipe( + Effect.flatMap((service) => service.getSettings), + Effect.map((settings) => settings.providers.codex), + ); + const checkedAt = new Date().toISOString(); + const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels); - if (!codexSettings.enabled) { - return buildServerProvider({ - provider: PROVIDER, - enabled: false, - checkedAt, - models, - probe: { - installed: false, - version: null, - status: "warning", - authStatus: "unknown", - message: "Codex is disabled in T3 Code settings.", - }, - }); - } + if (!codexSettings.enabled) { + return buildServerProvider({ + provider: PROVIDER, + enabled: false, + checkedAt, + models, + probe: { + installed: false, + version: null, + status: "warning", + auth: { status: "unknown" }, + message: "Codex is disabled in T3 Code settings.", + }, + }); + } - const versionProbe = yield* runCodexCommand(["--version"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); + const versionProbe = yield* runCodexCommand(["--version"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); - if (Result.isFailure(versionProbe)) { - const error = versionProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: !isCommandMissingCause(error), - version: null, - status: "error", - authStatus: "unknown", - message: isCommandMissingCause(error) - ? "Codex CLI (`codex`) is not installed or not on PATH." - : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`, - }, - }); - } + if (Result.isFailure(versionProbe)) { + const error = versionProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: !isCommandMissingCause(error), + version: null, + status: "error", + auth: { status: "unknown" }, + message: isCommandMissingCause(error) + ? "Codex CLI (`codex`) is not installed or not on PATH." + : `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`, + }, + }); + } - if (Option.isNone(versionProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: null, - status: "error", - authStatus: "unknown", - message: "Codex CLI is installed but failed to run. Timed out while running command.", - }, - }); - } + if (Option.isNone(versionProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: null, + status: "error", + auth: { status: "unknown" }, + message: "Codex CLI is installed but failed to run. Timed out while running command.", + }, + }); + } - const version = versionProbe.success.value; - const parsedVersion = - parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? - parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); - if (version.code !== 0) { - const detail = detailFromResult(version); - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: detail - ? `Codex CLI is installed but failed to run. ${detail}` - : "Codex CLI is installed but failed to run.", - }, - }); - } - - if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "error", - authStatus: "unknown", - message: formatCodexCliUpgradeMessage(parsedVersion), - }, - }); - } - - if (yield* hasCustomModelProvider) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "ready", - authStatus: "unknown", - message: "Using a custom Codex model provider; OpenAI login check skipped.", - }, - }); - } - - const authProbe = yield* runCodexCommand(["login", "status"]).pipe( - Effect.timeoutOption(DEFAULT_TIMEOUT_MS), - Effect.result, - ); - - if (Result.isFailure(authProbe)) { - const error = authProbe.failure; - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: - error instanceof Error - ? `Could not verify Codex authentication status: ${error.message}.` - : "Could not verify Codex authentication status.", - }, - }); - } - - if (Option.isNone(authProbe.success)) { - return buildServerProvider({ - provider: PROVIDER, - enabled: codexSettings.enabled, - checkedAt, - models, - probe: { - installed: true, - version: parsedVersion, - status: "warning", - authStatus: "unknown", - message: "Could not verify Codex authentication status. Timed out while running command.", - }, - }); - } - - const parsed = parseAuthStatusFromOutput(authProbe.success.value); + const version = versionProbe.success.value; + const parsedVersion = + parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ?? + parseGenericCliVersion(`${version.stdout}\n${version.stderr}`); + if (version.code !== 0) { + const detail = detailFromResult(version); return buildServerProvider({ provider: PROVIDER, enabled: codexSettings.enabled, @@ -487,13 +429,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")( probe: { installed: true, version: parsedVersion, - status: parsed.status, - authStatus: parsed.authStatus, - ...(parsed.message ? { message: parsed.message } : {}), + status: "error", + auth: { status: "unknown" }, + message: detail + ? `Codex CLI is installed but failed to run. ${detail}` + : "Codex CLI is installed but failed to run.", }, }); - }, -); + } + + if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "error", + auth: { status: "unknown" }, + message: formatCodexCliUpgradeMessage(parsedVersion), + }, + }); + } + + if (yield* hasCustomModelProvider) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models, + probe: { + installed: true, + version: parsedVersion, + status: "ready", + auth: { status: "unknown" }, + message: "Using a custom Codex model provider; OpenAI login check skipped.", + }, + }); + } + + const authProbe = yield* runCodexCommand(["login", "status"]).pipe( + Effect.timeoutOption(DEFAULT_TIMEOUT_MS), + Effect.result, + ); + const account = resolveAccount + ? yield* resolveAccount({ + binaryPath: codexSettings.binaryPath, + homePath: codexSettings.homePath, + }) + : undefined; + const resolvedModels = adjustCodexModelsForAccount(models, account); + + if (Result.isFailure(authProbe)) { + const error = authProbe.failure; + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: + error instanceof Error + ? `Could not verify Codex authentication status: ${error.message}.` + : "Could not verify Codex authentication status.", + }, + }); + } + + if (Option.isNone(authProbe.success)) { + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: "warning", + auth: { status: "unknown" }, + message: "Could not verify Codex authentication status. Timed out while running command.", + }, + }); + } + + const parsed = parseAuthStatusFromOutput(authProbe.success.value); + const authType = codexAuthSubType(account); + const authLabel = codexAuthSubLabel(account); + return buildServerProvider({ + provider: PROVIDER, + enabled: codexSettings.enabled, + checkedAt, + models: resolvedModels, + probe: { + installed: true, + version: parsedVersion, + status: parsed.status, + auth: { + ...parsed.auth, + ...(authType ? { type: authType } : {}), + ...(authLabel ? { label: authLabel } : {}), + }, + ...(parsed.message ? { message: parsed.message } : {}), + }, + }); +}); export const CodexProviderLive = Layer.effect( CodexProvider, @@ -502,8 +547,21 @@ export const CodexProviderLive = Layer.effect( const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const accountProbeCache = yield* Cache.make({ + capacity: 4, + timeToLive: Duration.minutes(5), + lookup: (key: string) => { + const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined]; + return probeCodexCapabilities({ + binaryPath, + ...(homePath ? { homePath } : {}), + }); + }, + }); - const checkProvider = checkCodexProviderStatus().pipe( + const checkProvider = checkCodexProviderStatus((input) => + Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])), + ).pipe( Effect.provideService(ServerSettingsService, serverSettings), Effect.provideService(FileSystem.FileSystem, fileSystem), Effect.provideService(Path.Path, path), diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 3657abeb6d..116c008d67 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -173,7 +173,133 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "authenticated"); + assert.strictEqual(status.auth.status, "authenticated"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns the codex plan type in auth and keeps spark for supported plans", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "pro" as const, + sparkEnabled: true, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "pro"); + assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + true, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for unsupported chatgpt plans", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "plus" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "plus"); + assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("hides spark from codex models for non-pro chatgpt subscriptions", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "chatgpt" as const, + planType: "team" as const, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.auth.type, "team"); + assert.strictEqual(status.auth.label, "ChatGPT Team Subscription"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 }; + if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for codex api key auth", () => + Effect.gen(function* () { + yield* withTempCodexHome(); + const status = yield* checkCodexProviderStatus(() => + Effect.succeed({ + type: "apiKey" as const, + planType: null, + sparkEnabled: false, + }), + ); + + assert.strictEqual(status.provider, "codex"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "OpenAI API Key"); + assert.deepStrictEqual( + status.models.some((model) => model.slug === "gpt-5.3-codex-spark"), + false, + ); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -235,7 +361,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.installed, true); assert.strictEqual(status.status, "ready"); - assert.strictEqual(status.authStatus, "authenticated"); + assert.strictEqual(status.auth.status, "authenticated"); } finally { process.env.PATH = previousPath; } @@ -249,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI (`codex`) is not installed or not on PATH.", @@ -264,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.", @@ -287,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Codex CLI is not authenticated. Run `codex login` and try again.", @@ -313,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Codex CLI is not authenticated. Run `codex login` and try again.", @@ -338,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "warning"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Codex CLI authentication status command is unavailable in this Codex version.", @@ -366,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status: "ready", enabled: true, installed: true, - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], @@ -376,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( status: "warning", enabled: true, installed: true, - authStatus: "unknown", + auth: { status: "unknown" }, checkedAt: "2026-03-25T00:00:00.000Z", version: "1.0.0", models: [], @@ -494,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "codex"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Using a custom Codex model provider; OpenAI login check skipped.", @@ -537,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( const status = yield* checkCodexProviderStatus(); // The auth probe runs and sees "not logged in" → error assert.strictEqual(status.status, "error"); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -558,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("exit code 0 with no auth markers is ready", () => { const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with authenticated=false is unauthenticated", () => { @@ -568,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.authStatus, "unauthenticated"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); }); it("JSON without auth marker is warning", () => { @@ -578,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.authStatus, "unknown"); + assert.strictEqual(parsed.auth.status, "unknown"); }); }); @@ -715,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "ready"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "authenticated"); + assert.strictEqual(status.auth.status, "authenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -733,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( ), ); + it.effect("returns a display label for claude subscription types", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan")); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "maxplan"); + assert.strictEqual(status.auth.label, "Claude Max Subscription"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + + it.effect("returns an api key label for claude api key auth", () => + Effect.gen(function* () { + const status = yield* checkClaudeProviderStatus(); + assert.strictEqual(status.provider, "claudeAgent"); + assert.strictEqual(status.status, "ready"); + assert.strictEqual(status.auth.status, "authenticated"); + assert.strictEqual(status.auth.type, "apiKey"); + assert.strictEqual(status.auth.label, "Claude API Key"); + }).pipe( + Effect.provide( + mockSpawnerLayer((args) => { + const joined = args.join(" "); + if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 }; + if (joined === "auth status") + return { + stdout: '{"loggedIn":true,"authMethod":"api-key"}\n', + stderr: "", + code: 0, + }; + throw new Error(`Unexpected args: ${joined}`); + }), + ), + ), + ); + it.effect("returns unavailable when claude is missing", () => Effect.gen(function* () { const status = yield* checkClaudeProviderStatus(); assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, false); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Claude Agent CLI (`claude`) is not installed or not on PATH.", @@ -771,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); assert.strictEqual( status.message, "Claude is not authenticated. Run `claude auth login` and try again.", @@ -799,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "error"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unauthenticated"); + assert.strictEqual(status.auth.status, "unauthenticated"); }).pipe( Effect.provide( mockSpawnerLayer((args) => { @@ -819,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( assert.strictEqual(status.provider, "claudeAgent"); assert.strictEqual(status.status, "warning"); assert.strictEqual(status.installed, true); - assert.strictEqual(status.authStatus, "unknown"); + assert.strictEqual(status.auth.status, "unknown"); assert.strictEqual( status.message, "Claude Agent authentication status command is unavailable in this version of Claude.", @@ -844,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( it("exit code 0 with no auth markers is ready", () => { const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with loggedIn=true is authenticated", () => { @@ -854,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "ready"); - assert.strictEqual(parsed.authStatus, "authenticated"); + assert.strictEqual(parsed.auth.status, "authenticated"); }); it("JSON with loggedIn=false is unauthenticated", () => { @@ -864,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "error"); - assert.strictEqual(parsed.authStatus, "unauthenticated"); + assert.strictEqual(parsed.auth.status, "unauthenticated"); }); it("JSON without auth marker is warning", () => { @@ -874,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))( code: 0, }); assert.strictEqual(parsed.status, "warning"); - assert.strictEqual(parsed.authStatus, "unknown"); + assert.strictEqual(parsed.auth.status, "unknown"); }); }); }, diff --git a/apps/server/src/provider/codexAccount.ts b/apps/server/src/provider/codexAccount.ts new file mode 100644 index 0000000000..1db00250f6 --- /dev/null +++ b/apps/server/src/provider/codexAccount.ts @@ -0,0 +1,123 @@ +import type { ServerProviderModel } from "@t3tools/contracts"; + +export type CodexPlanType = + | "free" + | "go" + | "plus" + | "pro" + | "team" + | "business" + | "enterprise" + | "edu" + | "unknown"; + +export interface CodexAccountSnapshot { + readonly type: "apiKey" | "chatgpt" | "unknown"; + readonly planType: CodexPlanType | null; + readonly sparkEnabled: boolean; +} + +export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex"; +export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark"; +const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set(["pro"]); + +function asObject(value: unknown): Record | undefined { + if (!value || typeof value !== "object") { + return undefined; + } + return value as Record; +} + +function asString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot { + const record = asObject(response); + const account = asObject(record?.account) ?? record; + const accountType = asString(account?.type); + + if (accountType === "apiKey") { + return { + type: "apiKey", + planType: null, + sparkEnabled: false, + }; + } + + if (accountType === "chatgpt") { + const planType = (account?.planType as CodexPlanType | null) ?? "unknown"; + return { + type: "chatgpt", + planType, + sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType), + }; + } + + return { + type: "unknown", + planType: null, + sparkEnabled: false, + }; +} + +export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined { + if (account?.type === "apiKey") { + return "apiKey"; + } + + if (account?.type !== "chatgpt") { + return undefined; + } + + return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt"; +} + +export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined { + switch (codexAuthSubType(account)) { + case "apiKey": + return "OpenAI API Key"; + case "chatgpt": + return "ChatGPT Subscription"; + case "free": + return "ChatGPT Free Subscription"; + case "go": + return "ChatGPT Go Subscription"; + case "plus": + return "ChatGPT Plus Subscription"; + case "pro": + return "ChatGPT Pro Subscription"; + case "team": + return "ChatGPT Team Subscription"; + case "business": + return "ChatGPT Business Subscription"; + case "enterprise": + return "ChatGPT Enterprise Subscription"; + case "edu": + return "ChatGPT Edu Subscription"; + default: + return undefined; + } +} + +export function adjustCodexModelsForAccount( + baseModels: ReadonlyArray, + account: CodexAccountSnapshot | undefined, +): ReadonlyArray { + if (account?.sparkEnabled !== false) { + return baseModels; + } + + return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL); +} + +export function resolveCodexModelForAccount( + model: string | undefined, + account: CodexAccountSnapshot, +): string | undefined { + if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) { + return model; + } + + return CODEX_DEFAULT_MODEL; +} diff --git a/apps/server/src/provider/codexAppServer.ts b/apps/server/src/provider/codexAppServer.ts new file mode 100644 index 0000000000..d25fc3533e --- /dev/null +++ b/apps/server/src/provider/codexAppServer.ts @@ -0,0 +1,154 @@ +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; +import readline from "node:readline"; +import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount"; + +interface JsonRpcProbeResponse { + readonly id?: unknown; + readonly result?: unknown; + readonly error?: { + readonly message?: unknown; + }; +} + +function readErrorMessage(response: JsonRpcProbeResponse): string | undefined { + return typeof response.error?.message === "string" ? response.error.message : undefined; +} + +export function buildCodexInitializeParams() { + return { + clientInfo: { + name: "t3code_desktop", + title: "T3 Code Desktop", + version: "0.1.0", + }, + capabilities: { + experimentalApi: true, + }, + } as const; +} + +export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void { + if (process.platform === "win32" && child.pid !== undefined) { + try { + spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }); + return; + } catch { + // Fall through to direct kill when taskkill is unavailable. + } + } + + child.kill(); +} + +export async function probeCodexAccount(input: { + readonly binaryPath: string; + readonly homePath?: string; + readonly signal?: AbortSignal; +}): Promise { + return await new Promise((resolve, reject) => { + const child = spawn(input.binaryPath, ["app-server"], { + env: { + ...process.env, + ...(input.homePath ? { CODEX_HOME: input.homePath } : {}), + }, + stdio: ["pipe", "pipe", "pipe"], + shell: process.platform === "win32", + }); + const output = readline.createInterface({ input: child.stdout }); + + let completed = false; + + const cleanup = () => { + output.removeAllListeners(); + output.close(); + child.removeAllListeners(); + if (!child.killed) { + killCodexChildProcess(child); + } + }; + + const finish = (callback: () => void) => { + if (completed) return; + completed = true; + cleanup(); + callback(); + }; + + const fail = (error: unknown) => + finish(() => + reject( + error instanceof Error + ? error + : new Error(`Codex account probe failed: ${String(error)}.`), + ), + ); + + if (input.signal?.aborted) { + fail(new Error("Codex account probe aborted.")); + return; + } + input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted."))); + + const writeMessage = (message: unknown) => { + if (!child.stdin.writable) { + fail(new Error("Cannot write to codex app-server stdin.")); + return; + } + + child.stdin.write(`${JSON.stringify(message)}\n`); + }; + + output.on("line", (line) => { + let parsed: unknown; + try { + parsed = JSON.parse(line); + } catch { + fail(new Error("Received invalid JSON from codex app-server during account probe.")); + return; + } + + if (!parsed || typeof parsed !== "object") { + return; + } + + const response = parsed as JsonRpcProbeResponse; + if (response.id === 1) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`initialize failed: ${errorMessage}`)); + return; + } + + writeMessage({ method: "initialized" }); + writeMessage({ id: 2, method: "account/read", params: {} }); + return; + } + + if (response.id === 2) { + const errorMessage = readErrorMessage(response); + if (errorMessage) { + fail(new Error(`account/read failed: ${errorMessage}`)); + return; + } + + finish(() => resolve(readCodexAccountSnapshot(response.result))); + } + }); + + child.once("error", fail); + child.once("exit", (code, signal) => { + if (completed) return; + fail( + new Error( + `codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`, + ), + ); + }); + + writeMessage({ + id: 1, + method: "initialize", + params: buildCodexInitializeParams(), + }); + }); +} diff --git a/apps/server/src/provider/providerSnapshot.ts b/apps/server/src/provider/providerSnapshot.ts index 65f820bd8e..e1243c4bd0 100644 --- a/apps/server/src/provider/providerSnapshot.ts +++ b/apps/server/src/provider/providerSnapshot.ts @@ -1,6 +1,6 @@ import type { ServerProvider, - ServerProviderAuthStatus, + ServerProviderAuth, ServerProviderModel, ServerProviderState, } from "@t3tools/contracts"; @@ -21,7 +21,7 @@ export interface ProviderProbeResult { readonly installed: boolean; readonly version: string | null; readonly status: Exclude; - readonly authStatus: ServerProviderAuthStatus; + readonly auth: ServerProviderAuth; readonly message?: string; } @@ -137,7 +137,7 @@ export function buildServerProvider(input: { installed: input.probe.installed, version: input.probe.version, status: input.enabled ? input.probe.status : "disabled", - authStatus: input.probe.authStatus, + auth: input.probe.auth, checkedAt: input.checkedAt, ...(input.probe.message ? { message: input.probe.message } : {}), models: input.models, diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index 826b9ad6fd..6dcf8b38ed 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -74,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray = [ installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", models: [], }, diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index be9d5f9ac7..64c3922b57 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -117,7 +117,7 @@ function createBaseServerConfig(): ServerConfig { installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: NOW_ISO, models: [], }, diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index 5d6ec94a50..ba21af4b77 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig { installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: NOW_ISO, models: [], }, diff --git a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx index 679cbff321..13fe6faba2 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.browser.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.browser.tsx @@ -22,7 +22,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: new Date().toISOString(), models: [ { @@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ installed: true, version: "1.0.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: new Date().toISOString(), models: [ { @@ -110,6 +110,19 @@ const TEST_PROVIDERS: ReadonlyArray = [ }, ]; +function buildCodexProvider(models: ServerProvider["models"]): ServerProvider { + return { + provider: "codex", + enabled: true, + installed: true, + version: "0.116.0", + status: "ready", + auth: { status: "authenticated" }, + checkedAt: new Date().toISOString(), + models, + }; +} + async function mountPicker(props: { provider: ProviderKind; model: string; @@ -241,6 +254,93 @@ describe("ProviderModelPicker", () => { } }); + it("only shows codex spark when the server reports it for the account", async () => { + const providersWithoutSpark: ReadonlyArray = [ + buildCodexProvider([ + { + slug: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + TEST_PROVIDERS[1]!, + ]; + const providersWithSpark: ReadonlyArray = [ + buildCodexProvider([ + { + slug: "gpt-5.3-codex", + name: "GPT-5.3 Codex", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + { + slug: "gpt-5.3-codex-spark", + name: "GPT-5.3 Codex Spark", + isCustom: false, + capabilities: { + reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")], + supportsFastMode: true, + supportsThinkingToggle: false, + contextWindowOptions: [], + promptInjectedEffortLevels: [], + }, + }, + ]), + TEST_PROVIDERS[1]!, + ]; + + const hidden = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + providers: providersWithoutSpark, + }); + + try { + await page.getByRole("button").click(); + await page.getByRole("menuitem", { name: "Codex" }).hover(); + + await vi.waitFor(() => { + const text = document.body.textContent ?? ""; + expect(text).toContain("GPT-5.3 Codex"); + expect(text).not.toContain("GPT-5.3 Codex Spark"); + }); + } finally { + await hidden.cleanup(); + } + + const visible = await mountPicker({ + provider: "claudeAgent", + model: "claude-opus-4-6", + lockedProvider: null, + providers: providersWithSpark, + }); + + try { + await page.getByRole("button").click(); + await page.getByRole("menuitem", { name: "Codex" }).hover(); + + await vi.waitFor(() => { + expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark"); + }); + } finally { + await visible.cleanup(); + } + }); + it("dispatches the canonical slug when a model is selected", async () => { const mounted = await mountPicker({ provider: "claudeAgent", diff --git a/apps/web/src/components/chat/TraitsPicker.browser.tsx b/apps/web/src/components/chat/TraitsPicker.browser.tsx index 9dea3651ea..74c22e6431 100644 --- a/apps/web/src/components/chat/TraitsPicker.browser.tsx +++ b/apps/web/src/components/chat/TraitsPicker.browser.tsx @@ -35,7 +35,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ installed: true, version: "0.1.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", models: [ { @@ -61,7 +61,7 @@ const TEST_PROVIDERS: ReadonlyArray = [ installed: true, version: "0.1.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", models: [ { diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index f9fdb1d615..b7fde0c5f6 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -146,13 +146,14 @@ function getProviderSummary(provider: ServerProvider | undefined) { detail: provider.message ?? "CLI not detected on PATH.", }; } - if (provider.authStatus === "authenticated") { + if (provider.auth.status === "authenticated") { + const authLabel = provider.auth.label ?? provider.auth.type; return { - headline: "Authenticated", + headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated", detail: provider.message ?? null, }; } - if (provider.authStatus === "unauthenticated") { + if (provider.auth.status === "unauthenticated") { return { headline: "Not authenticated", detail: provider.message ?? null, diff --git a/apps/web/src/wsNativeApi.test.ts b/apps/web/src/wsNativeApi.test.ts index 9e612543d0..be53eefd9b 100644 --- a/apps/web/src/wsNativeApi.test.ts +++ b/apps/web/src/wsNativeApi.test.ts @@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray = [ installed: true, version: "0.116.0", status: "ready", - authStatus: "authenticated", + auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", models: [], }, diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 78d0879cd2..08910c3ecc 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -35,6 +35,13 @@ export const ServerProviderAuthStatus = Schema.Literals([ ]); export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type; +export const ServerProviderAuth = Schema.Struct({ + status: ServerProviderAuthStatus, + type: Schema.optional(TrimmedNonEmptyString), + label: Schema.optional(TrimmedNonEmptyString), +}); +export type ServerProviderAuth = typeof ServerProviderAuth.Type; + export const ServerProviderModel = Schema.Struct({ slug: TrimmedNonEmptyString, name: TrimmedNonEmptyString, @@ -49,7 +56,7 @@ export const ServerProvider = Schema.Struct({ installed: Schema.Boolean, version: Schema.NullOr(TrimmedNonEmptyString), status: ServerProviderState, - authStatus: ServerProviderAuthStatus, + auth: ServerProviderAuth, checkedAt: IsoDateTime, message: Schema.optional(TrimmedNonEmptyString), models: Schema.Array(ServerProviderModel), From fc6507066ed348a459cb675ffd67eaf117f02987 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Mon, 30 Mar 2026 06:23:03 +0530 Subject: [PATCH 44/66] fix(windows): hover-effect-fix-in-the-branch-ui (#1559) Co-authored-by: Ewan --- apps/web/src/components/BranchToolbarBranchSelector.tsx | 1 - apps/web/src/components/ui/autocomplete.tsx | 2 +- apps/web/src/components/ui/combobox.tsx | 2 +- 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index b41ea0a6e1..c1a43adc90 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -397,7 +397,6 @@ export function BranchToolbarBranchSelector({ key={itemValue} index={index} value={itemValue} - className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined} style={style} onClick={() => selectBranch(branch)} > diff --git a/apps/web/src/components/ui/autocomplete.tsx b/apps/web/src/components/ui/autocomplete.tsx index 98ad1e431a..676db613ae 100644 --- a/apps/web/src/components/ui/autocomplete.tsx +++ b/apps/web/src/components/ui/autocomplete.tsx @@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti return ( Date: Mon, 30 Mar 2026 10:53:21 +1000 Subject: [PATCH 45/66] fix(web): preserve scroll when collapsing large changed-files trees (#1113) --- apps/web/src/components/chat/ChangedFilesTree.tsx | 1 + apps/web/src/components/chat/MessagesTimeline.tsx | 8 +++++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/ChangedFilesTree.tsx b/apps/web/src/components/chat/ChangedFilesTree.tsx index 0174a77088..a13ddad30d 100644 --- a/apps/web/src/components/chat/ChangedFilesTree.tsx +++ b/apps/web/src/components/chat/ChangedFilesTree.tsx @@ -50,6 +50,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
- ) : hoveredThreadId === thread.id && !isThreadRunning ? ( + ) : !isThreadRunning ? ( appSettings.confirmThreadArchive ? ( - +
+ +
) : ( { - event.stopPropagation(); - }} - onClick={(event) => { - event.preventDefault(); - event.stopPropagation(); - setHoveredThreadId((current) => - current === thread.id ? null : current, - ); - void attemptArchiveThread(thread.id); - }} - > - - +
+ +
} /> Archive
) - ) : ( - <> - {showThreadJumpHints && jumpLabel ? ( - - {jumpLabel} - - ) : ( - - {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} - - )} - - )} + ) : null} + + {showThreadJumpHints && jumpLabel ? ( + + {jumpLabel} + + ) : ( + + {formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)} + + )} +
From 0bb787b90d1d280cd772c490ce4edc5e048c84d2 Mon Sep 17 00:00:00 2001 From: Ivor Date: Mon, 30 Mar 2026 10:39:23 +0530 Subject: [PATCH 52/66] Clarify provider setup in README (#1406) --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5f842e3709..fd7a4c0309 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,11 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more ## How to use > [!WARNING] -> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work. +> T3 Code currently supports Codex and Claude. +> Install and authenticate at least one provider before use: +> +> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login` +> - Claude: install Claude Code and run `claude auth login` ```bash npx t3 From 145ddfc4081e258b892f3b074ec6c1f40ae13839 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 29 Mar 2026 22:33:05 -0700 Subject: [PATCH 53/66] Document T3 Code install methods (#1564) --- README.md | 36 +++++++++++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index fd7a4c0309..fe7c2219b2 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon). -## How to use +## Installation > [!WARNING] > T3 Code currently supports Codex and Claude. @@ -11,13 +11,43 @@ T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more > - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login` > - Claude: install Claude Code and run `claude auth login` +### Run without installing + ```bash npx t3 ``` -You can also just install the desktop app. It's cooler. +### Desktop app -Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases) +Install the desktop app using whichever method fits your platform: + +#### Direct download + +[GitHub Releases](https://github.com/pingdotgg/t3code/releases) + +#### Windows (`winget`) + +Reference: [pingdotgg/t3code#1544](https://github.com/pingdotgg/t3code/issues/1544), [winget-pkgs manifest](https://github.com/microsoft/winget-pkgs/tree/master/manifests/t/T3Tools/T3Code/) + +```bash +winget install T3Tools.T3Code +``` + +#### macOS (Homebrew) + +Reference: [t3-code cask](https://formulae.brew.sh/cask/t3-code#default) + +```bash +brew install --cask t3-code +``` + +#### Arch Linux (AUR) + +Reference: [t3code-bin](https://aur.archlinux.org/packages/t3code-bin) + +```bash +yay -S t3code-bin +``` ## Some notes From f47c1f10465762d108082aa687681c8461c5e017 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Sun, 29 Mar 2026 22:37:28 -0700 Subject: [PATCH 54/66] Update README.md (#1565) --- README.md | 12 +----------- 1 file changed, 1 insertion(+), 11 deletions(-) diff --git a/README.md b/README.md index fe7c2219b2..d7b2fccb8f 100644 --- a/README.md +++ b/README.md @@ -19,32 +19,22 @@ npx t3 ### Desktop app -Install the desktop app using whichever method fits your platform: - -#### Direct download - -[GitHub Releases](https://github.com/pingdotgg/t3code/releases) +Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry: #### Windows (`winget`) -Reference: [pingdotgg/t3code#1544](https://github.com/pingdotgg/t3code/issues/1544), [winget-pkgs manifest](https://github.com/microsoft/winget-pkgs/tree/master/manifests/t/T3Tools/T3Code/) - ```bash winget install T3Tools.T3Code ``` #### macOS (Homebrew) -Reference: [t3-code cask](https://formulae.brew.sh/cask/t3-code#default) - ```bash brew install --cask t3-code ``` #### Arch Linux (AUR) -Reference: [t3code-bin](https://aur.archlinux.org/packages/t3code-bin) - ```bash yay -S t3code-bin ``` From 8622b952cae4d520381bbd22c2c1d410de5f3285 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Mar 2026 10:19:11 -0700 Subject: [PATCH 55/66] Refactor terminal manager onto Effect runtime (#1525) --- .../src/terminal/Layers/Manager.test.ts | 1330 ++++++---- apps/server/src/terminal/Layers/Manager.ts | 2332 ++++++++++------- apps/server/src/terminal/Services/Manager.ts | 109 +- apps/server/src/wsServer.test.ts | 35 +- apps/server/src/wsServer.ts | 4 +- packages/contracts/src/ipc.ts | 12 +- packages/contracts/src/terminal.ts | 4 +- packages/shared/package.json | 4 + .../shared/src/KeyedCoalescingWorker.test.ts | 96 + packages/shared/src/KeyedCoalescingWorker.ts | 140 + 10 files changed, 2482 insertions(+), 1584 deletions(-) create mode 100644 packages/shared/src/KeyedCoalescingWorker.test.ts create mode 100644 packages/shared/src/KeyedCoalescingWorker.ts diff --git a/apps/server/src/terminal/Layers/Manager.test.ts b/apps/server/src/terminal/Layers/Manager.test.ts index 5717fda39e..ccdd477178 100644 --- a/apps/server/src/terminal/Layers/Manager.test.ts +++ b/apps/server/src/terminal/Layers/Manager.test.ts @@ -1,24 +1,38 @@ -import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; import { DEFAULT_TERMINAL_ID, type TerminalEvent, type TerminalOpenInput, type TerminalRestartInput, } from "@t3tools/contracts"; -import { afterEach, describe, expect, it } from "vitest"; - import { - PtySpawnError, + Duration, + Effect, + Encoding, + Exit, + Fiber, + FileSystem, + Option, + PlatformError, + Ref, + Schedule, + Scope, +} from "effect"; +import { TestClock } from "effect/testing"; +import { expect } from "vitest"; + +import type { TerminalManagerShape } from "../Services/Manager"; +import { type PtyAdapterShape, type PtyExitEvent, type PtyProcess, type PtySpawnInput, + PtySpawnError, } from "../Services/PTY"; -import { TerminalManagerRuntime } from "./Manager"; -import { Effect, Encoding } from "effect"; +import { makeTerminalManagerWithOptions } from "./Manager"; class FakePtyProcess implements PtyProcess { readonly writes: string[] = []; @@ -107,27 +121,29 @@ class FakePtyAdapter implements PtyAdapterShape { } } -function waitFor(predicate: () => boolean, timeoutMs = 800): Promise { - const started = Date.now(); - return new Promise((resolve, reject) => { - const poll = () => { - if (predicate()) { - resolve(); - return; - } - if (Date.now() - started > timeoutMs) { - reject(new Error("Timed out waiting for condition")); - return; - } - setTimeout(poll, 15); - }; - poll(); - }); -} +const waitFor = ( + predicate: Effect.Effect, + timeout: Duration.Input = 800, +): Effect.Effect => + predicate.pipe( + Effect.filterOrFail( + (done) => done, + () => new Error("Condition not met"), + ), + Effect.retry(Schedule.spaced("15 millis")), + Effect.timeoutOption(timeout), + Effect.flatMap((result) => + Option.match(result, { + onNone: () => Effect.fail(new Error("Timed out waiting for condition")), + onSome: () => Effect.void, + }), + ), + ); function openInput(overrides: Partial = {}): TerminalOpenInput { return { threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, cwd: process.cwd(), cols: 100, rows: 24, @@ -138,6 +154,7 @@ function openInput(overrides: Partial = {}): TerminalOpenInpu function restartInput(overrides: Partial = {}): TerminalRestartInput { return { threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, cwd: process.cwd(), cols: 100, rows: 24, @@ -169,598 +186,777 @@ function multiTerminalHistoryLogPath( return path.join(logsDir, multiTerminalHistoryLogName(threadId, terminalId)); } -describe("TerminalManager", () => { - const tempDirs: string[] = []; +interface CreateManagerOptions { + shellResolver?: () => string; + subprocessChecker?: (terminalPid: number) => Effect.Effect; + subprocessPollIntervalMs?: number; + processKillGraceMs?: number; + maxRetainedInactiveSessions?: number; + ptyAdapter?: FakePtyAdapter; +} - afterEach(() => { - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); +interface ManagerFixture { + readonly baseDir: string; + readonly logsDir: string; + readonly ptyAdapter: FakePtyAdapter; + readonly manager: TerminalManagerShape; + readonly getEvents: Effect.Effect>; +} - function makeManager( - historyLineLimit = 5, - options: { - shellResolver?: () => string; - subprocessChecker?: (terminalPid: number) => Promise; - subprocessPollIntervalMs?: number; - processKillGraceMs?: number; - maxRetainedInactiveSessions?: number; - ptyAdapter?: FakePtyAdapter; - } = {}, - ) { - const logsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-terminal-")); - tempDirs.push(logsDir); - const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter(); - const manager = new TerminalManagerRuntime({ - logsDir, - ptyAdapter, - historyLineLimit, - shellResolver: options.shellResolver ?? (() => "/bin/bash"), - ...(options.subprocessChecker ? { subprocessChecker: options.subprocessChecker } : {}), - ...(options.subprocessPollIntervalMs - ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } - : {}), - ...(options.processKillGraceMs ? { processKillGraceMs: options.processKillGraceMs } : {}), - ...(options.maxRetainedInactiveSessions - ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } - : {}), - }); - return { logsDir, ptyAdapter, manager }; - } +const createManager = ( + historyLineLimit = 5, + options: CreateManagerOptions = {}, +): Effect.Effect< + ManagerFixture, + PlatformError.PlatformError, + FileSystem.FileSystem | Scope.Scope +> => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + Effect.gen(function* () { + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" }); + const logsDir = path.join(baseDir, "userdata", "logs", "terminals"); + const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter(); - it("spawns lazily and reuses running terminal per thread", async () => { - const { manager, ptyAdapter } = makeManager(); - const [first, second] = await Promise.all([ - manager.open(openInput()), - manager.open(openInput()), - ]); - const third = await manager.open(openInput()); + const manager = yield* makeTerminalManagerWithOptions({ + logsDir, + historyLineLimit, + ptyAdapter, + ...(options.shellResolver !== undefined ? { shellResolver: options.shellResolver } : {}), + ...(options.subprocessChecker !== undefined + ? { subprocessChecker: options.subprocessChecker } + : {}), + ...(options.subprocessPollIntervalMs !== undefined + ? { subprocessPollIntervalMs: options.subprocessPollIntervalMs } + : {}), + ...(options.processKillGraceMs !== undefined + ? { processKillGraceMs: options.processKillGraceMs } + : {}), + ...(options.maxRetainedInactiveSessions !== undefined + ? { maxRetainedInactiveSessions: options.maxRetainedInactiveSessions } + : {}), + }); + const eventsRef = yield* Ref.make>([]); + const scope = yield* Effect.scope; + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(eventsRef, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); - expect(first.threadId).toBe("thread-1"); - expect(first.terminalId).toBe("default"); - expect(second.threadId).toBe("thread-1"); - expect(third.threadId).toBe("thread-1"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); + return { + baseDir, + logsDir, + ptyAdapter, + manager, + getEvents: Ref.get(eventsRef), + }; + }), + ); - manager.dispose(); - }); +it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => { + it.effect("spawns lazily and reuses running terminal per thread", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + const [first, second] = yield* Effect.all( + [manager.open(openInput()), manager.open(openInput())], + { concurrency: "unbounded" }, + ); + const third = yield* manager.open(openInput()); - it("supports asynchronous PTY spawn effects", async () => { - const { manager, ptyAdapter } = makeManager(5, { ptyAdapter: new FakePtyAdapter("async") }); + assert.equal(first.threadId, "thread-1"); + assert.equal(first.terminalId, "default"); + assert.equal(second.threadId, "thread-1"); + assert.equal(third.threadId, "thread-1"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + }), + ); - const snapshot = await manager.open(openInput()); - - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs).toHaveLength(1); - expect(ptyAdapter.processes).toHaveLength(1); - - manager.dispose(); - }); - - it("forwards write and resize to active pty process", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.write({ threadId: "thread-1", data: "ls\n" }); - await manager.resize({ threadId: "thread-1", cols: 120, rows: 30 }); - - expect(process.writes).toEqual(["ls\n"]); - expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); - - manager.dispose(); - }); - - it("resizes running terminal on open when a different size is requested", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ cols: 100, rows: 24 })); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.open(openInput({ cols: 140, rows: 40 })); - - expect(process.resizeCalls).toEqual([{ cols: 140, rows: 40 }]); - - manager.dispose(); - }); - - it("preserves existing terminal size on open when size is omitted", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ cols: 100, rows: 24 })); - const ptyProcess = ptyAdapter.processes[0]; - expect(ptyProcess).toBeDefined(); - if (!ptyProcess) return; - - await manager.open({ - threadId: "thread-1", - cwd: globalThis.process.cwd(), - }); - - expect(ptyProcess.resizeCalls).toEqual([]); - - ptyProcess.emitExit({ exitCode: 0, signal: 0 }); - await manager.open({ - threadId: "thread-1", - cwd: globalThis.process.cwd(), - }); - - const resumedSpawn = ptyAdapter.spawnInputs[1]; - expect(resumedSpawn).toBeDefined(); - if (!resumedSpawn) return; - expect(resumedSpawn.cols).toBe(100); - expect(resumedSpawn.rows).toBe(24); - - manager.dispose(); - }); - - it("uses default dimensions when opening a new terminal without size hints", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open({ - threadId: "thread-1", - cwd: process.cwd(), - }); - - const spawned = ptyAdapter.spawnInputs[0]; - expect(spawned).toBeDefined(); - if (!spawned) return; - expect(spawned.cols).toBe(120); - expect(spawned.rows).toBe(30); - - manager.dispose(); - }); - - it("supports multiple terminals per thread with isolated sessions", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "term-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - await manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); - await manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - - expect(first.writes).toEqual(["pwd\n"]); - expect(second.writes).toEqual(["ls\n"]); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - - manager.dispose(); - }); - - it("clears transcript and emits cleared event", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("hello\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - await manager.clear({ threadId: "thread-1" }); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - expect(events.some((event) => event.type === "cleared")).toBe(true); - expect( - events.some( - (event) => - event.type === "cleared" && - event.threadId === "thread-1" && - event.terminalId === "default", - ), - ).toBe(true); - - manager.dispose(); - }); - - it("restarts terminal with empty transcript and respawns pty", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const firstProcess = ptyAdapter.processes[0]; - expect(firstProcess).toBeDefined(); - if (!firstProcess) return; - firstProcess.emitData("before restart\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - const snapshot = await manager.restart(restartInput()); - expect(snapshot.history).toBe(""); - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - await waitFor(() => fs.readFileSync(historyLogPath(logsDir), "utf8") === ""); - - manager.dispose(); - }); - - it("emits exited event and reopens with clean transcript after exit", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("old data\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - process.emitExit({ exitCode: 0, signal: 0 }); - - await waitFor(() => events.some((event) => event.type === "exited")); - const reopened = await manager.open(openInput()); - - expect(reopened.history).toBe(""); - expect(ptyAdapter.spawnInputs).toHaveLength(2); - expect(fs.readFileSync(historyLogPath(logsDir), "utf8")).toBe(""); - - manager.dispose(); - }); - - it("ignores trailing writes after terminal exit", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitExit({ exitCode: 0, signal: 0 }); - - await expect(manager.write({ threadId: "thread-1", data: "\r" })).resolves.toBeUndefined(); - expect(process.writes).toEqual([]); - - manager.dispose(); - }); - - it("emits subprocess activity events when child-process state changes", async () => { - let hasRunningSubprocess = false; - const { manager } = makeManager(5, { - subprocessChecker: async () => hasRunningSubprocess, - subprocessPollIntervalMs: 20, - }); - const events: TerminalEvent[] = []; - manager.on("event", (event) => { - events.push(event); - }); - - await manager.open(openInput()); - await waitFor(() => events.some((event) => event.type === "started")); - expect(events.some((event) => event.type === "activity")).toBe(false); - - hasRunningSubprocess = true; - await waitFor( - () => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true), - 1_200, + const makeDirectory = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.makeDirectory(filePath, { recursive: true }), ); - hasRunningSubprocess = false; - await waitFor( - () => - events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false), - 1_200, + const chmod = (filePath: string, mode: number) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.chmod(filePath, mode)); + + const pathExists = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.exists(filePath)); + + const readFileString = (filePath: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => fs.readFileString(filePath)); + + const writeFileString = (filePath: string, contents: string) => + Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) => + fs.writeFileString(filePath, contents), ); - manager.dispose(); - }); + it.effect("preserves non-notFound cwd stat failures", () => + Effect.gen(function* () { + const { manager, baseDir } = yield* createManager(); + const blockedRoot = path.join(baseDir, "blocked-root"); + const blockedCwd = path.join(blockedRoot, "cwd"); + yield* makeDirectory(blockedCwd); + yield* chmod(blockedRoot, 0o000); - it("caps persisted history to configured line limit", async () => { - const { manager, ptyAdapter } = makeManager(3); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const error = yield* Effect.flip(manager.open(openInput({ cwd: blockedCwd }))).pipe( + Effect.ensuring(chmod(blockedRoot, 0o755).pipe(Effect.ignore)), + ); - process.emitData("line1\nline2\nline3\nline4\n"); - await manager.close({ threadId: "thread-1" }); + expect(error).toMatchObject({ + _tag: "TerminalCwdError", + cwd: blockedCwd, + reason: "statFailed", + }); + }), + ); - const reopened = await manager.open(openInput()); - const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); - expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); + it.effect("supports asynchronous PTY spawn effects", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); - manager.dispose(); - }); + const snapshot = yield* manager.open(openInput()); - it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(1); + expect(ptyAdapter.processes).toHaveLength(1); + }), + ); - process.emitData("prompt "); - process.emitData("\u001b[32mok\u001b[0m "); - process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); - process.emitData("\u001b[1;1R"); - process.emitData("done\n"); + it.effect("forwards write and resize to active pty process", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - await manager.close({ threadId: "thread-1" }); + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "ls\n", + }); + yield* manager.resize({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + cols: 120, + rows: 30, + }); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n"); + expect(process.writes).toEqual(["ls\n"]); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); - manager.dispose(); - }); + it.effect("resizes running terminal on open when a different size is requested", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ cols: 100, rows: 24 })); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + const reopened = yield* manager.open(openInput({ cols: 120, rows: 30 })); - process.emitData("before clear\n"); - process.emitData("\u001b[H\u001b[2J"); - process.emitData("prompt "); - process.emitData("\u001b]11;"); - process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); - process.emitData("R\u001b[36mdone\u001b[0m\n"); + assert.equal(reopened.status, "running"); + expect(process.resizeCalls).toEqual([{ cols: 120, rows: 30 }]); + }), + ); - await manager.close({ threadId: "thread-1" }); + it.effect("supports multiple terminals per thread independently", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "term-2" })); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe( - "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", - ); + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; - manager.dispose(); - }); + yield* manager.write({ threadId: "thread-1", terminalId: "default", data: "pwd\n" }); + yield* manager.write({ threadId: "thread-1", terminalId: "term-2", data: "ls\n" }); - it("does not leak final bytes from ESC sequences with intermediate bytes", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; + expect(first.writes).toEqual(["pwd\n"]); + expect(second.writes).toEqual(["ls\n"]); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + }), + ); - process.emitData("before "); - process.emitData("\u001b(B"); - process.emitData("after\n"); + it.effect("clears transcript and emits cleared event", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - await manager.close({ threadId: "thread-1" }); + process.emitData("hello\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID }); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("before \u001b(Bafter\n"); - - manager.dispose(); - }); - - it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - process.emitData("before "); - process.emitData("\u001b("); - process.emitData("Bafter\n"); - - await manager.close({ threadId: "thread-1" }); - - const reopened = await manager.open(openInput()); - expect(reopened.history).toBe("before \u001b(Bafter\n"); - - manager.dispose(); - }); - - it("deletes history file when close(deleteHistory=true)", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - process.emitData("bye\n"); - await waitFor(() => fs.existsSync(historyLogPath(logsDir))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - expect(fs.existsSync(historyLogPath(logsDir))).toBe(false); - - manager.dispose(); - }); - - it("closes all terminals for a thread when close omits terminalId", async () => { - const { manager, ptyAdapter, logsDir } = makeManager(); - await manager.open(openInput({ terminalId: "default" })); - await manager.open(openInput({ terminalId: "sidecar" })); - const defaultProcess = ptyAdapter.processes[0]; - const sidecarProcess = ptyAdapter.processes[1]; - expect(defaultProcess).toBeDefined(); - expect(sidecarProcess).toBeDefined(); - if (!defaultProcess || !sidecarProcess) return; - - defaultProcess.emitData("default\n"); - sidecarProcess.emitData("sidecar\n"); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); - await waitFor(() => fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); - - await manager.close({ threadId: "thread-1", deleteHistory: true }); - - expect(defaultProcess.killed).toBe(true); - expect(sidecarProcess.killed).toBe(true); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(false); - expect(fs.existsSync(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(false); - - manager.dispose(); - }); - - it("escalates terminal shutdown to SIGKILL when process does not exit in time", async () => { - const { manager, ptyAdapter } = makeManager(5, { processKillGraceMs: 10 }); - await manager.open(openInput()); - const process = ptyAdapter.processes[0]; - expect(process).toBeDefined(); - if (!process) return; - - await manager.close({ threadId: "thread-1" }); - await waitFor(() => process.killSignals.includes("SIGKILL")); - - expect(process.killSignals[0]).toBe("SIGTERM"); - expect(process.killSignals).toContain("SIGKILL"); - - manager.dispose(); - }); - - it("evicts oldest inactive terminal sessions when retention limit is exceeded", async () => { - const { manager, ptyAdapter } = makeManager(5, { maxRetainedInactiveSessions: 1 }); - - await manager.open(openInput({ threadId: "thread-1" })); - await manager.open(openInput({ threadId: "thread-2" })); - - const first = ptyAdapter.processes[0]; - const second = ptyAdapter.processes[1]; - expect(first).toBeDefined(); - expect(second).toBeDefined(); - if (!first || !second) return; - - first.emitExit({ exitCode: 0, signal: 0 }); - await new Promise((resolve) => setTimeout(resolve, 5)); - second.emitExit({ exitCode: 0, signal: 0 }); - - await waitFor(() => { - const sessions = (manager as unknown as { sessions: Map }).sessions; - return sessions.size === 1; - }); - - const sessions = (manager as unknown as { sessions: Map }).sessions; - const keys = [...sessions.keys()]; - expect(keys).toEqual(["thread-2\u0000default"]); - - manager.dispose(); - }); - - it("migrates legacy transcript filenames to terminal-scoped history path on open", async () => { - const { manager, logsDir } = makeManager(); - const legacyPath = path.join(logsDir, "thread-1.log"); - const nextPath = historyLogPath(logsDir); - fs.writeFileSync(legacyPath, "legacy-line\n", "utf8"); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.history).toBe("legacy-line\n"); - expect(fs.existsSync(nextPath)).toBe(true); - expect(fs.readFileSync(nextPath, "utf8")).toBe("legacy-line\n"); - expect(fs.existsSync(legacyPath)).toBe(false); - - manager.dispose(); - }); - - it("retries with fallback shells when preferred shell spawn fails", async () => { - const { manager, ptyAdapter } = makeManager(5, { - shellResolver: () => "/definitely/missing-shell -l", - }); - ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); - - const snapshot = await manager.open(openInput()); - - expect(snapshot.status).toBe("running"); - expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); - expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); - - if (process.platform === "win32") { + const events = yield* getEvents; + expect(events.some((event) => event.type === "cleared")).toBe(true); expect( - ptyAdapter.spawnInputs.some( - (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", + events.some( + (event) => + event.type === "cleared" && + event.threadId === "thread-1" && + event.terminalId === "default", ), ).toBe(true); - } else { - expect( - ptyAdapter.spawnInputs - .slice(1) - .some((input) => input.shell !== "/definitely/missing-shell"), - ).toBe(true); - } + }), + ); - manager.dispose(); - }); + it.effect("restarts terminal with empty transcript and respawns pty", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const firstProcess = ptyAdapter.processes[0]; + expect(firstProcess).toBeDefined(); + if (!firstProcess) return; + firstProcess.emitData("before restart\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); - it("filters app runtime env variables from terminal sessions", async () => { - const originalValues = new Map(); - const setEnv = (key: string, value: string | undefined) => { - if (!originalValues.has(key)) { - originalValues.set(key, process.env[key]); + const snapshot = yield* manager.restart(restartInput()); + assert.equal(snapshot.history, ""); + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === "")); + }), + ); + + it.effect("emits exited event and reopens with clean transcript after exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("old data\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => events.some((event) => event.type === "exited")), + ); + const reopened = yield* manager.open(openInput()); + + assert.equal(reopened.history, ""); + expect(ptyAdapter.spawnInputs).toHaveLength(2); + expect(yield* readFileString(historyLogPath(logsDir))).toBe(""); + }), + ); + + it.effect("ignores trailing writes after terminal exit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* manager.write({ + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + data: "\r", + }); + expect(process.writes).toEqual([]); + }), + ); + + it.effect("emits subprocess activity events when child-process state changes", () => + Effect.gen(function* () { + let hasRunningSubprocess = false; + const { manager, getEvents } = yield* createManager(5, { + subprocessChecker: () => Effect.succeed(hasRunningSubprocess), + subprocessPollIntervalMs: 20, + }); + + yield* manager.open(openInput()); + expect((yield* getEvents).some((event) => event.type === "activity")).toBe(false); + + hasRunningSubprocess = true; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "activity" && event.hasRunningSubprocess === true), + ), + "1200 millis", + ); + + hasRunningSubprocess = false; + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "activity" && event.hasRunningSubprocess === false), + ), + "1200 millis", + ); + }), + ); + + it.effect("does not invoke subprocess polling until a terminal session is running", () => + Effect.gen(function* () { + let checks = 0; + const { manager } = yield* createManager(5, { + subprocessChecker: () => { + checks += 1; + return Effect.succeed(false); + }, + subprocessPollIntervalMs: 20, + }); + + yield* Effect.sleep("80 millis"); + assert.equal(checks, 0); + + yield* manager.open(openInput()); + yield* waitFor( + Effect.sync(() => checks > 0), + "1200 millis", + ); + }), + ); + + it.effect("caps persisted history to configured line limit", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(3); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("line1\nline2\nline3\nline4\n"); + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + const nonEmptyLines = reopened.history.split("\n").filter((line) => line.length > 0); + expect(nonEmptyLines).toEqual(["line2", "line3", "line4"]); + }), + ); + + it.effect("strips replay-unsafe terminal query and reply sequences from persisted history", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("prompt "); + process.emitData("\u001b[32mok\u001b[0m "); + process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007"); + process.emitData("\u001b[1;1R"); + process.emitData("done\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "prompt \u001b[32mok\u001b[0m done\n"); + }), + ); + + it.effect( + "preserves clear and style control sequences while dropping chunk-split query traffic", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before clear\n"); + process.emitData("\u001b[H\u001b[2J"); + process.emitData("prompt "); + process.emitData("\u001b]11;"); + process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1"); + process.emitData("R\u001b[36mdone\u001b[0m\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal( + reopened.history, + "before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n", + ); + }), + ); + + it.effect("does not leak final bytes from ESC sequences with intermediate bytes", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b(B"); + process.emitData("after\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect( + "preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", + () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("before "); + process.emitData("\u001b("); + process.emitData("Bafter\n"); + + yield* manager.close({ threadId: "thread-1" }); + + const reopened = yield* manager.open(openInput()); + assert.equal(reopened.history, "before \u001b(Bafter\n"); + }), + ); + + it.effect("deletes history file when close(deleteHistory=true)", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + process.emitData("bye\n"); + yield* waitFor(pathExists(historyLogPath(logsDir))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + expect(yield* pathExists(historyLogPath(logsDir))).toBe(false); + }), + ); + + it.effect("closes all terminals for a thread when close omits terminalId", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir } = yield* createManager(); + yield* manager.open(openInput({ terminalId: "default" })); + yield* manager.open(openInput({ terminalId: "sidecar" })); + const defaultProcess = ptyAdapter.processes[0]; + const sidecarProcess = ptyAdapter.processes[1]; + expect(defaultProcess).toBeDefined(); + expect(sidecarProcess).toBeDefined(); + if (!defaultProcess || !sidecarProcess) return; + + defaultProcess.emitData("default\n"); + sidecarProcess.emitData("sidecar\n"); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))); + yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))); + + yield* manager.close({ threadId: "thread-1", deleteHistory: true }); + + assert.equal(defaultProcess.killed, true); + assert.equal(sidecarProcess.killed, true); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe( + false, + ); + expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe( + false, + ); + }), + ); + + it.effect("escalates terminal shutdown to SIGKILL when process does not exit in time", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { processKillGraceMs: 10 }); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeFiber = yield* manager.close({ threadId: "thread-1" }).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeFiber); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); + + it.effect("evicts oldest inactive terminal sessions when retention limit is exceeded", () => + Effect.gen(function* () { + const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager(5, { + maxRetainedInactiveSessions: 1, + }); + + yield* manager.open(openInput({ threadId: "thread-1" })); + yield* manager.open(openInput({ threadId: "thread-2" })); + + const first = ptyAdapter.processes[0]; + const second = ptyAdapter.processes[1]; + expect(first).toBeDefined(); + expect(second).toBeDefined(); + if (!first || !second) return; + + first.emitData("first-history\n"); + second.emitData("second-history\n"); + yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1"))); + first.emitExit({ exitCode: 0, signal: 0 }); + yield* Effect.sleep(Duration.millis(5)); + second.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map( + getEvents, + (events) => events.filter((event) => event.type === "exited").length === 2, + ), + ); + + const reopenedSecond = yield* manager.open(openInput({ threadId: "thread-2" })); + const reopenedFirst = yield* manager.open(openInput({ threadId: "thread-1" })); + + assert.equal(reopenedFirst.history, "first-history\n"); + assert.equal(reopenedSecond.history, ""); + }), + ); + + it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () => + Effect.gen(function* () { + const { manager, logsDir } = yield* createManager(); + const legacyPath = path.join(logsDir, "thread-1.log"); + const nextPath = historyLogPath(logsDir); + yield* writeFileString(legacyPath, "legacy-line\n"); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.history, "legacy-line\n"); + expect(yield* pathExists(nextPath)).toBe(true); + expect(yield* readFileString(nextPath)).toBe("legacy-line\n"); + expect(yield* pathExists(legacyPath)).toBe(false); + }), + ); + + it.effect("retries with fallback shells when preferred shell spawn fails", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/definitely/missing-shell -l", + }); + ptyAdapter.spawnFailures.push(new Error("posix_spawnp failed.")); + + const snapshot = yield* manager.open(openInput()); + + assert.equal(snapshot.status, "running"); + expect(ptyAdapter.spawnInputs.length).toBeGreaterThanOrEqual(2); + expect(ptyAdapter.spawnInputs[0]?.shell).toBe("/definitely/missing-shell"); + + if (process.platform === "win32") { + expect( + ptyAdapter.spawnInputs.some( + (input) => input.shell === "cmd.exe" || input.shell === "powershell.exe", + ), + ).toBe(true); + } else { + expect( + ptyAdapter.spawnInputs + .slice(1) + .some((input) => input.shell !== "/definitely/missing-shell"), + ).toBe(true); } - if (value === undefined) { - delete process.env[key]; - return; - } - process.env[key] = value; - }; - const restoreEnv = () => { - for (const [key, value] of originalValues) { + }), + ); + + it.effect("filters app runtime env variables from terminal sessions", () => + Effect.gen(function* () { + const originalValues = new Map(); + const setEnv = (key: string, value: string | undefined) => { + if (!originalValues.has(key)) { + originalValues.set(key, process.env[key]); + } if (value === undefined) { delete process.env[key]; - } else { - process.env[key] = value; + return; } + process.env[key] = value; + }; + const restoreEnv = () => { + for (const [key, value] of originalValues) { + if (value === undefined) { + delete process.env[key]; + } else { + process.env[key] = value; + } + } + }; + + setEnv("PORT", "5173"); + setEnv("T3CODE_PORT", "3773"); + setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); + setEnv("TEST_TERMINAL_KEEP", "keep-me"); + + try { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; + + expect(spawnInput.env.PORT).toBeUndefined(); + expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); + expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); + expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + } finally { + restoreEnv(); } - }; + }), + ); - setEnv("PORT", "5173"); - setEnv("T3CODE_PORT", "3773"); - setEnv("VITE_DEV_SERVER_URL", "http://localhost:5173"); - setEnv("TEST_TERMINAL_KEEP", "keep-me"); - - try { - const { manager, ptyAdapter } = makeManager(); - await manager.open(openInput()); + it.effect("injects runtime env overrides into spawned terminals", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(); + yield* manager.open( + openInput({ + env: { + T3CODE_PROJECT_ROOT: "/repo", + T3CODE_WORKTREE_PATH: "/repo/worktree-a", + CUSTOM_FLAG: "1", + }, + }), + ); const spawnInput = ptyAdapter.spawnInputs[0]; expect(spawnInput).toBeDefined(); if (!spawnInput) return; - expect(spawnInput.env.PORT).toBeUndefined(); - expect(spawnInput.env.T3CODE_PORT).toBeUndefined(); - expect(spawnInput.env.VITE_DEV_SERVER_URL).toBeUndefined(); - expect(spawnInput.env.TEST_TERMINAL_KEEP).toBe("keep-me"); + assert.equal(spawnInput.env.T3CODE_PROJECT_ROOT, "/repo"); + assert.equal(spawnInput.env.T3CODE_WORKTREE_PATH, "/repo/worktree-a"); + assert.equal(spawnInput.env.CUSTOM_FLAG, "1"); + }), + ); - manager.dispose(); - } finally { - restoreEnv(); - } - }); + it.effect("starts zsh with prompt spacer disabled to avoid `%` end markers", () => + Effect.gen(function* () { + if (process.platform === "win32") return; + const { manager, ptyAdapter } = yield* createManager(5, { + shellResolver: () => "/bin/zsh", + }); + yield* manager.open(openInput()); + const spawnInput = ptyAdapter.spawnInputs[0]; + expect(spawnInput).toBeDefined(); + if (!spawnInput) return; - it("injects runtime env overrides into spawned terminals", async () => { - const { manager, ptyAdapter } = makeManager(); - await manager.open( - openInput({ - env: { - T3CODE_PROJECT_ROOT: "/repo", - T3CODE_WORKTREE_PATH: "/repo/worktree-a", - CUSTOM_FLAG: "1", - }, - }), - ); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; + expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); + }), + ); - expect(spawnInput.env.T3CODE_PROJECT_ROOT).toBe("/repo"); - expect(spawnInput.env.T3CODE_WORKTREE_PATH).toBe("/repo/worktree-a"); - expect(spawnInput.env.CUSTOM_FLAG).toBe("1"); + it.effect("bridges PTY callbacks back into Effect-managed event streaming", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); - manager.dispose(); - }); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; - it("starts zsh with prompt spacer disabled to avoid `%` end markers", async () => { - if (process.platform === "win32") return; - const { manager, ptyAdapter } = makeManager(5, { - shellResolver: () => "/bin/zsh", - }); - await manager.open(openInput()); - const spawnInput = ptyAdapter.spawnInputs[0]; - expect(spawnInput).toBeDefined(); - if (!spawnInput) return; + process.emitData("hello from callback\n"); - expect(spawnInput.shell).toBe("/bin/zsh"); - expect(spawnInput.args).toEqual(["-o", "nopromptsp"]); + yield* waitFor( + Effect.map(getEvents, (events) => + events.some((event) => event.type === "output" && event.data === "hello from callback\n"), + ), + "1200 millis", + ); + }), + ); - manager.dispose(); - }); + it.effect("pushes PTY callbacks to direct event subscribers", () => + Effect.gen(function* () { + const { manager, ptyAdapter } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + const scope = yield* Effect.scope; + const subscriberEvents = yield* Ref.make>([]); + const unsubscribe = yield* manager.subscribe((event) => + Ref.update(subscriberEvents, (events) => [...events, event]), + ); + yield* Scope.addFinalizer(scope, Effect.sync(unsubscribe)); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("hello from subscriber\n"); + + yield* waitFor( + Effect.map(Ref.get(subscriberEvents), (events) => + events.some( + (event) => event.type === "output" && event.data === "hello from subscriber\n", + ), + ), + "1200 millis", + ); + }), + ); + + it.effect("preserves queued PTY output ordering through exit callbacks", () => + Effect.gen(function* () { + const { manager, ptyAdapter, getEvents } = yield* createManager(5, { + ptyAdapter: new FakePtyAdapter("async"), + }); + + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + process.emitData("first\n"); + process.emitData("second\n"); + process.emitExit({ exitCode: 0, signal: 0 }); + + yield* waitFor( + Effect.map(getEvents, (events) => { + const relevant = events.filter( + (event) => event.type === "output" || event.type === "exited", + ); + return relevant.length >= 3; + }), + "1200 millis", + ); + + const relevant = (yield* getEvents).filter( + (event) => event.type === "output" || event.type === "exited", + ); + expect(relevant).toEqual([ + expect.objectContaining({ type: "output", data: "first\n" }), + expect.objectContaining({ type: "output", data: "second\n" }), + expect.objectContaining({ type: "exited", exitCode: 0, exitSignal: 0 }), + ]); + }), + ); + + it.effect("scoped runtime shutdown stops active terminals cleanly", () => + Effect.gen(function* () { + const scope = yield* Scope.make("sequential"); + const { manager, ptyAdapter } = yield* createManager(5, { + processKillGraceMs: 10, + }).pipe(Effect.provideService(Scope.Scope, scope)); + yield* manager.open(openInput()); + const process = ptyAdapter.processes[0]; + expect(process).toBeDefined(); + if (!process) return; + + const closeScope = yield* Scope.close(scope, Exit.void).pipe(Effect.forkScoped); + yield* Effect.yieldNow; + yield* TestClock.adjust("10 millis"); + yield* Fiber.join(closeScope); + + assert.equal(process.killSignals[0], "SIGTERM"); + expect(process.killSignals).toContain("SIGKILL"); + }).pipe(Effect.provide(TestClock.layer())), + ); }); diff --git a/apps/server/src/terminal/Layers/Manager.ts b/apps/server/src/terminal/Layers/Manager.ts index b5085220c2..7ef18b1655 100644 --- a/apps/server/src/terminal/Layers/Manager.ts +++ b/apps/server/src/terminal/Layers/Manager.ts @@ -1,32 +1,44 @@ -import { EventEmitter } from "node:events"; -import fs from "node:fs"; import path from "node:path"; import { DEFAULT_TERMINAL_ID, - TerminalClearInput, - TerminalCloseInput, - TerminalOpenInput, - TerminalResizeInput, - TerminalRestartInput, - TerminalWriteInput, type TerminalEvent, type TerminalSessionSnapshot, + type TerminalSessionStatus, } from "@t3tools/contracts"; -import { Effect, Encoding, Layer, Schema } from "effect"; - -import { createLogger } from "../../logger"; -import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY"; -import { runProcess } from "../../processRunner"; -import { ServerConfig } from "../../config"; +import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker"; import { - ShellCandidate, - TerminalError, + Data, + Effect, + Encoding, + Equal, + Exit, + Fiber, + FileSystem, + Layer, + Option, + Scope, + Semaphore, + SynchronizedRef, +} from "effect"; + +import { ServerConfig } from "../../config"; +import { runProcess } from "../../processRunner"; +import { + TerminalCwdError, + TerminalHistoryError, TerminalManager, - TerminalManagerShape, - TerminalSessionState, - TerminalStartInput, + TerminalNotRunningError, + TerminalSessionLookupError, + type TerminalManagerShape, } from "../Services/Manager"; +import { + PtyAdapter, + PtySpawnError, + type PtyAdapterShape, + type PtyExitEvent, + type PtyProcess, +} from "../Services/PTY"; const DEFAULT_HISTORY_LINE_LIMIT = 5_000; const DEFAULT_PERSIST_DEBOUNCE_MS = 40; @@ -37,14 +49,128 @@ const DEFAULT_OPEN_COLS = 120; const DEFAULT_OPEN_ROWS = 30; const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]); -const decodeTerminalOpenInput = Schema.decodeUnknownSync(TerminalOpenInput); -const decodeTerminalRestartInput = Schema.decodeUnknownSync(TerminalRestartInput); -const decodeTerminalWriteInput = Schema.decodeUnknownSync(TerminalWriteInput); -const decodeTerminalResizeInput = Schema.decodeUnknownSync(TerminalResizeInput); -const decodeTerminalClearInput = Schema.decodeUnknownSync(TerminalClearInput); -const decodeTerminalCloseInput = Schema.decodeUnknownSync(TerminalCloseInput); +type TerminalSubprocessChecker = ( + terminalPid: number, +) => Effect.Effect; -type TerminalSubprocessChecker = (terminalPid: number) => Promise; +class TerminalSubprocessCheckError extends Data.TaggedError("TerminalSubprocessCheckError")<{ + readonly message: string; + readonly cause?: unknown; + readonly terminalPid: number; + readonly command: "powershell" | "pgrep" | "ps"; +}> {} + +class TerminalProcessSignalError extends Data.TaggedError("TerminalProcessSignalError")<{ + readonly message: string; + readonly cause?: unknown; + readonly signal: "SIGTERM" | "SIGKILL"; +}> {} + +interface ShellCandidate { + shell: string; + args?: string[]; +} + +interface TerminalStartInput { + threadId: string; + terminalId: string; + cwd: string; + cols: number; + rows: number; + env?: Record; +} + +interface TerminalSessionState { + threadId: string; + terminalId: string; + cwd: string; + status: TerminalSessionStatus; + pid: number | null; + history: string; + pendingHistoryControlSequence: string; + pendingProcessEvents: Array; + pendingProcessEventIndex: number; + processEventDrainRunning: boolean; + exitCode: number | null; + exitSignal: number | null; + updatedAt: string; + cols: number; + rows: number; + process: PtyProcess | null; + unsubscribeData: (() => void) | null; + unsubscribeExit: (() => void) | null; + hasRunningSubprocess: boolean; + runtimeEnv: Record | null; +} + +interface PersistHistoryRequest { + history: string; + immediate: boolean; +} + +type PendingProcessEvent = { type: "output"; data: string } | { type: "exit"; event: PtyExitEvent }; + +type DrainProcessEventAction = + | { type: "idle" } + | { + type: "output"; + threadId: string; + terminalId: string; + history: string | null; + data: string; + } + | { + type: "exit"; + process: PtyProcess | null; + threadId: string; + terminalId: string; + exitCode: number | null; + exitSignal: number | null; + }; + +interface TerminalManagerState { + sessions: Map; + killFibers: Map>; +} + +function snapshot(session: TerminalSessionState): TerminalSessionSnapshot { + return { + threadId: session.threadId, + terminalId: session.terminalId, + cwd: session.cwd, + status: session.status, + pid: session.pid, + history: session.history, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + updatedAt: session.updatedAt, + }; +} + +function cleanupProcessHandles(session: TerminalSessionState): void { + session.unsubscribeData?.(); + session.unsubscribeData = null; + session.unsubscribeExit?.(); + session.unsubscribeExit = null; +} + +function enqueueProcessEvent( + session: TerminalSessionState, + expectedPid: number, + event: PendingProcessEvent, +): boolean { + if (!session.process || session.status !== "running" || session.pid !== expectedPid) { + return false; + } + + session.pendingProcessEvents.push(event); + if (session.processEventDrainRunning) { + return false; + } + + session.processEventDrainRunning = true; + return true; +} function defaultShellResolver(): string { if (process.platform === "win32") { @@ -118,7 +244,7 @@ function resolveShellCandidates(shellResolver: () => string): ShellCandidate[] { ]); } -function isRetryableShellSpawnError(error: unknown): boolean { +function isRetryableShellSpawnError(error: PtySpawnError): boolean { const queue: unknown[] = [error]; const seen = new Set(); const messages: string[] = []; @@ -165,82 +291,107 @@ function isRetryableShellSpawnError(error: unknown): boolean { ); } -async function checkWindowsSubprocessActivity(terminalPid: number): Promise { +function checkWindowsSubprocessActivity( + terminalPid: number, +): Effect.Effect { const command = [ `$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`, "if ($children) { exit 0 }", "exit 1", ].join("; "); - try { - const result = await runProcess( - "powershell.exe", - ["-NoProfile", "-NonInteractive", "-Command", command], - { + return Effect.tryPromise({ + try: () => + runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], { timeoutMs: 1_500, allowNonZeroExit: true, maxBufferBytes: 32_768, outputMode: "truncate", - }, - ); - return result.code === 0; - } catch { - return false; - } + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to check Windows terminal subprocess activity.", + cause, + terminalPid, + command: "powershell", + }), + }).pipe(Effect.map((result) => result.code === 0)); } -async function checkPosixSubprocessActivity(terminalPid: number): Promise { - try { - const pgrepResult = await runProcess("pgrep", ["-P", String(terminalPid)], { - timeoutMs: 1_000, - allowNonZeroExit: true, - maxBufferBytes: 32_768, - outputMode: "truncate", - }); - if (pgrepResult.code === 0) { - return pgrepResult.stdout.trim().length > 0; +const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* ( + terminalPid: number, +): Effect.fn.Return { + const runPgrep = Effect.tryPromise({ + try: () => + runProcess("pgrep", ["-P", String(terminalPid)], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 32_768, + outputMode: "truncate", + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to inspect terminal subprocesses with pgrep.", + cause, + terminalPid, + command: "pgrep", + }), + }); + + const runPs = Effect.tryPromise({ + try: () => + runProcess("ps", ["-eo", "pid=,ppid="], { + timeoutMs: 1_000, + allowNonZeroExit: true, + maxBufferBytes: 262_144, + outputMode: "truncate", + }), + catch: (cause) => + new TerminalSubprocessCheckError({ + message: "Failed to inspect terminal subprocesses with ps.", + cause, + terminalPid, + command: "ps", + }), + }); + + const pgrepResult = yield* Effect.exit(runPgrep); + if (pgrepResult._tag === "Success") { + if (pgrepResult.value.code === 0) { + return pgrepResult.value.stdout.trim().length > 0; } - if (pgrepResult.code === 1) { + if (pgrepResult.value.code === 1) { return false; } - } catch { - // Fall back to ps when pgrep is unavailable. } - try { - const psResult = await runProcess("ps", ["-eo", "pid=,ppid="], { - timeoutMs: 1_000, - allowNonZeroExit: true, - maxBufferBytes: 262_144, - outputMode: "truncate", - }); - if (psResult.code !== 0) { - return false; - } - - for (const line of psResult.stdout.split(/\r?\n/g)) { - const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); - const pid = Number(pidRaw); - const ppid = Number(ppidRaw); - if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; - if (ppid === terminalPid) { - return true; - } - } - return false; - } catch { + const psResult = yield* Effect.exit(runPs); + if (psResult._tag === "Failure" || psResult.value.code !== 0) { return false; } -} -async function defaultSubprocessChecker(terminalPid: number): Promise { + for (const line of psResult.value.stdout.split(/\r?\n/g)) { + const [pidRaw, ppidRaw] = line.trim().split(/\s+/g); + const pid = Number(pidRaw); + const ppid = Number(ppidRaw); + if (!Number.isInteger(pid) || !Number.isInteger(ppid)) continue; + if (ppid === terminalPid) { + return true; + } + } + return false; +}); + +const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* ( + terminalPid: number, +): Effect.fn.Return { if (!Number.isInteger(terminalPid) || terminalPid <= 0) { return false; } if (process.platform === "win32") { - return checkWindowsSubprocessActivity(terminalPid); + return yield* checkWindowsSubprocessActivity(terminalPid); } - return checkPosixSubprocessActivity(terminalPid); -} + return yield* checkPosixSubprocessActivity(terminalPid); +}); function capHistory(history: string, maxLines: number): string { if (history.length === 0) return history; @@ -482,12 +633,8 @@ function normalizedRuntimeEnv( return Object.fromEntries(entries.toSorted(([left], [right]) => left.localeCompare(right))); } -interface TerminalManagerEvents { - event: [event: TerminalEvent]; -} - interface TerminalManagerOptions { - logsDir?: string; + logsDir: string; historyLineLimit?: number; ptyAdapter: PtyAdapterShape; shellResolver?: () => string; @@ -497,917 +644,1192 @@ interface TerminalManagerOptions { maxRetainedInactiveSessions?: number; } -export class TerminalManagerRuntime extends EventEmitter { - private readonly sessions = new Map(); - private readonly logsDir: string; - private readonly historyLineLimit: number; - private readonly ptyAdapter: PtyAdapterShape; - private readonly shellResolver: () => string; - private readonly persistQueues = new Map>(); - private readonly persistTimers = new Map>(); - private readonly pendingPersistHistory = new Map(); - private readonly threadLocks = new Map>(); - private readonly persistDebounceMs: number; - private readonly subprocessChecker: TerminalSubprocessChecker; - private readonly subprocessPollIntervalMs: number; - private readonly processKillGraceMs: number; - private readonly maxRetainedInactiveSessions: number; - private subprocessPollTimer: ReturnType | null = null; - private subprocessPollInFlight = false; - private readonly killEscalationTimers = new Map>(); - private readonly logger = createLogger("terminal"); +const makeTerminalManager = Effect.fn("makeTerminalManager")(function* () { + const { terminalLogsDir } = yield* ServerConfig; + const ptyAdapter = yield* PtyAdapter; + return yield* makeTerminalManagerWithOptions({ + logsDir: terminalLogsDir, + ptyAdapter, + }); +}); - constructor(options: TerminalManagerOptions) { - super(); - this.logsDir = options.logsDir ?? path.resolve(process.cwd(), ".logs", "terminals"); - this.historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; - this.ptyAdapter = options.ptyAdapter; - this.shellResolver = options.shellResolver ?? defaultShellResolver; - this.persistDebounceMs = DEFAULT_PERSIST_DEBOUNCE_MS; - this.subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; - this.subprocessPollIntervalMs = +export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWithOptions")( + function* (options: TerminalManagerOptions) { + const fileSystem = yield* FileSystem.FileSystem; + const services = yield* Effect.services(); + const runFork = Effect.runForkWith(services); + + const logsDir = options.logsDir; + const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT; + const shellResolver = options.shellResolver ?? defaultShellResolver; + const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker; + const subprocessPollIntervalMs = options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS; - this.processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; - this.maxRetainedInactiveSessions = + const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS; + const maxRetainedInactiveSessions = options.maxRetainedInactiveSessions ?? DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS; - fs.mkdirSync(this.logsDir, { recursive: true }); - } - async open(raw: TerminalOpenInput): Promise { - const input = decodeTerminalOpenInput(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); + yield* fileSystem.makeDirectory(logsDir, { recursive: true }).pipe(Effect.orDie); - const sessionKey = toSessionKey(input.threadId, input.terminalId); - const existing = this.sessions.get(sessionKey); - if (!existing) { - await this.flushPersistQueue(input.threadId, input.terminalId); - const history = await this.readHistory(input.threadId, input.terminalId); - const cols = input.cols ?? DEFAULT_OPEN_COLS; - const rows = input.rows ?? DEFAULT_OPEN_ROWS; - const session: TerminalSessionState = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history, - pendingHistoryControlSequence: "", - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols, - rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runtimeEnv: normalizedRuntimeEnv(input.env), - }; - this.sessions.set(sessionKey, session); - this.evictInactiveSessionsIfNeeded(); - await this.startSession(session, { ...input, cols, rows }, "started"); - return this.snapshot(session); - } - - const nextRuntimeEnv = normalizedRuntimeEnv(input.env); - const currentRuntimeEnv = existing.runtimeEnv; - const targetCols = input.cols ?? existing.cols; - const targetRows = input.rows ?? existing.rows; - const runtimeEnvChanged = - JSON.stringify(currentRuntimeEnv) !== JSON.stringify(nextRuntimeEnv); - - if (existing.cwd !== input.cwd || runtimeEnvChanged) { - this.stopProcess(existing); - existing.cwd = input.cwd; - existing.runtimeEnv = nextRuntimeEnv; - existing.history = ""; - existing.pendingHistoryControlSequence = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } else if (existing.status === "exited" || existing.status === "error") { - existing.runtimeEnv = nextRuntimeEnv; - existing.history = ""; - existing.pendingHistoryControlSequence = ""; - await this.persistHistory(existing.threadId, existing.terminalId, existing.history); - } else if (currentRuntimeEnv !== nextRuntimeEnv) { - existing.runtimeEnv = nextRuntimeEnv; - } - - if (!existing.process) { - await this.startSession( - existing, - { ...input, cols: targetCols, rows: targetRows }, - "started", - ); - return this.snapshot(existing); - } - - if (existing.cols !== targetCols || existing.rows !== targetRows) { - existing.cols = targetCols; - existing.rows = targetRows; - existing.process.resize(targetCols, targetRows); - existing.updatedAt = new Date().toISOString(); - } - - return this.snapshot(existing); + const managerStateRef = yield* SynchronizedRef.make({ + sessions: new Map(), + killFibers: new Map(), }); - } + const threadLocksRef = yield* SynchronizedRef.make(new Map()); + const terminalEventListeners = new Set<(event: TerminalEvent) => Effect.Effect>(); + const workerScope = yield* Scope.make("sequential"); + yield* Effect.addFinalizer(() => Scope.close(workerScope, Exit.void)); - async write(raw: TerminalWriteInput): Promise { - const input = decodeTerminalWriteInput(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - if (session.status === "exited") { - return; + const publishEvent = (event: TerminalEvent) => + Effect.gen(function* () { + for (const listener of terminalEventListeners) { + yield* listener(event).pipe(Effect.ignoreCause({ log: true })); + } + }); + + const historyPath = (threadId: string, terminalId: string) => { + const threadPart = toSafeThreadId(threadId); + if (terminalId === DEFAULT_TERMINAL_ID) { + return path.join(logsDir, `${threadPart}.log`); } - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.process.write(input.data); - } + return path.join(logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); + }; - async resize(raw: TerminalResizeInput): Promise { - const input = decodeTerminalResizeInput(raw); - const session = this.requireSession(input.threadId, input.terminalId); - if (!session.process || session.status !== "running") { - throw new Error( - `Terminal is not running for thread: ${input.threadId}, terminal: ${input.terminalId}`, - ); - } - session.cols = input.cols; - session.rows = input.rows; - session.updatedAt = new Date().toISOString(); - session.process.resize(input.cols, input.rows); - } + const legacyHistoryPath = (threadId: string) => + path.join(logsDir, `${legacySafeThreadId(threadId)}.log`); - async clear(raw: TerminalClearInput): Promise { - const input = decodeTerminalClearInput(raw); - await this.runWithThreadLock(input.threadId, async () => { - const session = this.requireSession(input.threadId, input.terminalId); - session.history = ""; - session.pendingHistoryControlSequence = ""; - session.updatedAt = new Date().toISOString(); - await this.persistHistory(input.threadId, input.terminalId, session.history); - this.emitEvent({ - type: "cleared", - threadId: input.threadId, - terminalId: input.terminalId, - createdAt: new Date().toISOString(), + const toTerminalHistoryError = + (operation: "read" | "truncate" | "migrate", threadId: string, terminalId: string) => + (cause: unknown) => + new TerminalHistoryError({ + operation, + threadId, + terminalId, + cause, + }); + + const readManagerState = SynchronizedRef.get(managerStateRef); + + const modifyManagerState = ( + f: (state: TerminalManagerState) => readonly [A, TerminalManagerState], + ) => SynchronizedRef.modify(managerStateRef, f); + + const getThreadSemaphore = (threadId: string) => + SynchronizedRef.modifyEffect(threadLocksRef, (current) => { + const existing: Option.Option = Option.fromNullishOr( + current.get(threadId), + ); + return Option.match(existing, { + onNone: () => + Semaphore.make(1).pipe( + Effect.map((semaphore) => { + const next = new Map(current); + next.set(threadId, semaphore); + return [semaphore, next] as const; + }), + ), + onSome: (semaphore) => Effect.succeed([semaphore, current] as const), + }); + }); + + const withThreadLock = ( + threadId: string, + effect: Effect.Effect, + ): Effect.Effect => + Effect.flatMap(getThreadSemaphore(threadId), (semaphore) => semaphore.withPermit(effect)); + + const clearKillFiber = Effect.fn("terminal.clearKillFiber")(function* ( + process: PtyProcess | null, + ) { + if (!process) return; + const fiber: Option.Option> = yield* modifyManagerState< + Option.Option> + >((state) => { + const existing: Option.Option> = Option.fromNullishOr( + state.killFibers.get(process), + ); + if (Option.isNone(existing)) { + return [Option.none>(), state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [existing, { ...state, killFibers }] as const; + }); + if (Option.isSome(fiber)) { + yield* Fiber.interrupt(fiber.value).pipe(Effect.ignore); + } + }); + + const registerKillFiber = Effect.fn("terminal.registerKillFiber")(function* ( + process: PtyProcess, + fiber: Fiber.Fiber, + ) { + yield* modifyManagerState((state) => { + const killFibers = new Map(state.killFibers); + killFibers.set(process, fiber); + return [undefined, { ...state, killFibers }] as const; }); }); - } - async restart(raw: TerminalRestartInput): Promise { - const input = decodeTerminalRestartInput(raw); - return this.runWithThreadLock(input.threadId, async () => { - await this.assertValidCwd(input.cwd); - - const sessionKey = toSessionKey(input.threadId, input.terminalId); - let session = this.sessions.get(sessionKey); - if (!session) { - const cols = input.cols ?? DEFAULT_OPEN_COLS; - const rows = input.rows ?? DEFAULT_OPEN_ROWS; - session = { - threadId: input.threadId, - terminalId: input.terminalId, - cwd: input.cwd, - status: "starting", - pid: null, - history: "", - pendingHistoryControlSequence: "", - exitCode: null, - exitSignal: null, - updatedAt: new Date().toISOString(), - cols, - rows, - process: null, - unsubscribeData: null, - unsubscribeExit: null, - hasRunningSubprocess: false, - runtimeEnv: normalizedRuntimeEnv(input.env), - }; - this.sessions.set(sessionKey, session); - this.evictInactiveSessionsIfNeeded(); - } else { - this.stopProcess(session); - session.cwd = input.cwd; - session.runtimeEnv = normalizedRuntimeEnv(input.env); - } - - const cols = input.cols ?? session.cols; - const rows = input.rows ?? session.rows; - - session.history = ""; - session.pendingHistoryControlSequence = ""; - await this.persistHistory(input.threadId, input.terminalId, session.history); - await this.startSession(session, { ...input, cols, rows }, "restarted"); - return this.snapshot(session); - }); - } - - async close(raw: TerminalCloseInput): Promise { - const input = decodeTerminalCloseInput(raw); - await this.runWithThreadLock(input.threadId, async () => { - if (input.terminalId) { - await this.closeSession(input.threadId, input.terminalId, input.deleteHistory === true); - return; - } - - const threadSessions = this.sessionsForThread(input.threadId); - for (const session of threadSessions) { - this.stopProcess(session); - this.sessions.delete(toSessionKey(session.threadId, session.terminalId)); - } - await Promise.all( - threadSessions.map((session) => - this.flushPersistQueue(session.threadId, session.terminalId), + const runKillEscalation = Effect.fn("terminal.runKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const terminated = yield* Effect.try({ + try: () => process.kill("SIGTERM"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGTERM to terminal process.", + cause, + signal: "SIGTERM", + }), + }).pipe( + Effect.as(true), + Effect.catch((error) => + Effect.logWarning("failed to kill terminal process", { + threadId, + terminalId, + signal: "SIGTERM", + error: error.message, + }).pipe(Effect.as(false)), ), ); - - if (input.deleteHistory) { - await this.deleteAllHistoryForThread(input.threadId); - } - this.updateSubprocessPollingState(); - }); - } - - dispose(): void { - this.stopSubprocessPolling(); - const sessions = [...this.sessions.values()]; - this.sessions.clear(); - for (const session of sessions) { - this.stopProcess(session); - } - for (const timer of this.persistTimers.values()) { - clearTimeout(timer); - } - this.persistTimers.clear(); - for (const timer of this.killEscalationTimers.values()) { - clearTimeout(timer); - } - this.killEscalationTimers.clear(); - this.pendingPersistHistory.clear(); - this.threadLocks.clear(); - this.persistQueues.clear(); - } - - private async startSession( - session: TerminalSessionState, - input: TerminalStartInput, - eventType: "started" | "restarted", - ): Promise { - this.stopProcess(session); - - session.status = "starting"; - session.cwd = input.cwd; - session.cols = input.cols; - session.rows = input.rows; - session.exitCode = null; - session.exitSignal = null; - session.hasRunningSubprocess = false; - session.updatedAt = new Date().toISOString(); - - let ptyProcess: PtyProcess | null = null; - let startedShell: string | null = null; - try { - const shellCandidates = resolveShellCandidates(this.shellResolver); - const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); - let lastSpawnError: unknown = null; - - const spawnWithCandidate = (candidate: ShellCandidate) => - Effect.runPromise( - this.ptyAdapter.spawn({ - shell: candidate.shell, - ...(candidate.args ? { args: candidate.args } : {}), - cwd: session.cwd, - cols: session.cols, - rows: session.rows, - env: terminalEnv, - }), - ); - - const trySpawn = async ( - candidates: ShellCandidate[], - index = 0, - ): Promise<{ process: PtyProcess; shellLabel: string } | null> => { - if (index >= candidates.length) { - return null; - } - const candidate = candidates[index]; - if (!candidate) { - return null; - } - - try { - const process = await spawnWithCandidate(candidate); - return { process, shellLabel: formatShellCandidate(candidate) }; - } catch (error) { - lastSpawnError = error; - if (!isRetryableShellSpawnError(error)) { - throw error; - } - return trySpawn(candidates, index + 1); - } - }; - - const spawnResult = await trySpawn(shellCandidates); - if (spawnResult) { - ptyProcess = spawnResult.process; - startedShell = spawnResult.shellLabel; - } - - if (!ptyProcess) { - const detail = - lastSpawnError instanceof Error ? lastSpawnError.message : "Terminal start failed"; - const tried = - shellCandidates.length > 0 - ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` - : ""; - throw new Error(`${detail}.${tried}`.trim()); - } - - session.process = ptyProcess; - session.pid = ptyProcess.pid; - session.status = "running"; - session.updatedAt = new Date().toISOString(); - session.unsubscribeData = ptyProcess.onData((data) => { - this.onProcessData(session, data); - }); - session.unsubscribeExit = ptyProcess.onExit((event) => { - this.onProcessExit(session, event); - }); - this.updateSubprocessPollingState(); - this.emitEvent({ - type: eventType, - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - snapshot: this.snapshot(session), - }); - } catch (error) { - if (ptyProcess) { - this.killProcessWithEscalation(ptyProcess, session.threadId, session.terminalId); - } - session.status = "error"; - session.pid = null; - session.process = null; - session.hasRunningSubprocess = false; - session.updatedAt = new Date().toISOString(); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - const message = error instanceof Error ? error.message : "Terminal start failed"; - this.emitEvent({ - type: "error", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - message, - }); - this.logger.error("failed to start terminal", { - threadId: session.threadId, - terminalId: session.terminalId, - error: message, - ...(startedShell ? { shell: startedShell } : {}), - }); - } - } - - private onProcessData(session: TerminalSessionState, data: string): void { - const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data); - session.pendingHistoryControlSequence = sanitized.pendingControlSequence; - if (sanitized.visibleText.length > 0) { - session.history = capHistory( - `${session.history}${sanitized.visibleText}`, - this.historyLineLimit, - ); - this.queuePersist(session.threadId, session.terminalId, session.history); - } - session.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "output", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - data, - }); - } - - private onProcessExit(session: TerminalSessionState, event: PtyExitEvent): void { - this.clearKillEscalationTimer(session.process); - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.status = "exited"; - session.pendingHistoryControlSequence = ""; - session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null; - session.exitSignal = Number.isInteger(event.signal) ? event.signal : null; - session.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "exited", - threadId: session.threadId, - terminalId: session.terminalId, - createdAt: new Date().toISOString(), - exitCode: session.exitCode, - exitSignal: session.exitSignal, - }); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - } - - private stopProcess(session: TerminalSessionState): void { - const process = session.process; - if (!process) return; - this.cleanupProcessHandles(session); - session.process = null; - session.pid = null; - session.hasRunningSubprocess = false; - session.status = "exited"; - session.pendingHistoryControlSequence = ""; - session.updatedAt = new Date().toISOString(); - this.killProcessWithEscalation(process, session.threadId, session.terminalId); - this.evictInactiveSessionsIfNeeded(); - this.updateSubprocessPollingState(); - } - - private cleanupProcessHandles(session: TerminalSessionState): void { - session.unsubscribeData?.(); - session.unsubscribeData = null; - session.unsubscribeExit?.(); - session.unsubscribeExit = null; - } - - private clearKillEscalationTimer(process: PtyProcess | null): void { - if (!process) return; - const timer = this.killEscalationTimers.get(process); - if (!timer) return; - clearTimeout(timer); - this.killEscalationTimers.delete(process); - } - - private killProcessWithEscalation( - process: PtyProcess, - threadId: string, - terminalId: string, - ): void { - this.clearKillEscalationTimer(process); - try { - process.kill("SIGTERM"); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.logger.warn("failed to kill terminal process", { - threadId, - terminalId, - signal: "SIGTERM", - error: message, - }); - return; - } - - const timer = setTimeout(() => { - this.killEscalationTimers.delete(process); - try { - process.kill("SIGKILL"); - } catch (error) { - const message = error instanceof Error ? error.message : String(error); - this.logger.warn("failed to force-kill terminal process", { - threadId, - terminalId, - signal: "SIGKILL", - error: message, - }); - } - }, this.processKillGraceMs); - timer.unref?.(); - this.killEscalationTimers.set(process, timer); - } - - private evictInactiveSessionsIfNeeded(): void { - const inactiveSessions = [...this.sessions.values()].filter( - (session) => session.status !== "running", - ); - if (inactiveSessions.length <= this.maxRetainedInactiveSessions) { - return; - } - - inactiveSessions.sort( - (left, right) => - left.updatedAt.localeCompare(right.updatedAt) || - left.threadId.localeCompare(right.threadId) || - left.terminalId.localeCompare(right.terminalId), - ); - const toEvict = inactiveSessions.length - this.maxRetainedInactiveSessions; - for (const session of inactiveSessions.slice(0, toEvict)) { - const key = toSessionKey(session.threadId, session.terminalId); - this.sessions.delete(key); - this.clearPersistTimer(session.threadId, session.terminalId); - this.pendingPersistHistory.delete(key); - this.persistQueues.delete(key); - this.clearKillEscalationTimer(session.process); - } - } - - private queuePersist(threadId: string, terminalId: string, history: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - this.pendingPersistHistory.set(persistenceKey, history); - this.schedulePersist(threadId, terminalId); - } - - private async persistHistory( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, history); - } - - private enqueuePersistWrite( - threadId: string, - terminalId: string, - history: string, - ): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - const task = async () => { - await fs.promises.writeFile(this.historyPath(threadId, terminalId), history, "utf8"); - }; - const previous = this.persistQueues.get(persistenceKey) ?? Promise.resolve(); - const next = previous - .catch(() => undefined) - .then(task) - .catch((error) => { - this.logger.warn("failed to persist terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - }); - this.persistQueues.set(persistenceKey, next); - const finalized = next.finally(() => { - if (this.persistQueues.get(persistenceKey) === next) { - this.persistQueues.delete(persistenceKey); - } - if ( - this.pendingPersistHistory.has(persistenceKey) && - !this.persistTimers.has(persistenceKey) - ) { - this.schedulePersist(threadId, terminalId); - } - }); - void finalized.catch(() => undefined); - return finalized; - } - - private schedulePersist(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - if (this.persistTimers.has(persistenceKey)) return; - const timer = setTimeout(() => { - this.persistTimers.delete(persistenceKey); - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory === undefined) return; - this.pendingPersistHistory.delete(persistenceKey); - void this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - }, this.persistDebounceMs); - this.persistTimers.set(persistenceKey, timer); - } - - private clearPersistTimer(threadId: string, terminalId: string): void { - const persistenceKey = toSessionKey(threadId, terminalId); - const timer = this.persistTimers.get(persistenceKey); - if (!timer) return; - clearTimeout(timer); - this.persistTimers.delete(persistenceKey); - } - - private async readHistory(threadId: string, terminalId: string): Promise { - const nextPath = this.historyPath(threadId, terminalId); - try { - const raw = await fs.promises.readFile(nextPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - if (capped !== raw) { - await fs.promises.writeFile(nextPath, capped, "utf8"); - } - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ENOENT") { - throw error; - } - } - - if (terminalId !== DEFAULT_TERMINAL_ID) { - return ""; - } - - const legacyPath = this.legacyHistoryPath(threadId); - try { - const raw = await fs.promises.readFile(legacyPath, "utf8"); - const capped = capHistory(raw, this.historyLineLimit); - - // Migrate legacy transcript filename to the terminal-scoped path. - await fs.promises.writeFile(nextPath, capped, "utf8"); - try { - await fs.promises.rm(legacyPath, { force: true }); - } catch (cleanupError) { - this.logger.warn("failed to remove legacy terminal history", { - threadId, - error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), - }); - } - - return capped; - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - return ""; - } - throw error; - } - } - - private async deleteHistory(threadId: string, terminalId: string): Promise { - const deletions = [fs.promises.rm(this.historyPath(threadId, terminalId), { force: true })]; - if (terminalId === DEFAULT_TERMINAL_ID) { - deletions.push(fs.promises.rm(this.legacyHistoryPath(threadId), { force: true })); - } - try { - await Promise.all(deletions); - } catch (error) { - this.logger.warn("failed to delete terminal history", { - threadId, - terminalId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private async flushPersistQueue(threadId: string, terminalId: string): Promise { - const persistenceKey = toSessionKey(threadId, terminalId); - this.clearPersistTimer(threadId, terminalId); - - while (true) { - const pendingHistory = this.pendingPersistHistory.get(persistenceKey); - if (pendingHistory !== undefined) { - this.pendingPersistHistory.delete(persistenceKey); - await this.enqueuePersistWrite(threadId, terminalId, pendingHistory); - } - - const pending = this.persistQueues.get(persistenceKey); - if (!pending) { + if (!terminated) { return; } - await pending.catch(() => undefined); - } - } - private updateSubprocessPollingState(): void { - const hasRunningSessions = [...this.sessions.values()].some( - (session) => session.status === "running" && session.pid !== null, - ); - if (hasRunningSessions) { - this.ensureSubprocessPolling(); - return; - } - this.stopSubprocessPolling(); - } + yield* Effect.sleep(processKillGraceMs); - private ensureSubprocessPolling(): void { - if (this.subprocessPollTimer) return; - this.subprocessPollTimer = setInterval(() => { - void this.pollSubprocessActivity(); - }, this.subprocessPollIntervalMs); - this.subprocessPollTimer.unref?.(); - void this.pollSubprocessActivity(); - } - - private stopSubprocessPolling(): void { - if (!this.subprocessPollTimer) return; - clearInterval(this.subprocessPollTimer); - this.subprocessPollTimer = null; - } - - private async pollSubprocessActivity(): Promise { - if (this.subprocessPollInFlight) return; - - const runningSessions = [...this.sessions.values()].filter( - (session): session is TerminalSessionState & { pid: number } => - session.status === "running" && Number.isInteger(session.pid), - ); - if (runningSessions.length === 0) { - this.stopSubprocessPolling(); - return; - } - - this.subprocessPollInFlight = true; - try { - await Promise.all( - runningSessions.map(async (session) => { - const terminalPid = session.pid; - let hasRunningSubprocess = false; - try { - hasRunningSubprocess = await this.subprocessChecker(terminalPid); - } catch (error) { - this.logger.warn("failed to check terminal subprocess activity", { - threadId: session.threadId, - terminalId: session.terminalId, - terminalPid, - error: error instanceof Error ? error.message : String(error), - }); - return; - } - - const liveSession = this.sessions.get(toSessionKey(session.threadId, session.terminalId)); - if (!liveSession || liveSession.status !== "running" || liveSession.pid !== terminalPid) { - return; - } - if (liveSession.hasRunningSubprocess === hasRunningSubprocess) { - return; - } - - liveSession.hasRunningSubprocess = hasRunningSubprocess; - liveSession.updatedAt = new Date().toISOString(); - this.emitEvent({ - type: "activity", - threadId: liveSession.threadId, - terminalId: liveSession.terminalId, - createdAt: new Date().toISOString(), - hasRunningSubprocess, - }); - }), + yield* Effect.try({ + try: () => process.kill("SIGKILL"), + catch: (cause) => + new TerminalProcessSignalError({ + message: "Failed to send SIGKILL to terminal process.", + cause, + signal: "SIGKILL", + }), + }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to force-kill terminal process", { + threadId, + terminalId, + signal: "SIGKILL", + error: error.message, + }), + ), ); - } finally { - this.subprocessPollInFlight = false; - } - } + }); - private async assertValidCwd(cwd: string): Promise { - let stats: fs.Stats; - try { - stats = await fs.promises.stat(cwd); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") { - throw new Error(`Terminal cwd does not exist: ${cwd}`, { cause: error }); + const startKillEscalation = Effect.fn("terminal.startKillEscalation")(function* ( + process: PtyProcess, + threadId: string, + terminalId: string, + ) { + const fiber = yield* runKillEscalation(process, threadId, terminalId).pipe( + Effect.ensuring( + modifyManagerState((state) => { + if (!state.killFibers.has(process)) { + return [undefined, state] as const; + } + const killFibers = new Map(state.killFibers); + killFibers.delete(process); + return [undefined, { ...state, killFibers }] as const; + }), + ), + Effect.forkIn(workerScope), + ); + + yield* registerKillFiber(process, fiber); + }); + + const persistWorker = yield* makeKeyedCoalescingWorker< + string, + PersistHistoryRequest, + never, + never + >({ + merge: (current, next) => ({ + history: next.history, + immediate: current.immediate || next.immediate, + }), + process: Effect.fn("terminal.persistHistoryWorker")(function* (sessionKey, request) { + if (!request.immediate) { + yield* Effect.sleep(DEFAULT_PERSIST_DEBOUNCE_MS); + } + + const [threadId, terminalId] = sessionKey.split("\u0000"); + if (!threadId || !terminalId) { + return; + } + + yield* fileSystem.writeFileString(historyPath(threadId, terminalId), request.history).pipe( + Effect.catch((error) => + Effect.logWarning("failed to persist terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + }), + }); + + const queuePersist = Effect.fn("terminal.queuePersist")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: false, + }); + }); + + const flushPersist = Effect.fn("terminal.flushPersist")(function* ( + threadId: string, + terminalId: string, + ) { + yield* persistWorker.drainKey(toSessionKey(threadId, terminalId)); + }); + + const persistHistory = Effect.fn("terminal.persistHistory")(function* ( + threadId: string, + terminalId: string, + history: string, + ) { + yield* persistWorker.enqueue(toSessionKey(threadId, terminalId), { + history, + immediate: true, + }); + yield* flushPersist(threadId, terminalId); + }); + + const readHistory = Effect.fn("terminal.readHistory")(function* ( + threadId: string, + terminalId: string, + ) { + const nextPath = historyPath(threadId, terminalId); + if ( + yield* fileSystem + .exists(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))) + ) { + const raw = yield* fileSystem + .readFileString(nextPath) + .pipe(Effect.mapError(toTerminalHistoryError("read", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + if (capped !== raw) { + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("truncate", threadId, terminalId))); + } + return capped; } - throw error; - } - if (!stats.isDirectory()) { - throw new Error(`Terminal cwd is not a directory: ${cwd}`); - } - } - private async closeSession( - threadId: string, - terminalId: string, - deleteHistory: boolean, - ): Promise { - const key = toSessionKey(threadId, terminalId); - const session = this.sessions.get(key); - if (session) { - this.stopProcess(session); - this.sessions.delete(key); - } - this.updateSubprocessPollingState(); - await this.flushPersistQueue(threadId, terminalId); - if (deleteHistory) { - await this.deleteHistory(threadId, terminalId); - } - } + if (terminalId !== DEFAULT_TERMINAL_ID) { + return ""; + } - private sessionsForThread(threadId: string): TerminalSessionState[] { - return [...this.sessions.values()].filter((session) => session.threadId === threadId); - } + const legacyPath = legacyHistoryPath(threadId); + if ( + !(yield* fileSystem + .exists(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId)))) + ) { + return ""; + } - private async deleteAllHistoryForThread(threadId: string): Promise { - const threadPrefix = `${toSafeThreadId(threadId)}_`; - try { - const entries = await fs.promises.readdir(this.logsDir, { withFileTypes: true }); - const removals = entries - .filter((entry) => entry.isFile()) - .map((entry) => entry.name) - .filter( + const raw = yield* fileSystem + .readFileString(legacyPath) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + const capped = capHistory(raw, historyLineLimit); + yield* fileSystem + .writeFileString(nextPath, capped) + .pipe(Effect.mapError(toTerminalHistoryError("migrate", threadId, terminalId))); + yield* fileSystem.remove(legacyPath, { force: true }).pipe( + Effect.catch((cleanupError) => + Effect.logWarning("failed to remove legacy terminal history", { + threadId, + error: cleanupError instanceof Error ? cleanupError.message : String(cleanupError), + }), + ), + ); + return capped; + }); + + const deleteHistory = Effect.fn("terminal.deleteHistory")(function* ( + threadId: string, + terminalId: string, + ) { + yield* fileSystem.remove(historyPath(threadId, terminalId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + if (terminalId === DEFAULT_TERMINAL_ID) { + yield* fileSystem.remove(legacyHistoryPath(threadId), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal history", { + threadId, + terminalId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ); + } + }); + + const deleteAllHistoryForThread = Effect.fn("terminal.deleteAllHistoryForThread")(function* ( + threadId: string, + ) { + const threadPrefix = `${toSafeThreadId(threadId)}_`; + const entries = yield* fileSystem + .readDirectory(logsDir, { recursive: false }) + .pipe(Effect.catch(() => Effect.succeed([] as Array))); + yield* Effect.forEach( + entries.filter( (name) => name === `${toSafeThreadId(threadId)}.log` || name === `${legacySafeThreadId(threadId)}.log` || name.startsWith(threadPrefix), - ) - .map((name) => fs.promises.rm(path.join(this.logsDir, name), { force: true })); - await Promise.all(removals); - } catch (error) { - this.logger.warn("failed to delete terminal histories for thread", { - threadId, - error: error instanceof Error ? error.message : String(error), - }); - } - } - - private requireSession(threadId: string, terminalId: string): TerminalSessionState { - const session = this.sessions.get(toSessionKey(threadId, terminalId)); - if (!session) { - throw new Error(`Unknown terminal thread: ${threadId}, terminal: ${terminalId}`); - } - return session; - } - - private snapshot(session: TerminalSessionState): TerminalSessionSnapshot { - return { - threadId: session.threadId, - terminalId: session.terminalId, - cwd: session.cwd, - status: session.status, - pid: session.pid, - history: session.history, - exitCode: session.exitCode, - exitSignal: session.exitSignal, - updatedAt: session.updatedAt, - }; - } - - private emitEvent(event: TerminalEvent): void { - this.emit("event", event); - } - - private historyPath(threadId: string, terminalId: string): string { - const threadPart = toSafeThreadId(threadId); - if (terminalId === DEFAULT_TERMINAL_ID) { - return path.join(this.logsDir, `${threadPart}.log`); - } - return path.join(this.logsDir, `${threadPart}_${toSafeTerminalId(terminalId)}.log`); - } - - private legacyHistoryPath(threadId: string): string { - return path.join(this.logsDir, `${legacySafeThreadId(threadId)}.log`); - } - - private async runWithThreadLock(threadId: string, task: () => Promise): Promise { - const previous = this.threadLocks.get(threadId) ?? Promise.resolve(); - let release!: () => void; - const current = new Promise((resolve) => { - release = resolve; + ), + (name) => + fileSystem.remove(path.join(logsDir, name), { force: true }).pipe( + Effect.catch((error) => + Effect.logWarning("failed to delete terminal histories for thread", { + threadId, + error: error instanceof Error ? error.message : String(error), + }), + ), + ), + { discard: true }, + ); }); - this.threadLocks.set(threadId, current); - await previous.catch(() => undefined); - try { - return await task(); - } finally { - release(); - if (this.threadLocks.get(threadId) === current) { - this.threadLocks.delete(threadId); + + const assertValidCwd = Effect.fn("terminal.assertValidCwd")(function* (cwd: string) { + const stats = yield* fileSystem.stat(cwd).pipe( + Effect.mapError( + (cause) => + new TerminalCwdError({ + cwd, + reason: cause.reason._tag === "NotFound" ? "notFound" : "statFailed", + cause, + }), + ), + ); + if (stats.type !== "Directory") { + return yield* new TerminalCwdError({ + cwd, + reason: "notDirectory", + }); } - } - } -} + }); -export const TerminalManagerLive = Layer.effect( - TerminalManager, - Effect.gen(function* () { - const { terminalLogsDir } = yield* ServerConfig; + const getSession = Effect.fn("terminal.getSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return> { + return yield* Effect.map(readManagerState, (state) => + Option.fromNullishOr(state.sessions.get(toSessionKey(threadId, terminalId))), + ); + }); - const ptyAdapter = yield* PtyAdapter; - const runtime = yield* Effect.acquireRelease( - Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })), - (r) => Effect.sync(() => r.dispose()), + const requireSession = Effect.fn("terminal.requireSession")(function* ( + threadId: string, + terminalId: string, + ): Effect.fn.Return { + return yield* Effect.flatMap(getSession(threadId, terminalId), (session) => + Option.match(session, { + onNone: () => + Effect.fail( + new TerminalSessionLookupError({ + threadId, + terminalId, + }), + ), + onSome: Effect.succeed, + }), + ); + }); + + const sessionsForThread = Effect.fn("terminal.sessionsForThread")(function* (threadId: string) { + return yield* readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].filter((session) => session.threadId === threadId), + ), + ); + }); + + const evictInactiveSessionsIfNeeded = Effect.fn("terminal.evictInactiveSessionsIfNeeded")( + function* () { + yield* modifyManagerState((state) => { + const inactiveSessions = [...state.sessions.values()].filter( + (session) => session.status !== "running", + ); + if (inactiveSessions.length <= maxRetainedInactiveSessions) { + return [undefined, state] as const; + } + + inactiveSessions.sort( + (left, right) => + left.updatedAt.localeCompare(right.updatedAt) || + left.threadId.localeCompare(right.threadId) || + left.terminalId.localeCompare(right.terminalId), + ); + + const sessions = new Map(state.sessions); + + const toEvict = inactiveSessions.length - maxRetainedInactiveSessions; + for (const session of inactiveSessions.slice(0, toEvict)) { + const key = toSessionKey(session.threadId, session.terminalId); + sessions.delete(key); + } + + return [undefined, { ...state, sessions }] as const; + }); + }, ); + const drainProcessEvents = Effect.fn("terminal.drainProcessEvents")(function* ( + session: TerminalSessionState, + expectedPid: number, + ) { + while (true) { + const action: DrainProcessEventAction = yield* Effect.sync(() => { + if (session.pid !== expectedPid || !session.process || session.status !== "running") { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + const nextEvent = session.pendingProcessEvents[session.pendingProcessEventIndex]; + if (!nextEvent) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + return { type: "idle" } as const; + } + + session.pendingProcessEventIndex += 1; + if (session.pendingProcessEventIndex >= session.pendingProcessEvents.length) { + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + } + + if (nextEvent.type === "output") { + const sanitized = sanitizeTerminalHistoryChunk( + session.pendingHistoryControlSequence, + nextEvent.data, + ); + session.pendingHistoryControlSequence = sanitized.pendingControlSequence; + if (sanitized.visibleText.length > 0) { + session.history = capHistory( + `${session.history}${sanitized.visibleText}`, + historyLineLimit, + ); + } + session.updatedAt = new Date().toISOString(); + + return { + type: "output", + threadId: session.threadId, + terminalId: session.terminalId, + history: sanitized.visibleText.length > 0 ? session.history : null, + data: nextEvent.data, + } as const; + } + + const process = session.process; + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.exitCode = Number.isInteger(nextEvent.event.exitCode) + ? nextEvent.event.exitCode + : null; + session.exitSignal = Number.isInteger(nextEvent.event.signal) + ? nextEvent.event.signal + : null; + session.updatedAt = new Date().toISOString(); + + return { + type: "exit", + process, + threadId: session.threadId, + terminalId: session.terminalId, + exitCode: session.exitCode, + exitSignal: session.exitSignal, + } as const; + }); + + if (action.type === "idle") { + return; + } + + if (action.type === "output") { + if (action.history !== null) { + yield* queuePersist(action.threadId, action.terminalId, action.history); + } + + yield* publishEvent({ + type: "output", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + data: action.data, + }); + continue; + } + + yield* clearKillFiber(action.process); + yield* publishEvent({ + type: "exited", + threadId: action.threadId, + terminalId: action.terminalId, + createdAt: new Date().toISOString(), + exitCode: action.exitCode, + exitSignal: action.exitSignal, + }); + yield* evictInactiveSessionsIfNeeded(); + return; + } + }); + + const stopProcess = Effect.fn("terminal.stopProcess")(function* ( + session: TerminalSessionState, + ) { + const process = session.process; + if (!process) return; + + yield* modifyManagerState((state) => { + cleanupProcessHandles(session); + session.process = null; + session.pid = null; + session.hasRunningSubprocess = false; + session.status = "exited"; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* clearKillFiber(process); + yield* startKillEscalation(process, session.threadId, session.terminalId); + yield* evictInactiveSessionsIfNeeded(); + }); + + const trySpawn = Effect.fn("terminal.trySpawn")(function* ( + shellCandidates: ReadonlyArray, + spawnEnv: NodeJS.ProcessEnv, + session: TerminalSessionState, + index = 0, + lastError: PtySpawnError | null = null, + ): Effect.fn.Return<{ process: PtyProcess; shellLabel: string }, PtySpawnError> { + if (index >= shellCandidates.length) { + const detail = lastError?.message ?? "Failed to spawn PTY process"; + const tried = + shellCandidates.length > 0 + ? ` Tried shells: ${shellCandidates.map((candidate) => formatShellCandidate(candidate)).join(", ")}.` + : ""; + return yield* new PtySpawnError({ + adapter: "terminal-manager", + message: `${detail}.${tried}`.trim(), + ...(lastError ? { cause: lastError } : {}), + }); + } + + const candidate = shellCandidates[index]; + if (!candidate) { + return yield* ( + lastError ?? + new PtySpawnError({ + adapter: "terminal-manager", + message: "No shell candidate available for PTY spawn.", + }) + ); + } + + const attempt = yield* Effect.result( + options.ptyAdapter.spawn({ + shell: candidate.shell, + ...(candidate.args ? { args: candidate.args } : {}), + cwd: session.cwd, + cols: session.cols, + rows: session.rows, + env: spawnEnv, + }), + ); + + if (attempt._tag === "Success") { + return { + process: attempt.success, + shellLabel: formatShellCandidate(candidate), + }; + } + + const spawnError = attempt.failure; + if (!isRetryableShellSpawnError(spawnError)) { + return yield* spawnError; + } + + return yield* trySpawn(shellCandidates, spawnEnv, session, index + 1, spawnError); + }); + + const startSession = Effect.fn("terminal.startSession")(function* ( + session: TerminalSessionState, + input: TerminalStartInput, + eventType: "started" | "restarted", + ) { + yield* stopProcess(session); + + yield* modifyManagerState((state) => { + session.status = "starting"; + session.cwd = input.cwd; + session.cols = input.cols; + session.rows = input.rows; + session.exitCode = null; + session.exitSignal = null; + session.hasRunningSubprocess = false; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + let ptyProcess: PtyProcess | null = null; + let startedShell: string | null = null; + + const startResult = yield* Effect.result( + Effect.gen(function* () { + const shellCandidates = resolveShellCandidates(shellResolver); + const terminalEnv = createTerminalSpawnEnv(process.env, session.runtimeEnv); + const spawnResult = yield* trySpawn(shellCandidates, terminalEnv, session); + ptyProcess = spawnResult.process; + startedShell = spawnResult.shellLabel; + + const processPid = ptyProcess.pid; + const unsubscribeData = ptyProcess.onData((data) => { + if (!enqueueProcessEvent(session, processPid, { type: "output", data })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + const unsubscribeExit = ptyProcess.onExit((event) => { + if (!enqueueProcessEvent(session, processPid, { type: "exit", event })) { + return; + } + runFork(drainProcessEvents(session, processPid)); + }); + + yield* modifyManagerState((state) => { + session.process = ptyProcess; + session.pid = processPid; + session.status = "running"; + session.updatedAt = new Date().toISOString(); + session.unsubscribeData = unsubscribeData; + session.unsubscribeExit = unsubscribeExit; + return [undefined, state] as const; + }); + + yield* publishEvent({ + type: eventType, + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + snapshot: snapshot(session), + }); + }), + ); + + if (startResult._tag === "Success") { + return; + } + + { + const error = startResult.failure; + if (ptyProcess) { + yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId); + } + + yield* modifyManagerState((state) => { + session.status = "error"; + session.pid = null; + session.process = null; + session.unsubscribeData = null; + session.unsubscribeExit = null; + session.hasRunningSubprocess = false; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + return [undefined, state] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + + const message = error.message; + yield* publishEvent({ + type: "error", + threadId: session.threadId, + terminalId: session.terminalId, + createdAt: new Date().toISOString(), + message, + }); + yield* Effect.logError("failed to start terminal", { + threadId: session.threadId, + terminalId: session.terminalId, + error: message, + ...(startedShell ? { shell: startedShell } : {}), + }); + } + }); + + const closeSession = Effect.fn("terminal.closeSession")(function* ( + threadId: string, + terminalId: string, + deleteHistoryOnClose: boolean, + ) { + const key = toSessionKey(threadId, terminalId); + const session = yield* getSession(threadId, terminalId); + + if (Option.isSome(session)) { + yield* stopProcess(session.value); + yield* persistHistory(threadId, terminalId, session.value.history); + } + + yield* flushPersist(threadId, terminalId); + + yield* modifyManagerState((state) => { + if (!state.sessions.has(key)) { + return [undefined, state] as const; + } + const sessions = new Map(state.sessions); + sessions.delete(key); + return [undefined, { ...state, sessions }] as const; + }); + + if (deleteHistoryOnClose) { + yield* deleteHistory(threadId, terminalId); + } + }); + + const pollSubprocessActivity = Effect.fn("terminal.pollSubprocessActivity")(function* () { + const state = yield* readManagerState; + const runningSessions = [...state.sessions.values()].filter( + (session): session is TerminalSessionState & { pid: number } => + session.status === "running" && Number.isInteger(session.pid), + ); + + if (runningSessions.length === 0) { + return; + } + + const checkSubprocessActivity = Effect.fn("terminal.checkSubprocessActivity")(function* ( + session: TerminalSessionState & { pid: number }, + ) { + const terminalPid = session.pid; + const hasRunningSubprocess = yield* subprocessChecker(terminalPid).pipe( + Effect.map(Option.some), + Effect.catch((error) => + Effect.logWarning("failed to check terminal subprocess activity", { + threadId: session.threadId, + terminalId: session.terminalId, + terminalPid, + error: error instanceof Error ? error.message : String(error), + }).pipe(Effect.as(Option.none())), + ), + ); + + if (Option.isNone(hasRunningSubprocess)) { + return; + } + + const event = yield* modifyManagerState((state) => { + const liveSession: Option.Option = Option.fromNullishOr( + state.sessions.get(toSessionKey(session.threadId, session.terminalId)), + ); + if ( + Option.isNone(liveSession) || + liveSession.value.status !== "running" || + liveSession.value.pid !== terminalPid || + liveSession.value.hasRunningSubprocess === hasRunningSubprocess.value + ) { + return [Option.none(), state] as const; + } + + liveSession.value.hasRunningSubprocess = hasRunningSubprocess.value; + liveSession.value.updatedAt = new Date().toISOString(); + + return [ + Option.some({ + type: "activity" as const, + threadId: liveSession.value.threadId, + terminalId: liveSession.value.terminalId, + createdAt: new Date().toISOString(), + hasRunningSubprocess: hasRunningSubprocess.value, + }), + state, + ] as const; + }); + + if (Option.isSome(event)) { + yield* publishEvent(event.value); + } + }); + + yield* Effect.forEach(runningSessions, checkSubprocessActivity, { + concurrency: "unbounded", + discard: true, + }); + }); + + const hasRunningSessions = readManagerState.pipe( + Effect.map((state) => + [...state.sessions.values()].some((session) => session.status === "running"), + ), + ); + + yield* Effect.forever( + hasRunningSessions.pipe( + Effect.flatMap((active) => + active + ? pollSubprocessActivity().pipe( + Effect.flatMap(() => Effect.sleep(subprocessPollIntervalMs)), + ) + : Effect.sleep(subprocessPollIntervalMs), + ), + ), + ).pipe(Effect.forkIn(workerScope)); + + yield* Effect.addFinalizer(() => + Effect.gen(function* () { + const sessions = yield* modifyManagerState( + (state) => + [ + [...state.sessions.values()], + { + ...state, + sessions: new Map(), + }, + ] as const, + ); + + const cleanupSession = Effect.fn("terminal.cleanupSession")(function* ( + session: TerminalSessionState, + ) { + cleanupProcessHandles(session); + if (!session.process) return; + yield* clearKillFiber(session.process); + yield* runKillEscalation(session.process, session.threadId, session.terminalId); + }); + + yield* Effect.forEach(sessions, cleanupSession, { + concurrency: "unbounded", + discard: true, + }); + }).pipe(Effect.ignoreCause({ log: true })), + ); + + const open: TerminalManagerShape["open"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existing = yield* getSession(input.threadId, terminalId); + if (Option.isNone(existing)) { + yield* flushPersist(input.threadId, terminalId); + const history = yield* readHistory(input.threadId, terminalId); + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + const session: TerminalSessionState = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + status: "starting", + pid: null, + history, + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + + yield* evictInactiveSessionsIfNeeded(); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(session); + } + + const liveSession = existing.value; + const nextRuntimeEnv = normalizedRuntimeEnv(input.env); + const currentRuntimeEnv = liveSession.runtimeEnv; + const targetCols = input.cols ?? liveSession.cols; + const targetRows = input.rows ?? liveSession.rows; + const runtimeEnvChanged = !Equal.equals(currentRuntimeEnv, nextRuntimeEnv); + + if (liveSession.cwd !== input.cwd || runtimeEnvChanged) { + yield* stopProcess(liveSession); + liveSession.cwd = input.cwd; + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } else if (liveSession.status === "exited" || liveSession.status === "error") { + liveSession.runtimeEnv = nextRuntimeEnv; + liveSession.history = ""; + liveSession.pendingHistoryControlSequence = ""; + liveSession.pendingProcessEvents = []; + liveSession.pendingProcessEventIndex = 0; + liveSession.processEventDrainRunning = false; + yield* persistHistory( + liveSession.threadId, + liveSession.terminalId, + liveSession.history, + ); + } + + if (!liveSession.process) { + yield* startSession( + liveSession, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols: targetCols, + rows: targetRows, + ...(input.env ? { env: input.env } : {}), + }, + "started", + ); + return snapshot(liveSession); + } + + if (liveSession.cols !== targetCols || liveSession.rows !== targetRows) { + liveSession.cols = targetCols; + liveSession.rows = targetRows; + liveSession.updatedAt = new Date().toISOString(); + liveSession.process.resize(targetCols, targetRows); + } + + return snapshot(liveSession); + }), + ); + + const write: TerminalManagerShape["write"] = Effect.fn("terminal.write")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + if (session.status === "exited") return; + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + yield* Effect.sync(() => process.write(input.data)); + }); + + const resize: TerminalManagerShape["resize"] = Effect.fn("terminal.resize")(function* (input) { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + const process = session.process; + if (!process || session.status !== "running") { + return yield* new TerminalNotRunningError({ + threadId: input.threadId, + terminalId, + }); + } + session.cols = input.cols; + session.rows = input.rows; + session.updatedAt = new Date().toISOString(); + yield* Effect.sync(() => process.resize(input.cols, input.rows)); + }); + + const clear: TerminalManagerShape["clear"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + const session = yield* requireSession(input.threadId, terminalId); + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + session.updatedAt = new Date().toISOString(); + yield* persistHistory(input.threadId, terminalId, session.history); + yield* publishEvent({ + type: "cleared", + threadId: input.threadId, + terminalId, + createdAt: new Date().toISOString(), + }); + }), + ); + + const restart: TerminalManagerShape["restart"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID; + yield* assertValidCwd(input.cwd); + + const sessionKey = toSessionKey(input.threadId, terminalId); + const existingSession = yield* getSession(input.threadId, terminalId); + let session: TerminalSessionState; + if (Option.isNone(existingSession)) { + const cols = input.cols ?? DEFAULT_OPEN_COLS; + const rows = input.rows ?? DEFAULT_OPEN_ROWS; + session = { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + status: "starting", + pid: null, + history: "", + pendingHistoryControlSequence: "", + pendingProcessEvents: [], + pendingProcessEventIndex: 0, + processEventDrainRunning: false, + exitCode: null, + exitSignal: null, + updatedAt: new Date().toISOString(), + cols, + rows, + process: null, + unsubscribeData: null, + unsubscribeExit: null, + hasRunningSubprocess: false, + runtimeEnv: normalizedRuntimeEnv(input.env), + }; + const createdSession = session; + yield* modifyManagerState((state) => { + const sessions = new Map(state.sessions); + sessions.set(sessionKey, createdSession); + return [undefined, { ...state, sessions }] as const; + }); + yield* evictInactiveSessionsIfNeeded(); + } else { + session = existingSession.value; + yield* stopProcess(session); + session.cwd = input.cwd; + session.runtimeEnv = normalizedRuntimeEnv(input.env); + } + + const cols = input.cols ?? session.cols; + const rows = input.rows ?? session.rows; + + session.history = ""; + session.pendingHistoryControlSequence = ""; + session.pendingProcessEvents = []; + session.pendingProcessEventIndex = 0; + session.processEventDrainRunning = false; + yield* persistHistory(input.threadId, terminalId, session.history); + yield* startSession( + session, + { + threadId: input.threadId, + terminalId, + cwd: input.cwd, + cols, + rows, + ...(input.env ? { env: input.env } : {}), + }, + "restarted", + ); + return snapshot(session); + }), + ); + + const close: TerminalManagerShape["close"] = (input) => + withThreadLock( + input.threadId, + Effect.gen(function* () { + if (input.terminalId) { + yield* closeSession(input.threadId, input.terminalId, input.deleteHistory === true); + return; + } + + const threadSessions = yield* sessionsForThread(input.threadId); + yield* Effect.forEach( + threadSessions, + (session) => closeSession(input.threadId, session.terminalId, false), + { discard: true }, + ); + + if (input.deleteHistory) { + yield* deleteAllHistoryForThread(input.threadId); + } + }), + ); + return { - open: (input) => - Effect.tryPromise({ - try: () => runtime.open(input), - catch: (cause) => new TerminalError({ message: "Failed to open terminal", cause }), - }), - write: (input) => - Effect.tryPromise({ - try: () => runtime.write(input), - catch: (cause) => new TerminalError({ message: "Failed to write to terminal", cause }), - }), - resize: (input) => - Effect.tryPromise({ - try: () => runtime.resize(input), - catch: (cause) => new TerminalError({ message: "Failed to resize terminal", cause }), - }), - clear: (input) => - Effect.tryPromise({ - try: () => runtime.clear(input), - catch: (cause) => new TerminalError({ message: "Failed to clear terminal", cause }), - }), - restart: (input) => - Effect.tryPromise({ - try: () => runtime.restart(input), - catch: (cause) => new TerminalError({ message: "Failed to restart terminal", cause }), - }), - close: (input) => - Effect.tryPromise({ - try: () => runtime.close(input), - catch: (cause) => new TerminalError({ message: "Failed to close terminal", cause }), - }), + open, + write, + resize, + clear, + restart, + close, subscribe: (listener) => Effect.sync(() => { - runtime.on("event", listener); + terminalEventListeners.add(listener); return () => { - runtime.off("event", listener); + terminalEventListeners.delete(listener); }; }), - dispose: Effect.sync(() => runtime.dispose()), } satisfies TerminalManagerShape; - }), + }, ); + +export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()); diff --git a/apps/server/src/terminal/Services/Manager.ts b/apps/server/src/terminal/Services/Manager.ts index c2539da4b6..067cd55438 100644 --- a/apps/server/src/terminal/Services/Manager.ts +++ b/apps/server/src/terminal/Services/Manager.ts @@ -14,47 +14,81 @@ import { TerminalResizeInput, TerminalRestartInput, TerminalSessionSnapshot, - TerminalSessionStatus, TerminalWriteInput, } from "@t3tools/contracts"; -import { PtyProcess } from "./PTY"; import { Effect, Schema, ServiceMap } from "effect"; -export class TerminalError extends Schema.TaggedErrorClass()("TerminalError", { - message: Schema.String, - cause: Schema.optional(Schema.Defect), -}) {} - -export interface TerminalSessionState { - threadId: string; - terminalId: string; - cwd: string; - status: TerminalSessionStatus; - pid: number | null; - history: string; - pendingHistoryControlSequence: string; - exitCode: number | null; - exitSignal: number | null; - updatedAt: string; - cols: number; - rows: number; - process: PtyProcess | null; - unsubscribeData: (() => void) | null; - unsubscribeExit: (() => void) | null; - hasRunningSubprocess: boolean; - runtimeEnv: Record | null; +export class TerminalCwdError extends Schema.TaggedErrorClass()( + "TerminalCwdError", + { + cwd: Schema.String, + reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]), + cause: Schema.optional(Schema.Defect), + }, +) { + override get message() { + if (this.reason === "notDirectory") { + return `Terminal cwd is not a directory: ${this.cwd}`; + } + if (this.reason === "notFound") { + return `Terminal cwd does not exist: ${this.cwd}`; + } + const causeMessage = + this.cause && typeof this.cause === "object" && "message" in this.cause + ? this.cause.message + : undefined; + return causeMessage + ? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})` + : `Failed to access terminal cwd: ${this.cwd}`; + } } -export interface ShellCandidate { - shell: string; - args?: string[]; +export class TerminalHistoryError extends Schema.TaggedErrorClass()( + "TerminalHistoryError", + { + operation: Schema.Literals(["read", "truncate", "migrate"]), + threadId: Schema.String, + terminalId: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) { + override get message() { + return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`; + } } -export interface TerminalStartInput extends TerminalOpenInput { - cols: number; - rows: number; +export class TerminalSessionLookupError extends Schema.TaggedErrorClass()( + "TerminalSessionLookupError", + { + threadId: Schema.String, + terminalId: Schema.String, + }, +) { + override get message() { + return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`; + } } +export class TerminalNotRunningError extends Schema.TaggedErrorClass()( + "TerminalNotRunningError", + { + threadId: Schema.String, + terminalId: Schema.String, + }, +) { + override get message() { + return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`; + } +} + +export const TerminalError = Schema.Union([ + TerminalCwdError, + TerminalHistoryError, + TerminalSessionLookupError, + TerminalNotRunningError, +]); +export type TerminalError = typeof TerminalError.Type; + /** * TerminalManagerShape - Service API for terminal session lifecycle operations. */ @@ -101,14 +135,13 @@ export interface TerminalManagerShape { readonly close: (input: TerminalCloseInput) => Effect.Effect; /** - * Subscribe to terminal runtime events. + * Subscribe to terminal runtime events with a direct callback. + * + * Returns an unsubscribe function. */ - readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>; - - /** - * Dispose all managed terminal resources. - */ - readonly dispose: Effect.Effect; + readonly subscribe: ( + listener: (event: TerminalEvent) => Effect.Effect, + ) => Effect.Effect<() => void>; } /** diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index 6dcf8b38ed..0e06650fe6 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -4,7 +4,7 @@ import os from "node:os"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect"; +import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect"; import { describe, expect, it, afterEach, vi } from "vitest"; import { createServer } from "./wsServer"; import WebSocket from "ws"; @@ -90,20 +90,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS; class MockTerminalManager implements TerminalManagerShape { private readonly sessions = new Map(); - private readonly listeners = new Set<(event: TerminalEvent) => void>(); + private readonly eventPubSub = Effect.runSync(PubSub.unbounded()); + private activeSubscriptions = 0; private key(threadId: string, terminalId: string): string { return `${threadId}\u0000${terminalId}`; } emitEvent(event: TerminalEvent): void { - for (const listener of this.listeners) { - listener(event); - } + Effect.runSync(PubSub.publish(this.eventPubSub, event)); } subscriptionCount(): number { - return this.listeners.size; + return this.activeSubscriptions; } readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) => @@ -210,13 +209,15 @@ class MockTerminalManager implements TerminalManagerShape { readonly subscribe: TerminalManagerShape["subscribe"] = (listener) => Effect.sync(() => { - this.listeners.add(listener); + this.activeSubscriptions += 1; + const fiber = Effect.runFork( + Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)), + ); return () => { - this.listeners.delete(listener); + this.activeSubscriptions -= 1; + Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore)); }; }); - - readonly dispose: TerminalManagerShape["dispose"] = Effect.void; } // --------------------------------------------------------------------------- @@ -1454,19 +1455,25 @@ describe("WebSocket Server", () => { expect(push.channel).toBe(WS_CHANNELS.terminalEvent); }); - it("detaches terminal event listener on stop for injected manager", async () => { + it("shuts down cleanly for injected terminal managers", async () => { const terminalManager = new MockTerminalManager(); server = await createTestServer({ cwd: "/test", terminalManager, }); - expect(terminalManager.subscriptionCount()).toBe(1); - await closeTestServer(); server = null; - expect(terminalManager.subscriptionCount()).toBe(0); + expect(() => + terminalManager.emitEvent({ + type: "output", + threadId: "thread-1", + terminalId: DEFAULT_TERMINAL_ID, + createdAt: new Date().toISOString(), + data: "after shutdown\n", + }), + ).not.toThrow(); }); it("returns validation errors for invalid terminal open params", async () => { diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index c04d913d52..25f8158926 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -719,9 +719,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< } const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) => - runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)), + pushBus.publishAll(WS_CHANNELS.terminalEvent, event), ); - yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents())); + yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents)); yield* readiness.markTerminalSubscriptionsReady; yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe( diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index 5585e7f309..e8b1c46274 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -130,12 +130,12 @@ export interface NativeApi { confirm: (message: string) => Promise; }; terminal: { - open: (input: TerminalOpenInput) => Promise; - write: (input: TerminalWriteInput) => Promise; - resize: (input: TerminalResizeInput) => Promise; - clear: (input: TerminalClearInput) => Promise; - restart: (input: TerminalRestartInput) => Promise; - close: (input: TerminalCloseInput) => Promise; + open: (input: typeof TerminalOpenInput.Encoded) => Promise; + write: (input: typeof TerminalWriteInput.Encoded) => Promise; + resize: (input: typeof TerminalResizeInput.Encoded) => Promise; + clear: (input: typeof TerminalClearInput.Encoded) => Promise; + restart: (input: typeof TerminalRestartInput.Encoded) => Promise; + close: (input: typeof TerminalCloseInput.Encoded) => Promise; onEvent: (callback: (event: TerminalEvent) => void) => () => void; }; projects: { diff --git a/packages/contracts/src/terminal.ts b/packages/contracts/src/terminal.ts index b0493d95c2..f9729da66f 100644 --- a/packages/contracts/src/terminal.ts +++ b/packages/contracts/src/terminal.ts @@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe( export const TerminalThreadInput = Schema.Struct({ threadId: TrimmedNonEmptyStringSchema, }); -export type TerminalThreadInput = Schema.Codec.Encoded; +export type TerminalThreadInput = typeof TerminalThreadInput.Type; const TerminalSessionInput = Schema.Struct({ ...TerminalThreadInput.fields, @@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({ terminalId: Schema.optional(TerminalIdSchema), deleteHistory: Schema.optional(Schema.Boolean), }); -export type TerminalCloseInput = Schema.Codec.Encoded; +export type TerminalCloseInput = typeof TerminalCloseInput.Type; export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]); export type TerminalSessionStatus = typeof TerminalSessionStatus.Type; diff --git a/packages/shared/package.json b/packages/shared/package.json index 40ffbf35c2..b35d23ef15 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -28,6 +28,10 @@ "types": "./src/DrainableWorker.ts", "import": "./src/DrainableWorker.ts" }, + "./KeyedCoalescingWorker": { + "types": "./src/KeyedCoalescingWorker.ts", + "import": "./src/KeyedCoalescingWorker.ts" + }, "./schemaJson": { "types": "./src/schemaJson.ts", "import": "./src/schemaJson.ts" diff --git a/packages/shared/src/KeyedCoalescingWorker.test.ts b/packages/shared/src/KeyedCoalescingWorker.test.ts new file mode 100644 index 0000000000..2226bbd003 --- /dev/null +++ b/packages/shared/src/KeyedCoalescingWorker.test.ts @@ -0,0 +1,96 @@ +import { it } from "@effect/vitest"; +import { describe, expect } from "vitest"; +import { Deferred, Effect } from "effect"; + +import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker"; + +describe("makeKeyedCoalescingWorker", () => { + it.live("waits for latest work enqueued during active processing before draining the key", () => + Effect.scoped( + Effect.gen(function* () { + const processed: string[] = []; + const firstStarted = yield* Deferred.make(); + const releaseFirst = yield* Deferred.make(); + const secondStarted = yield* Deferred.make(); + const releaseSecond = yield* Deferred.make(); + + const worker = yield* makeKeyedCoalescingWorker({ + merge: (_current, next) => next, + process: (key, value) => + Effect.gen(function* () { + processed.push(`${key}:${value}`); + + if (value === "first") { + yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseFirst); + } + + if (value === "second") { + yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseSecond); + } + }), + }); + + yield* worker.enqueue("terminal-1", "first"); + yield* Deferred.await(firstStarted); + + const drained = yield* Deferred.make(); + yield* Effect.forkChild( + worker + .drainKey("terminal-1") + .pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))), + ); + + yield* worker.enqueue("terminal-1", "second"); + yield* Deferred.succeed(releaseFirst, undefined); + yield* Deferred.await(secondStarted); + + expect(yield* Deferred.isDone(drained)).toBe(false); + + yield* Deferred.succeed(releaseSecond, undefined); + yield* Deferred.await(drained); + + expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]); + }), + ), + ); + + it.live("requeues pending work for a key after a processor failure and keeps draining", () => + Effect.scoped( + Effect.gen(function* () { + const processed: string[] = []; + const firstStarted = yield* Deferred.make(); + const releaseFailure = yield* Deferred.make(); + const secondProcessed = yield* Deferred.make(); + + const worker = yield* makeKeyedCoalescingWorker({ + merge: (_current, next) => next, + process: (key, value) => + Effect.gen(function* () { + processed.push(`${key}:${value}`); + + if (value === "first") { + yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie); + yield* Deferred.await(releaseFailure); + yield* Effect.fail("boom"); + } + + if (value === "second") { + yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie); + } + }), + }); + + yield* worker.enqueue("terminal-1", "first"); + yield* Deferred.await(firstStarted); + yield* worker.enqueue("terminal-1", "second"); + yield* Deferred.succeed(releaseFailure, undefined); + yield* Deferred.await(secondProcessed); + yield* worker.drainKey("terminal-1"); + + expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]); + }), + ), + ); +}); diff --git a/packages/shared/src/KeyedCoalescingWorker.ts b/packages/shared/src/KeyedCoalescingWorker.ts new file mode 100644 index 0000000000..567c1dac17 --- /dev/null +++ b/packages/shared/src/KeyedCoalescingWorker.ts @@ -0,0 +1,140 @@ +/** + * KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key. + * + * Enqueues for an active or already-queued key are merged atomically instead of + * creating duplicate queued items. `drainKey()` resolves only when that key has + * no queued, pending, or active work left. + * + * @module KeyedCoalescingWorker + */ +import type { Scope } from "effect"; +import { Effect, TxQueue, TxRef } from "effect"; + +export interface KeyedCoalescingWorker { + readonly enqueue: (key: K, value: V) => Effect.Effect; + readonly drainKey: (key: K) => Effect.Effect; +} + +interface KeyedCoalescingWorkerState { + readonly latestByKey: Map; + readonly queuedKeys: Set; + readonly activeKeys: Set; +} + +export const makeKeyedCoalescingWorker = (options: { + readonly merge: (current: V, next: V) => V; + readonly process: (key: K, value: V) => Effect.Effect; +}): Effect.Effect, never, Scope.Scope | R> => + Effect.gen(function* () { + const queue = yield* Effect.acquireRelease(TxQueue.unbounded(), TxQueue.shutdown); + const stateRef = yield* TxRef.make>({ + latestByKey: new Map(), + queuedKeys: new Set(), + activeKeys: new Set(), + }); + + const processKey = (key: K, value: V): Effect.Effect => + options.process(key, value).pipe( + Effect.flatMap(() => + TxRef.modify(stateRef, (state) => { + const nextValue = state.latestByKey.get(key); + if (nextValue === undefined) { + const activeKeys = new Set(state.activeKeys); + activeKeys.delete(key); + return [null, { ...state, activeKeys }] as const; + } + + const latestByKey = new Map(state.latestByKey); + latestByKey.delete(key); + return [nextValue, { ...state, latestByKey }] as const; + }).pipe(Effect.tx), + ), + Effect.flatMap((nextValue) => + nextValue === null ? Effect.void : processKey(key, nextValue), + ), + ); + + const cleanupFailedKey = (key: K): Effect.Effect => + TxRef.modify(stateRef, (state) => { + const activeKeys = new Set(state.activeKeys); + activeKeys.delete(key); + + if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, activeKeys, queuedKeys }] as const; + } + + return [false, { ...state, activeKeys }] as const; + }).pipe( + Effect.tx, + Effect.flatMap((shouldRequeue) => + shouldRequeue ? TxQueue.offer(queue, key) : Effect.void, + ), + ); + + yield* TxQueue.take(queue).pipe( + Effect.flatMap((key) => + TxRef.modify(stateRef, (state) => { + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.delete(key); + + const value = state.latestByKey.get(key); + if (value === undefined) { + return [null, { ...state, queuedKeys }] as const; + } + + const latestByKey = new Map(state.latestByKey); + latestByKey.delete(key); + const activeKeys = new Set(state.activeKeys); + activeKeys.add(key); + + return [ + { key, value } as const, + { ...state, latestByKey, queuedKeys, activeKeys }, + ] as const; + }).pipe(Effect.tx), + ), + Effect.flatMap((item) => + item === null + ? Effect.void + : processKey(item.key, item.value).pipe( + Effect.catchCause(() => cleanupFailedKey(item.key)), + ), + ), + Effect.forever, + Effect.forkScoped, + ); + + const enqueue: KeyedCoalescingWorker["enqueue"] = (key, value) => + TxRef.modify(stateRef, (state) => { + const latestByKey = new Map(state.latestByKey); + const existing = latestByKey.get(key); + latestByKey.set(key, existing === undefined ? value : options.merge(existing, value)); + + if (state.queuedKeys.has(key) || state.activeKeys.has(key)) { + return [false, { ...state, latestByKey }] as const; + } + + const queuedKeys = new Set(state.queuedKeys); + queuedKeys.add(key); + return [true, { ...state, latestByKey, queuedKeys }] as const; + }).pipe( + Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)), + Effect.tx, + Effect.asVoid, + ); + + const drainKey: KeyedCoalescingWorker["drainKey"] = (key) => + TxRef.get(stateRef).pipe( + Effect.tap((state) => + state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key) + ? Effect.txRetry + : Effect.void, + ), + Effect.asVoid, + Effect.tx, + ); + + return { enqueue, drainKey } satisfies KeyedCoalescingWorker; + }); From 6f517257325f7c8bcac660595f2cbc53c1d32b35 Mon Sep 17 00:00:00 2001 From: Utkarsh Patil <73941998+UtkarshUsername@users.noreply.github.com> Date: Mon, 30 Mar 2026 23:01:38 +0530 Subject: [PATCH 56/66] refactor(web): remove redundant add-project cancel button (#1302) --- apps/web/src/components/Sidebar.tsx | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 55c5271c37..207082477d 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1934,7 +1934,6 @@ export default function Sidebar() { - {shouldShowProjectPathEntry && (
{isElectron && ( @@ -1985,18 +1984,6 @@ export default function Sidebar() { {addProjectError}

)} -
- -
)} From 0ea639196a7bed94deb08f5c96d147418f4e9749 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Mar 2026 12:51:49 -0700 Subject: [PATCH 57/66] Refactor web orchestration sync to incremental events and isolated recovery (#1560) Co-authored-by: codex Co-authored-by: Cursor Agent --- apps/web/src/components/ChatView.browser.tsx | 103 +- .../web/src/components/ChatView.logic.test.ts | 300 ++++- apps/web/src/components/ChatView.logic.ts | 121 +- apps/web/src/components/ChatView.tsx | 346 ++++-- .../components/KeybindingsToast.browser.tsx | 2 +- apps/web/src/components/Sidebar.logic.test.ts | 50 +- apps/web/src/components/Sidebar.logic.ts | 64 +- apps/web/src/components/Sidebar.tsx | 132 +- apps/web/src/composerDraftStore.test.ts | 53 + apps/web/src/composerDraftStore.ts | 25 +- apps/web/src/hooks/useHandleNewThread.ts | 24 +- apps/web/src/hooks/useThreadActions.ts | 13 +- .../web/src/orchestrationEventEffects.test.ts | 108 ++ apps/web/src/orchestrationEventEffects.ts | 76 ++ apps/web/src/orchestrationRecovery.test.ts | 100 ++ apps/web/src/orchestrationRecovery.ts | 136 ++ apps/web/src/router.ts | 12 +- apps/web/src/routes/__root.tsx | 193 ++- apps/web/src/routes/_chat.$threadId.tsx | 8 +- apps/web/src/routes/_chat.tsx | 25 +- apps/web/src/session-logic.test.ts | 32 + apps/web/src/session-logic.ts | 47 + apps/web/src/store.test.ts | 582 +++++++-- apps/web/src/store.ts | 1096 ++++++++++++----- apps/web/src/storeSelectors.ts | 14 + apps/web/src/terminalStateStore.ts | 10 + apps/web/src/types.ts | 4 +- apps/web/src/uiStateStore.test.ts | 192 +++ apps/web/src/uiStateStore.ts | 417 +++++++ 29 files changed, 3613 insertions(+), 672 deletions(-) create mode 100644 apps/web/src/orchestrationEventEffects.test.ts create mode 100644 apps/web/src/orchestrationEventEffects.ts create mode 100644 apps/web/src/orchestrationRecovery.test.ts create mode 100644 apps/web/src/orchestrationRecovery.ts create mode 100644 apps/web/src/storeSelectors.ts create mode 100644 apps/web/src/uiStateStore.test.ts create mode 100644 apps/web/src/uiStateStore.ts diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 0d612534e5..20816d6935 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -2,8 +2,11 @@ import "../index.css"; import { + EventId, ORCHESTRATION_WS_METHODS, + ORCHESTRATION_WS_CHANNELS, type MessageId, + type OrchestrationEvent, type OrchestrationReadModel, type ProjectId, type ServerConfig, @@ -57,6 +60,8 @@ interface TestFixture { let fixture: TestFixture; const wsRequests: WsRequestEnvelope["body"][] = []; let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null; +let wsClient: { send: (message: string) => void } | null = null; +let pushSequence = 1; const wsLink = ws.link(/ws(s)?:\/\/.*/); interface ViewportSpec { @@ -336,6 +341,79 @@ function addThreadToSnapshot( }; } +function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent { + return { + sequence, + eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: NOW_ISO, + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type: "thread.created", + payload: { + threadId, + projectId: PROJECT_ID, + title: "New thread", + modelSelection: { + provider: "codex", + model: "gpt-5", + }, + runtimeMode: "full-access", + interactionMode: "default", + branch: "main", + worktreePath: null, + createdAt: NOW_ISO, + updatedAt: NOW_ISO, + }, + }; +} + +function sendOrchestrationDomainEvent(event: OrchestrationEvent): void { + if (!wsClient) { + throw new Error("WebSocket client not connected"); + } + wsClient.send( + JSON.stringify({ + type: "push", + sequence: pushSequence++, + channel: ORCHESTRATION_WS_CHANNELS.domainEvent, + data: event, + }), + ); +} + +async function waitForWsClient(): Promise<{ send: (message: string) => void }> { + let client: { send: (message: string) => void } | null = null; + await vi.waitFor( + () => { + client = wsClient; + expect(client).toBeTruthy(); + }, + { timeout: 8_000, interval: 16 }, + ); + if (!client) { + throw new Error("WebSocket client not connected"); + } + return client; +} + +async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise { + await waitForWsClient(); + fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId); + sendOrchestrationDomainEvent( + createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence), + ); + await vi.waitFor( + () => { + expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined(); + }, + { timeout: 8_000, interval: 16 }, + ); +} + function createDraftOnlySnapshot(): OrchestrationReadModel { const snapshot = createSnapshotForTargetUser({ targetMessageId: "msg-user-draft-target" as MessageId, @@ -500,10 +578,12 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { const worker = setupWorker( wsLink.addEventListener("connection", ({ client }) => { + wsClient = client; + pushSequence = 1; client.send( JSON.stringify({ type: "push", - sequence: 1, + sequence: pushSequence++, channel: WS_CHANNELS.serverWelcome, data: fixture.welcome, }), @@ -875,7 +955,7 @@ describe("ChatView timeline estimator parity (full app)", () => { useStore.setState({ projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }); }); @@ -1881,21 +1961,16 @@ describe("ChatView timeline estimator parity (full app)", () => { // The composer editor should be present for the new draft thread. await waitForComposerEditor(); - // Simulate the snapshot sync arriving from the server after the draft - // thread has been promoted to a server thread (thread.create + turn.start - // succeeded). The snapshot now includes the new thread, and the sync - // should clear the draft without disrupting the route. - const { syncServerReadModel } = useStore.getState(); - syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId)); - - // Clear the draft now that the server thread exists (mirrors EventRouter behavior). - useComposerDraftStore.getState().clearDraftThread(newThreadId); + // Simulate the steady-state promotion path: the server emits + // `thread.created`, the client materializes the thread incrementally, + // and the draft is cleared by live batch effects. + await promoteDraftThreadViaDomainEvent(newThreadId); // The route should still be on the new thread — not redirected away. await waitForURL( mounted.router, (path) => path === newThreadPath, - "New thread should remain selected after snapshot sync clears the draft.", + "New thread should remain selected after server thread promotion clears the draft.", ); // The empty thread view and composer should still be visible. @@ -2217,9 +2292,7 @@ describe("ChatView timeline estimator parity (full app)", () => { ); const promotedThreadId = promotedThreadPath.slice(1) as ThreadId; - const { syncServerReadModel } = useStore.getState(); - syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId)); - useComposerDraftStore.getState().clearDraftThread(promotedThreadId); + await promoteDraftThreadViaDomainEvent(promotedThreadId); const freshThreadPath = await triggerChatNewShortcutUntilPath( mounted.router, diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.ts index bf72ec0b84..80c842d91f 100644 --- a/apps/web/src/components/ChatView.logic.test.ts +++ b/apps/web/src/components/ChatView.logic.test.ts @@ -1,7 +1,14 @@ -import { ThreadId } from "@t3tools/contracts"; -import { describe, expect, it } from "vitest"; +import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { useStore } from "../store"; -import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic"; +import { + buildExpiredTerminalContextToastCopy, + createLocalDispatchSnapshot, + deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, + waitForStartedServerThread, +} from "./ChatView.logic"; describe("deriveComposerSendState", () => { it("treats expired terminal pills as non-sendable content", () => { @@ -67,3 +74,290 @@ describe("buildExpiredTerminalContextToastCopy", () => { }); }); }); + +const makeThread = (input?: { + id?: ThreadId; + latestTurn?: { + turnId: TurnId; + state: "running" | "completed"; + requestedAt: string; + startedAt: string | null; + completedAt: string | null; + } | null; +}) => ({ + id: input?.id ?? ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId: ProjectId.makeUnsafe("project-1"), + title: "Thread", + modelSelection: { provider: "codex" as const, model: "gpt-5.4" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + session: null, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:00.000Z", + latestTurn: input?.latestTurn + ? { + ...input.latestTurn, + assistantMessageId: null, + } + : null, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], +}); + +afterEach(() => { + vi.useRealTimers(); + vi.restoreAllMocks(); + useStore.setState((state) => ({ + ...state, + projects: [], + threads: [], + bootstrapComplete: true, + })); +}); + +describe("waitForStartedServerThread", () => { + it("resolves immediately when the thread is already started", async () => { + const threadId = ThreadId.makeUnsafe("thread-started"); + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(waitForStartedServerThread(threadId)).resolves.toBe(true); + }); + + it("waits for the thread to start via subscription updates", async () => { + const threadId = ThreadId.makeUnsafe("thread-wait"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const promise = waitForStartedServerThread(threadId, 500); + + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-started"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + + await expect(promise).resolves.toBe(true); + }); + + it("handles the thread starting between the initial read and subscription setup", async () => { + const threadId = ThreadId.makeUnsafe("thread-race"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + + const originalSubscribe = useStore.subscribe.bind(useStore); + let raced = false; + vi.spyOn(useStore, "subscribe").mockImplementation((listener) => { + if (!raced) { + raced = true; + useStore.setState((state) => ({ + ...state, + threads: [ + makeThread({ + id: threadId, + latestTurn: { + turnId: TurnId.makeUnsafe("turn-race"), + state: "running", + requestedAt: "2026-03-29T00:00:01.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: null, + }, + }), + ], + })); + } + return originalSubscribe(listener); + }); + + await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true); + }); + + it("returns false after the timeout when the thread never starts", async () => { + vi.useFakeTimers(); + + const threadId = ThreadId.makeUnsafe("thread-timeout"); + useStore.setState((state) => ({ + ...state, + threads: [makeThread({ id: threadId })], + })); + const promise = waitForStartedServerThread(threadId, 500); + + await vi.advanceTimersByTimeAsync(500); + + await expect(promise).resolves.toBe(false); + }); +}); + +describe("hasServerAcknowledgedLocalDispatch", () => { + const projectId = ProjectId.makeUnsafe("project-1"); + const previousLatestTurn = { + turnId: TurnId.makeUnsafe("turn-1"), + state: "completed" as const, + requestedAt: "2026-03-29T00:00:00.000Z", + startedAt: "2026-03-29T00:00:01.000Z", + completedAt: "2026-03-29T00:00:10.000Z", + assistantMessageId: null, + }; + + const previousSession = { + provider: "codex" as const, + status: "ready" as const, + createdAt: "2026-03-29T00:00:00.000Z", + updatedAt: "2026-03-29T00:00:10.000Z", + orchestrationStatus: "idle" as const, + }; + + it("does not clear local dispatch before server state changes", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: previousSession, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(false); + }); + + it("clears local dispatch when a new turn is already settled", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: { + ...previousLatestTurn, + turnId: TurnId.makeUnsafe("turn-2"), + requestedAt: "2026-03-29T00:01:00.000Z", + startedAt: "2026-03-29T00:01:01.000Z", + completedAt: "2026-03-29T00:01:30.000Z", + }, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:01:30.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); + + it("clears local dispatch when the session changes without an observed running phase", () => { + const localDispatch = createLocalDispatchSnapshot({ + id: ThreadId.makeUnsafe("thread-1"), + codexThreadId: null, + projectId, + title: "Thread", + modelSelection: { provider: "codex", model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + session: previousSession, + messages: [], + proposedPlans: [], + error: null, + createdAt: "2026-03-29T00:00:00.000Z", + archivedAt: null, + updatedAt: "2026-03-29T00:00:10.000Z", + latestTurn: previousLatestTurn, + branch: null, + worktreePath: null, + turnDiffSummaries: [], + activities: [], + }); + + expect( + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: "ready", + latestTurn: previousLatestTurn, + session: { + ...previousSession, + updatedAt: "2026-03-29T00:00:11.000Z", + }, + hasPendingApproval: false, + hasPendingUserInput: false, + threadError: null, + }), + ).toBe(true); + }); +}); diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.ts index 0a27fb203e..1821c65ed9 100644 --- a/apps/web/src/components/ChatView.logic.ts +++ b/apps/web/src/components/ChatView.logic.ts @@ -1,8 +1,9 @@ -import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts"; -import { type ChatMessage, type Thread } from "../types"; +import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts"; +import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types"; import { randomUUID } from "~/lib/utils"; import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore"; import { Schema } from "effect"; +import { useStore } from "../store"; import { filterTerminalContextsWithText, stripInlineTerminalContextPlaceholders, @@ -34,7 +35,6 @@ export function buildLocalDraftThread( createdAt: draftThread.createdAt, archivedAt: null, latestTurn: null, - lastVisitedAt: draftThread.createdAt, branch: draftThread.branch, worktreePath: draftThread.worktreePath, turnDiffSummaries: [], @@ -75,8 +75,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[ return previewUrls; } -export type SendPhase = "idle" | "preparing-worktree" | "sending-turn"; - export interface PullRequestDialogState { initialReference: string | null; key: number; @@ -161,3 +159,116 @@ export function buildExpiredTerminalContextToastCopy( description: "Re-add it if you want that terminal output included.", }; } + +export function threadHasStarted(thread: Thread | null | undefined): boolean { + return Boolean( + thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null), + ); +} + +export async function waitForStartedServerThread( + threadId: ThreadId, + timeoutMs = 1_000, +): Promise { + const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId); + const thread = getThread(); + + if (threadHasStarted(thread)) { + return true; + } + + return await new Promise((resolve) => { + let settled = false; + let timeoutId: ReturnType | null = null; + const finish = (result: boolean) => { + if (settled) { + return; + } + settled = true; + if (timeoutId !== null) { + globalThis.clearTimeout(timeoutId); + } + unsubscribe(); + resolve(result); + }; + + const unsubscribe = useStore.subscribe((state) => { + if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) { + return; + } + finish(true); + }); + + if (threadHasStarted(getThread())) { + finish(true); + return; + } + + timeoutId = globalThis.setTimeout(() => { + finish(false); + }, timeoutMs); + }); +} + +export interface LocalDispatchSnapshot { + startedAt: string; + preparingWorktree: boolean; + latestTurnTurnId: TurnId | null; + latestTurnRequestedAt: string | null; + latestTurnStartedAt: string | null; + latestTurnCompletedAt: string | null; + sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null; + sessionUpdatedAt: string | null; +} + +export function createLocalDispatchSnapshot( + activeThread: Thread | undefined, + options?: { preparingWorktree?: boolean }, +): LocalDispatchSnapshot { + const latestTurn = activeThread?.latestTurn ?? null; + const session = activeThread?.session ?? null; + return { + startedAt: new Date().toISOString(), + preparingWorktree: Boolean(options?.preparingWorktree), + latestTurnTurnId: latestTurn?.turnId ?? null, + latestTurnRequestedAt: latestTurn?.requestedAt ?? null, + latestTurnStartedAt: latestTurn?.startedAt ?? null, + latestTurnCompletedAt: latestTurn?.completedAt ?? null, + sessionOrchestrationStatus: session?.orchestrationStatus ?? null, + sessionUpdatedAt: session?.updatedAt ?? null, + }; +} + +export function hasServerAcknowledgedLocalDispatch(input: { + localDispatch: LocalDispatchSnapshot | null; + phase: SessionPhase; + latestTurn: Thread["latestTurn"] | null; + session: Thread["session"] | null; + hasPendingApproval: boolean; + hasPendingUserInput: boolean; + threadError: string | null | undefined; +}): boolean { + if (!input.localDispatch) { + return false; + } + if ( + input.phase === "running" || + input.hasPendingApproval || + input.hasPendingUserInput || + Boolean(input.threadError) + ) { + return true; + } + + const latestTurn = input.latestTurn ?? null; + const session = input.session ?? null; + + return ( + input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) || + input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) || + input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) || + input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) || + input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) || + input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null) + ); +} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fbd332354a..7562f845e2 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -20,6 +20,7 @@ import { OrchestrationThreadActivity, ProviderInteractionMode, RuntimeMode, + TerminalOpenInput, } from "@t3tools/contracts"; import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model"; import { truncate } from "@t3tools/shared/String"; @@ -42,6 +43,7 @@ import { replaceTextRange, } from "../composer-logic"; import { + deriveCompletionDividerBeforeEntryId, derivePendingApprovals, derivePendingUserInputs, derivePhase, @@ -64,6 +66,8 @@ import { type PendingUserInputDraftAnswer, } from "../pendingUserInput"; import { useStore } from "../store"; +import { useProjectById, useThreadById } from "../storeSelectors"; +import { useUiStateStore } from "../uiStateStore"; import { buildPlanImplementationThreadTitle, buildPlanImplementationPrompt, @@ -76,8 +80,12 @@ import { DEFAULT_THREAD_TERMINAL_ID, MAX_TERMINALS_PER_GROUP, type ChatMessage, + type SessionPhase, + type Thread, type TurnDiffSummary, } from "../types"; +import { LRUCache } from "../lib/lruCache"; + import { basenameOfPath } from "../vscode-icons"; import { useTheme } from "../hooks/useTheme"; import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries"; @@ -168,14 +176,18 @@ import { buildTemporaryWorktreeBranchName, cloneComposerImageForRetry, collectUserMessageBlobPreviewUrls, + createLocalDispatchSnapshot, deriveComposerSendState, + hasServerAcknowledgedLocalDispatch, LAST_INVOKED_SCRIPT_BY_PROJECT_KEY, LastInvokedScriptByProjectSchema, + type LocalDispatchSnapshot, PullRequestDialogState, readFileAsDataUrl, revokeBlobPreviewUrl, revokeUserMessagePreviewUrls, - SendPhase, + threadHasStarted, + waitForStartedServerThread, } from "./ChatView.logic"; import { useLocalStorage } from "~/hooks/useLocalStorage"; @@ -190,6 +202,81 @@ const EMPTY_AVAILABLE_EDITORS: EditorId[] = []; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; +type ThreadPlanCatalogEntry = Pick; + +const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500; +const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024; +const threadPlanCatalogCache = new LRUCache<{ + proposedPlans: Thread["proposedPlans"]; + entry: ThreadPlanCatalogEntry; +}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES); + +function estimateThreadPlanCatalogEntrySize(thread: Thread): number { + return Math.max( + 64, + thread.id.length + + thread.proposedPlans.reduce( + (total, plan) => + total + + plan.id.length + + plan.planMarkdown.length + + plan.updatedAt.length + + (plan.turnId?.length ?? 0), + 0, + ), + ); +} + +function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry { + const cached = threadPlanCatalogCache.get(thread.id); + if (cached && cached.proposedPlans === thread.proposedPlans) { + return cached.entry; + } + + const entry: ThreadPlanCatalogEntry = { + id: thread.id, + proposedPlans: thread.proposedPlans, + }; + threadPlanCatalogCache.set( + thread.id, + { + proposedPlans: thread.proposedPlans, + entry, + }, + estimateThreadPlanCatalogEntrySize(thread), + ); + return entry; +} + +function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] { + const selector = useMemo(() => { + let previousThreads: Array | null = null; + let previousEntries: ThreadPlanCatalogEntry[] = []; + + return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => { + const nextThreads = threadIds.map((threadId) => + state.threads.find((thread) => thread.id === threadId), + ); + const cachedThreads = previousThreads; + if ( + cachedThreads && + nextThreads.length === cachedThreads.length && + nextThreads.every((thread, index) => thread === cachedThreads[index]) + ) { + return previousEntries; + } + + previousThreads = nextThreads; + previousEntries = nextThreads.flatMap((thread) => + thread ? [toThreadPlanCatalogEntry(thread)] : [], + ); + return previousEntries; + }; + }, [threadIds]); + + return useStore(selector); +} + function formatOutgoingPrompt(params: { provider: ProviderKind; model: string | null; @@ -245,13 +332,81 @@ interface PendingPullRequestSetupRequest { scriptId: string; } +function useLocalDispatchState(input: { + activeThread: Thread | undefined; + activeLatestTurn: Thread["latestTurn"] | null; + phase: SessionPhase; + activePendingApproval: ApprovalRequestId | null; + activePendingUserInput: ApprovalRequestId | null; + threadError: string | null | undefined; +}) { + const [localDispatch, setLocalDispatch] = useState(null); + + const beginLocalDispatch = useCallback( + (options?: { preparingWorktree?: boolean }) => { + const preparingWorktree = Boolean(options?.preparingWorktree); + setLocalDispatch((current) => { + if (current) { + return current.preparingWorktree === preparingWorktree + ? current + : { ...current, preparingWorktree }; + } + return createLocalDispatchSnapshot(input.activeThread, options); + }); + }, + [input.activeThread], + ); + + const resetLocalDispatch = useCallback(() => { + setLocalDispatch(null); + }, []); + + const serverAcknowledgedLocalDispatch = useMemo( + () => + hasServerAcknowledgedLocalDispatch({ + localDispatch, + phase: input.phase, + latestTurn: input.activeLatestTurn, + session: input.activeThread?.session ?? null, + hasPendingApproval: input.activePendingApproval !== null, + hasPendingUserInput: input.activePendingUserInput !== null, + threadError: input.threadError, + }), + [ + input.activeLatestTurn, + input.activePendingApproval, + input.activePendingUserInput, + input.activeThread?.session, + input.phase, + input.threadError, + localDispatch, + ], + ); + + useEffect(() => { + if (!serverAcknowledgedLocalDispatch) { + return; + } + resetLocalDispatch(); + }, [resetLocalDispatch, serverAcknowledgedLocalDispatch]); + + return { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt: localDispatch?.startedAt ?? null, + isPreparingWorktree: localDispatch?.preparingWorktree ?? false, + isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch, + }; +} + export default function ChatView({ threadId }: ChatViewProps) { - const threads = useStore((store) => store.threads); - const projects = useStore((store) => store.projects); - const markThreadVisited = useStore((store) => store.markThreadVisited); - const syncServerReadModel = useStore((store) => store.syncServerReadModel); + const serverThread = useThreadById(threadId); const setStoreThreadError = useStore((store) => store.setError); const setStoreThreadBranch = useStore((store) => store.setThreadBranch); + const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); + const activeThreadLastVisitedAt = useUiStateStore( + (store) => store.threadLastVisitedAtById[threadId], + ); const settings = useSettings(); const setStickyComposerModelSelection = useComposerDraftStore( (store) => store.setStickyModelSelection, @@ -330,8 +485,6 @@ export default function ChatView({ threadId }: ChatViewProps) { const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState< Record >({}); - const [sendPhase, setSendPhase] = useState("idle"); - const [sendStartedAt, setSendStartedAt] = useState(null); const [isConnecting, _setIsConnecting] = useState(false); const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false); const [respondingRequestIds, setRespondingRequestIds] = useState([]); @@ -466,8 +619,7 @@ export default function ChatView({ threadId }: ChatViewProps) { [composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId], ); - const serverThread = threads.find((t) => t.id === threadId); - const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId); + const fallbackDraftProject = useProjectById(draftThread?.projectId); const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null); const localDraftThread = useMemo( () => @@ -495,12 +647,25 @@ export default function ChatView({ threadId }: ChatViewProps) { const diffOpen = rawSearch.diff === "1"; const activeThreadId = activeThread?.id ?? null; const activeLatestTurn = activeThread?.latestTurn ?? null; + const threadPlanCatalog = useThreadPlanCatalog( + useMemo(() => { + const threadIds: ThreadId[] = []; + if (activeThread?.id) { + threadIds.push(activeThread.id); + } + const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId; + if (sourceThreadId && sourceThreadId !== activeThread?.id) { + threadIds.push(sourceThreadId); + } + return threadIds; + }, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]), + ); const activeContextWindow = useMemo( () => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []), [activeThread?.activities], ); const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null); - const activeProject = projects.find((p) => p.id === activeThread?.projectId); + const activeProject = useProjectById(activeThread?.projectId); const openPullRequestDialog = useCallback( (reference?: string) => { @@ -595,33 +760,28 @@ export default function ChatView({ threadId }: ChatViewProps) { ); useEffect(() => { - if (!activeThread?.id) return; + if (!serverThread?.id) return; if (!latestTurnSettled) return; if (!activeLatestTurn?.completedAt) return; const turnCompletedAt = Date.parse(activeLatestTurn.completedAt); if (Number.isNaN(turnCompletedAt)) return; - const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN; + const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN; if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return; - markThreadVisited(activeThread.id); + markThreadVisited(serverThread.id); }, [ - activeThread?.id, - activeThread?.lastVisitedAt, activeLatestTurn?.completedAt, + activeThreadLastVisitedAt, latestTurnSettled, markThreadVisited, + serverThread?.id, ]); const sessionProvider = activeThread?.session?.provider ?? null; const selectedProviderByThreadId = composerDraft.activeProvider ?? null; const threadProvider = activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null; - const hasThreadStarted = Boolean( - activeThread && - (activeThread.latestTurn !== null || - activeThread.messages.length > 0 || - activeThread.session !== null), - ); + const hasThreadStarted = threadHasStarted(activeThread); const lockedProvider: ProviderKind | null = hasThreadStarted ? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null) : null; @@ -664,15 +824,6 @@ export default function ChatView({ threadId }: ChatViewProps) { ); const selectedModelForPicker = selectedModel; const phase = derivePhase(activeThread?.session ?? null); - const isSendBusy = sendPhase !== "idle"; - const isPreparingWorktree = sendPhase === "preparing-worktree"; - const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; - const nowIso = new Date(nowTick).toISOString(); - const activeWorkStartedAt = deriveActiveWorkStartedAt( - activeLatestTurn, - activeThread?.session ?? null, - sendStartedAt, - ); const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES; const workLogEntries = useMemo( () => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined), @@ -735,12 +886,12 @@ export default function ChatView({ threadId }: ChatViewProps) { const sidebarProposedPlan = useMemo( () => findSidebarProposedPlan({ - threads, + threads: threadPlanCatalog, latestTurn: activeLatestTurn, latestTurnSettled, threadId: activeThread?.id ?? null, }), - [activeLatestTurn, activeThread?.id, latestTurnSettled, threads], + [activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog], ); const activePlan = useMemo( () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined), @@ -752,6 +903,27 @@ export default function ChatView({ threadId }: ChatViewProps) { latestTurnSettled && hasActionableProposedPlan(activeProposedPlan); const activePendingApproval = pendingApprovals[0] ?? null; + const { + beginLocalDispatch, + resetLocalDispatch, + localDispatchStartedAt, + isPreparingWorktree, + isSendBusy, + } = useLocalDispatchState({ + activeThread, + activeLatestTurn, + phase, + activePendingApproval: activePendingApproval?.requestId ?? null, + activePendingUserInput: activePendingUserInput?.requestId ?? null, + threadError: activeThread?.error, + }); + const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; + const nowIso = new Date(nowTick).toISOString(); + const activeWorkStartedAt = deriveActiveWorkStartedAt( + activeLatestTurn, + activeThread?.session ?? null, + localDispatchStartedAt, + ); const isComposerApprovalState = activePendingApproval !== null; const hasComposerHeader = isComposerApprovalState || @@ -980,35 +1152,9 @@ export default function ChatView({ threadId }: ChatViewProps) { ]); const completionDividerBeforeEntryId = useMemo(() => { if (!latestTurnSettled) return null; - if (!activeLatestTurn?.startedAt) return null; - if (!activeLatestTurn.completedAt) return null; if (!completionSummary) return null; - - const turnStartedAt = Date.parse(activeLatestTurn.startedAt); - const turnCompletedAt = Date.parse(activeLatestTurn.completedAt); - if (Number.isNaN(turnStartedAt)) return null; - if (Number.isNaN(turnCompletedAt)) return null; - - let inRangeMatch: string | null = null; - let fallbackMatch: string | null = null; - for (const timelineEntry of timelineEntries) { - if (timelineEntry.kind !== "message") continue; - if (timelineEntry.message.role !== "assistant") continue; - const messageAt = Date.parse(timelineEntry.message.createdAt); - if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue; - fallbackMatch = timelineEntry.id; - if (messageAt <= turnCompletedAt) { - inRangeMatch = timelineEntry.id; - } - } - return inRangeMatch ?? fallbackMatch; - }, [ - activeLatestTurn?.completedAt, - activeLatestTurn?.startedAt, - completionSummary, - latestTurnSettled, - timelineEntries, - ]); + return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn); + }, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]); const gitCwd = activeProject ? projectScriptCwd({ project: { cwd: activeProject.cwd }, @@ -1230,7 +1376,7 @@ export default function ChatView({ threadId }: ChatViewProps) { const setThreadError = useCallback( (targetThreadId: ThreadId | null, error: string | null) => { if (!targetThreadId) return; - if (threads.some((thread) => thread.id === targetThreadId)) { + if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) { setStoreThreadError(targetThreadId, error); return; } @@ -1244,7 +1390,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }; }); }, - [setStoreThreadError, threads], + [setStoreThreadError], ); const focusComposer = useCallback(() => { @@ -1411,7 +1557,7 @@ export default function ChatView({ threadId }: ChatViewProps) { worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null, ...(options?.env ? { extraEnv: options.env } : {}), }); - const openTerminalInput: Parameters[0] = shouldCreateNewTerminal + const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal ? { threadId: activeThreadId, terminalId: targetTerminalId, @@ -2020,15 +2166,14 @@ export default function ChatView({ threadId }: ChatViewProps) { } return []; }); - setSendPhase("idle"); - setSendStartedAt(null); + resetLocalDispatch(); setComposerHighlightedItemId(null); setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length)); setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length)); dragDepthRef.current = 0; setIsDragOverComposer(false); setExpandedImage(null); - }, [threadId]); + }, [resetLocalDispatch, threadId]); useEffect(() => { let cancelled = false; @@ -2161,37 +2306,6 @@ export default function ChatView({ threadId }: ChatViewProps) { }; }, [phase]); - const beginSendPhase = useCallback((nextPhase: Exclude) => { - setSendStartedAt((current) => current ?? new Date().toISOString()); - setSendPhase(nextPhase); - }, []); - - const resetSendPhase = useCallback(() => { - setSendPhase("idle"); - setSendStartedAt(null); - }, []); - - useEffect(() => { - if (sendPhase === "idle") { - return; - } - if ( - phase === "running" || - activePendingApproval !== null || - activePendingUserInput !== null || - activeThread?.error - ) { - resetSendPhase(); - } - }, [ - activePendingApproval, - activePendingUserInput, - activeThread?.error, - phase, - resetSendPhase, - sendPhase, - ]); - useEffect(() => { if (!activeThreadId) return; const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false; @@ -2529,7 +2643,7 @@ export default function ChatView({ threadId }: ChatViewProps) { } sendInFlightRef.current = true; - beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn"); + beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) }); const composerImagesSnapshot = [...composerImages]; const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts]; @@ -2603,7 +2717,7 @@ export default function ChatView({ threadId }: ChatViewProps) { await (async () => { // On first message: lock in branch + create worktree if needed. if (baseBranchForWorktree) { - beginSendPhase("preparing-worktree"); + beginLocalDispatch({ preparingWorktree: true }); const newBranch = buildTemporaryWorktreeBranchName(); const result = await createWorktreeMutation.mutateAsync({ cwd: activeProject.cwd, @@ -2715,7 +2829,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); } - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); const turnAttachments = await turnAttachmentsPromise; await api.orchestration.dispatchCommand({ type: "thread.turn.start", @@ -2772,7 +2886,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); sendInFlightRef.current = false; if (!turnStartSucceeded) { - resetSendPhase(); + resetLocalDispatch(); } }; @@ -2971,7 +3085,7 @@ export default function ChatView({ threadId }: ChatViewProps) { }); sendInFlightRef.current = true; - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); setThreadError(threadIdForSend, null); setOptimisticUserMessages((existing) => [ ...existing, @@ -3040,19 +3154,19 @@ export default function ChatView({ threadId }: ChatViewProps) { err instanceof Error ? err.message : "Failed to send plan follow-up.", ); sendInFlightRef.current = false; - resetSendPhase(); + resetLocalDispatch(); } }, [ activeThread, activeProposedPlan, - beginSendPhase, + beginLocalDispatch, forceStickToBottom, isConnecting, isSendBusy, isServerThread, persistThreadSettingsForNextTurn, - resetSendPhase, + resetLocalDispatch, runtimeMode, selectedPromptEffort, selectedModelSelection, @@ -3094,10 +3208,10 @@ export default function ChatView({ threadId }: ChatViewProps) { const nextThreadModelSelection: ModelSelection = selectedModelSelection; sendInFlightRef.current = true; - beginSendPhase("sending-turn"); + beginLocalDispatch({ preparingWorktree: false }); const finish = () => { sendInFlightRef.current = false; - resetSendPhase(); + resetLocalDispatch(); }; await api.orchestration @@ -3132,9 +3246,10 @@ export default function ChatView({ threadId }: ChatViewProps) { createdAt, }); }) - .then(() => api.orchestration.getSnapshot()) - .then((snapshot) => { - syncServerReadModel(snapshot); + .then(() => { + return waitForStartedServerThread(nextThreadId); + }) + .then(() => { // Signal that the plan sidebar should open on the new thread. planSidebarOpenOnNextThreadRef.current = true; return navigate({ @@ -3150,12 +3265,6 @@ export default function ChatView({ threadId }: ChatViewProps) { threadId: nextThreadId, }) .catch(() => undefined); - await api.orchestration - .getSnapshot() - .then((snapshot) => { - syncServerReadModel(snapshot); - }) - .catch(() => undefined); toastManager.add({ type: "error", title: "Could not start implementation thread", @@ -3168,18 +3277,17 @@ export default function ChatView({ threadId }: ChatViewProps) { activeProject, activeProposedPlan, activeThread, - beginSendPhase, + beginLocalDispatch, isConnecting, isSendBusy, isServerThread, navigate, - resetSendPhase, + resetLocalDispatch, runtimeMode, selectedPromptEffort, selectedModelSelection, selectedProvider, selectedProviderModels, - syncServerReadModel, selectedModel, ]); diff --git a/apps/web/src/components/KeybindingsToast.browser.tsx b/apps/web/src/components/KeybindingsToast.browser.tsx index ba21af4b77..224bd2f887 100644 --- a/apps/web/src/components/KeybindingsToast.browser.tsx +++ b/apps/web/src/components/KeybindingsToast.browser.tsx @@ -323,7 +323,7 @@ describe("Keybindings update toast", () => { useStore.setState({ projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }); }); diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 232da5bd09..d4cd25db4c 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -9,6 +9,7 @@ import { getProjectSortTimestamp, hasUnseenCompletion, isContextMenuPointerDown, + orderItemsByPreferredIds, resolveProjectStatusIndicator, resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, @@ -18,7 +19,7 @@ import { sortThreadsForSidebar, THREAD_JUMP_HINT_SHOW_DELAY_MS, } from "./Sidebar.logic"; -import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, @@ -29,7 +30,7 @@ import { function makeLatestTurn(overrides?: { completedAt?: string | null; startedAt?: string | null; -}): Parameters[0]["latestTurn"] { +}): OrchestrationLatestTurn { return { turnId: "turn-1" as never, state: "completed", @@ -163,6 +164,50 @@ describe("resolveSidebarNewThreadEnvMode", () => { }); }); +describe("orderItemsByPreferredIds", () => { + it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => { + const ordered = orderItemsByPreferredIds({ + items: [ + { id: ProjectId.makeUnsafe("project-1"), name: "One" }, + { id: ProjectId.makeUnsafe("project-2"), name: "Two" }, + { id: ProjectId.makeUnsafe("project-3"), name: "Three" }, + ], + preferredIds: [ + ProjectId.makeUnsafe("project-3"), + ProjectId.makeUnsafe("project-missing"), + ProjectId.makeUnsafe("project-1"), + ], + getId: (project) => project.id, + }); + + expect(ordered.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-3"), + ProjectId.makeUnsafe("project-1"), + ProjectId.makeUnsafe("project-2"), + ]); + }); + + it("does not duplicate items when preferred ids repeat", () => { + const ordered = orderItemsByPreferredIds({ + items: [ + { id: ProjectId.makeUnsafe("project-1"), name: "One" }, + { id: ProjectId.makeUnsafe("project-2"), name: "Two" }, + ], + preferredIds: [ + ProjectId.makeUnsafe("project-2"), + ProjectId.makeUnsafe("project-1"), + ProjectId.makeUnsafe("project-2"), + ], + getId: (project) => project.id, + }); + + expect(ordered.map((project) => project.id)).toEqual([ + ProjectId.makeUnsafe("project-2"), + ProjectId.makeUnsafe("project-1"), + ]); + }); +}); + describe("resolveAdjacentThreadId", () => { it("resolves adjacent thread ids in ordered sidebar traversal", () => { const threads = [ @@ -552,7 +597,6 @@ function makeProject(overrides: Partial = {}): Project { model: "gpt-5.4", ...defaultModelSelection, }, - expanded: true, createdAt: "2026-03-09T10:00:00.000Z", updatedAt: "2026-03-09T10:00:00.000Z", scripts: [], diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index baf8292117..16c7752f74 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -17,7 +17,10 @@ type SidebarProject = { createdAt?: string | undefined; updatedAt?: string | undefined; }; -type SidebarThreadSortInput = Pick; +type SidebarThreadSortInput = Pick & { + latestUserMessageAt?: string | null; + messages?: Pick[]; +}; export type ThreadTraversalDirection = "previous" | "next"; @@ -45,8 +48,10 @@ const THREAD_STATUS_PRIORITY: Record = { type ThreadStatusInput = Pick< Thread, - "interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session" ->; + "interactionMode" | "latestTurn" | "proposedPlans" | "session" +> & { + lastVisitedAt?: string | undefined; +}; export interface ThreadJumpHintVisibilityController { sync: (shouldShow: boolean) => void; @@ -156,6 +161,34 @@ export function resolveSidebarNewThreadEnvMode(input: { return input.requestedEnvMode ?? input.defaultEnvMode; } +export function orderItemsByPreferredIds(input: { + items: readonly TItem[]; + preferredIds: readonly TId[]; + getId: (item: TItem) => TId; +}): TItem[] { + const { getId, items, preferredIds } = input; + if (preferredIds.length === 0) { + return [...items]; + } + + const itemsById = new Map(items.map((item) => [getId(item), item] as const)); + const preferredIdSet = new Set(preferredIds); + const emittedPreferredIds = new Set(); + const ordered = preferredIds.flatMap((id) => { + if (emittedPreferredIds.has(id)) { + return []; + } + const item = itemsById.get(id); + if (!item) { + return []; + } + emittedPreferredIds.add(id); + return [item]; + }); + const remaining = items.filter((item) => !preferredIdSet.has(getId(item))); + return [...ordered, ...remaining]; +} + export function getVisibleSidebarThreadIds( renderedProjects: readonly { shouldShowThreadPanel?: boolean; @@ -327,15 +360,15 @@ export function resolveProjectStatusIndicator( return highestPriorityStatus; } -export function getVisibleThreadsForProject(input: { - threads: readonly Thread[]; - activeThreadId: Thread["id"] | undefined; +export function getVisibleThreadsForProject>(input: { + threads: readonly T[]; + activeThreadId: T["id"] | undefined; isThreadListExpanded: boolean; previewLimit: number; }): { hasHiddenThreads: boolean; - hiddenThreads: Thread[]; - visibleThreads: Thread[]; + visibleThreads: T[]; + hiddenThreads: T[]; } { const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input; const hasHiddenThreads = threads.length > previewLimit; @@ -382,9 +415,13 @@ function toSortableTimestamp(iso: string | undefined): number | null { } function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number { + if (thread.latestUserMessageAt) { + return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY; + } + let latestUserMessageTimestamp: number | null = null; - for (const message of thread.messages) { + for (const message of thread.messages ?? []) { if (message.role !== "user") continue; const messageTimestamp = toSortableTimestamp(message.createdAt); if (messageTimestamp === null) continue; @@ -412,7 +449,7 @@ function getThreadSortTimestamp( } export function sortThreadsForSidebar< - T extends Pick, + T extends Pick & SidebarThreadSortInput, >(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] { return threads.toSorted((left, right) => { const rightTimestamp = getThreadSortTimestamp(right, sortOrder); @@ -425,7 +462,7 @@ export function sortThreadsForSidebar< } export function getFallbackThreadIdAfterDelete< - T extends Pick, + T extends Pick & SidebarThreadSortInput, >(input: { threads: readonly T[]; deletedThreadId: T["id"]; @@ -469,7 +506,10 @@ export function getProjectSortTimestamp( return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY; } -export function sortProjectsForSidebar( +export function sortProjectsForSidebar< + TProject extends SidebarProject, + TThread extends Pick & SidebarThreadSortInput, +>( projects: readonly TProject[], threads: readonly TThread[], sortOrder: SidebarProjectSortOrder, diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 207082477d..efa5124288 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -21,6 +21,7 @@ import { type MouseEvent, type PointerEvent, } from "react"; +import { useShallow } from "zustand/react/shallow"; import { DndContext, type DragCancelEvent, @@ -55,6 +56,7 @@ import { APP_STAGE_LABEL, APP_VERSION } from "../branding"; import { isTerminalFocused } from "../lib/terminalFocus"; import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils"; import { useStore } from "../store"; +import { useUiStateStore } from "../uiStateStore"; import { resolveShortcutCommand, shortcutLabelForCommand, @@ -114,6 +116,7 @@ import { resolveSidebarNewThreadEnvMode, resolveThreadRowClassName, resolveThreadStatusPill, + orderItemsByPreferredIds, shouldClearThreadSelectionOnMouseDown, sortProjectsForSidebar, sortThreadsForSidebar, @@ -122,6 +125,7 @@ import { import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill"; import { useCopyToClipboard } from "~/hooks/useCopyToClipboard"; import { useSettings, useUpdateSettings } from "~/hooks/useSettings"; +import type { Project, Thread } from "../types"; const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; const THREAD_PREVIEW_LIMIT = 6; @@ -138,6 +142,80 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = { duration: 180, easing: "ease-out", } as const; + +type SidebarThreadSnapshot = Pick< + Thread, + | "activities" + | "archivedAt" + | "branch" + | "createdAt" + | "id" + | "interactionMode" + | "latestTurn" + | "projectId" + | "proposedPlans" + | "session" + | "title" + | "updatedAt" + | "worktreePath" +> & { + lastVisitedAt?: string | undefined; + latestUserMessageAt: string | null; +}; + +type SidebarProjectSnapshot = Project & { + expanded: boolean; +}; + +const sidebarThreadSnapshotCache = new WeakMap< + Thread, + { lastVisitedAt?: string | undefined; snapshot: SidebarThreadSnapshot } +>(); + +function getLatestUserMessageAt(thread: Thread): string | null { + let latestUserMessageAt: string | null = null; + + for (const message of thread.messages) { + if (message.role !== "user") { + continue; + } + if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) { + latestUserMessageAt = message.createdAt; + } + } + + return latestUserMessageAt; +} + +function toSidebarThreadSnapshot( + thread: Thread, + lastVisitedAt: string | undefined, +): SidebarThreadSnapshot { + const cached = sidebarThreadSnapshotCache.get(thread); + if (cached && cached.lastVisitedAt === lastVisitedAt) { + return cached.snapshot; + } + + const snapshot: SidebarThreadSnapshot = { + id: thread.id, + projectId: thread.projectId, + title: thread.title, + interactionMode: thread.interactionMode, + session: thread.session, + createdAt: thread.createdAt, + updatedAt: thread.updatedAt, + archivedAt: thread.archivedAt, + latestTurn: thread.latestTurn, + lastVisitedAt, + branch: thread.branch, + worktreePath: thread.worktreePath, + activities: thread.activities, + proposedPlans: thread.proposedPlans, + latestUserMessageAt: getLatestUserMessageAt(thread), + }; + sidebarThreadSnapshotCache.set(thread, { lastVisitedAt, snapshot }); + return snapshot; +} interface TerminalStatusIndicator { label: "Terminal process running"; colorClass: string; @@ -361,10 +439,17 @@ function SortableProjectItem({ export default function Sidebar() { const projects = useStore((store) => store.projects); - const threads = useStore((store) => store.threads); - const markThreadUnread = useStore((store) => store.markThreadUnread); - const toggleProject = useStore((store) => store.toggleProject); - const reorderProjects = useStore((store) => store.reorderProjects); + const serverThreads = useStore((store) => store.threads); + const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore( + useShallow((store) => ({ + projectExpandedById: store.projectExpandedById, + projectOrder: store.projectOrder, + threadLastVisitedAtById: store.threadLastVisitedAtById, + })), + ); + const markThreadUnread = useUiStateStore((store) => store.markThreadUnread); + const toggleProject = useUiStateStore((store) => store.toggleProject); + const reorderProjects = useUiStateStore((store) => store.reorderProjects); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const getDraftThreadByProjectId = useComposerDraftStore( (store) => store.getDraftThreadByProjectId, @@ -418,6 +503,28 @@ export default function Sidebar() { const platform = navigator.platform; const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop; const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately; + const orderedProjects = useMemo(() => { + return orderItemsByPreferredIds({ + items: projects, + preferredIds: projectOrder, + getId: (project) => project.id, + }); + }, [projectOrder, projects]); + const sidebarProjects = useMemo( + () => + orderedProjects.map((project) => ({ + ...project, + expanded: projectExpandedById[project.id] ?? true, + })), + [orderedProjects, projectExpandedById], + ); + const threads = useMemo( + () => + serverThreads.map((thread) => + toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]), + ), + [serverThreads, threadLastVisitedAtById], + ); const projectCwdById = useMemo( () => new Map(projects.map((project) => [project.id, project.cwd] as const)), [projects], @@ -752,7 +859,7 @@ export default function Sidebar() { } if (clicked === "mark-unread") { - markThreadUnread(threadId); + markThreadUnread(threadId, thread.latestTurn?.completedAt); return; } if (clicked === "copy-path") { @@ -814,7 +921,8 @@ export default function Sidebar() { if (clicked === "mark-unread") { for (const id of ids) { - markThreadUnread(id); + const thread = threads.find((candidate) => candidate.id === id); + markThreadUnread(id, thread?.latestTurn?.completedAt); } clearSelection(); return; @@ -845,6 +953,7 @@ export default function Sidebar() { markThreadUnread, removeFromSelection, selectedThreadIds, + threads, ], ); @@ -987,12 +1096,12 @@ export default function Sidebar() { dragInProgressRef.current = false; const { active, over } = event; if (!over || active.id === over.id) return; - const activeProject = projects.find((project) => project.id === active.id); - const overProject = projects.find((project) => project.id === over.id); + const activeProject = sidebarProjects.find((project) => project.id === active.id); + const overProject = sidebarProjects.find((project) => project.id === over.id); if (!activeProject || !overProject) return; reorderProjects(activeProject.id, overProject.id); }, - [appSettings.sidebarProjectSortOrder, projects, reorderProjects], + [appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects], ); const handleProjectDragStart = useCallback( @@ -1052,8 +1161,9 @@ export default function Sidebar() { [threads], ); const sortedProjects = useMemo( - () => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder), - [appSettings.sidebarProjectSortOrder, projects, visibleThreads], + () => + sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder), + [appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads], ); const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual"; const renderedProjects = useMemo( diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.ts index b68663a890..797e27a6ed 100644 --- a/apps/web/src/composerDraftStore.test.ts +++ b/apps/web/src/composerDraftStore.test.ts @@ -9,6 +9,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { COMPOSER_DRAFT_STORAGE_KEY, + clearPromotedDraftThread, + clearPromotedDraftThreads, type ComposerImageAttachment, useComposerDraftStore, } from "./composerDraftStore"; @@ -549,6 +551,57 @@ describe("composerDraftStore project draft thread mapping", () => { expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined(); }); + it("clears a promoted draft by thread id", () => { + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectId, threadId); + store.setPrompt(threadId, "promote me"); + + clearPromotedDraftThread(threadId); + + expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull(); + expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull(); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined(); + }); + + it("does not clear composer drafts for existing server threads during promotion cleanup", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(threadId, "keep me"); + + clearPromotedDraftThread(threadId); + + expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull(); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me"); + }); + + it("clears promoted drafts from an iterable of server thread ids", () => { + const store = useComposerDraftStore.getState(); + store.setProjectDraftThreadId(projectId, threadId); + store.setPrompt(threadId, "promote me"); + store.setProjectDraftThreadId(otherProjectId, otherThreadId); + store.setPrompt(otherThreadId, "keep me"); + + clearPromotedDraftThreads([threadId]); + + expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull(); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined(); + expect( + useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId, + ).toBe(otherThreadId); + expect(useComposerDraftStore.getState().draftsByThreadId[otherThreadId]?.prompt).toBe( + "keep me", + ); + }); + + it("keeps existing server-thread composer drafts during iterable promotion cleanup", () => { + const store = useComposerDraftStore.getState(); + store.setPrompt(threadId, "keep me"); + + clearPromotedDraftThreads([threadId]); + + expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull(); + expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me"); + }); + it("updates branch context on an existing draft thread", () => { const store = useComposerDraftStore.getState(); store.setProjectDraftThreadId(projectId, threadId, { diff --git a/apps/web/src/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 17b06e7bd1..8a93b7b0da 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -2195,18 +2195,21 @@ export function useEffectiveComposerModelState(input: { } /** - * Clear draft threads that have been promoted to server threads. + * Clear a draft thread once the server has materialized the same thread id. * - * Call this after a snapshot sync so the route guard in `_chat.$threadId` - * sees the server thread before the draft is removed — avoids a redirect - * to `/` caused by a gap where neither draft nor server thread exists. + * Use the single-thread helper for live `thread.created` events and the + * iterable helper for bootstrap/recovery paths that discover multiple server + * threads at once. */ -export function clearPromotedDraftThreads(serverThreadIds: ReadonlySet): void { - const store = useComposerDraftStore.getState(); - const draftThreadIds = Object.keys(store.draftThreadsByThreadId) as ThreadId[]; - for (const draftId of draftThreadIds) { - if (serverThreadIds.has(draftId)) { - store.clearDraftThread(draftId); - } +export function clearPromotedDraftThread(threadId: ThreadId): void { + if (!useComposerDraftStore.getState().getDraftThread(threadId)) { + return; + } + useComposerDraftStore.getState().clearDraftThread(threadId); +} + +export function clearPromotedDraftThreads(serverThreadIds: Iterable): void { + for (const threadId of serverThreadIds) { + clearPromotedDraftThread(threadId); } } diff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.ts index ffb4b5cf67..1547035bf4 100644 --- a/apps/web/src/hooks/useHandleNewThread.ts +++ b/apps/web/src/hooks/useHandleNewThread.ts @@ -1,29 +1,37 @@ import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts"; import { useNavigate, useParams } from "@tanstack/react-router"; -import { useCallback } from "react"; +import { useCallback, useMemo } from "react"; +import { useShallow } from "zustand/react/shallow"; import { type DraftThreadEnvMode, type DraftThreadState, useComposerDraftStore, } from "../composerDraftStore"; import { newThreadId } from "../lib/utils"; +import { orderItemsByPreferredIds } from "../components/Sidebar.logic"; import { useStore } from "../store"; +import { useThreadById } from "../storeSelectors"; +import { useUiStateStore } from "../uiStateStore"; export function useHandleNewThread() { - const projects = useStore((store) => store.projects); - const threads = useStore((store) => store.threads); + const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id))); + const projectOrder = useUiStateStore((store) => store.projectOrder); const navigate = useNavigate(); const routeThreadId = useParams({ strict: false, select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null), }); + const activeThread = useThreadById(routeThreadId); const activeDraftThread = useComposerDraftStore((store) => routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null, ); - - const activeThread = routeThreadId - ? threads.find((thread) => thread.id === routeThreadId) - : undefined; + const orderedProjects = useMemo(() => { + return orderItemsByPreferredIds({ + items: projectIds, + preferredIds: projectOrder, + getId: (projectId) => projectId, + }); + }, [projectIds, projectOrder]); const handleNewThread = useCallback( ( @@ -111,8 +119,8 @@ export function useHandleNewThread() { return { activeDraftThread, activeThread, + defaultProjectId: orderedProjects[0] ?? null, handleNewThread, - projects, routeThreadId, }; } diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 83cfe911fc..d5557b4a96 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -16,8 +16,6 @@ import { toastManager } from "../components/ui/toast"; import { useSettings } from "./useSettings"; export function useThreadActions() { - const threads = useStore((store) => store.threads); - const projects = useStore((store) => store.projects); const appSettings = useSettings(); const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread); const clearProjectDraftThreadById = useComposerDraftStore( @@ -37,7 +35,7 @@ export function useThreadActions() { async (threadId: ThreadId) => { const api = readNativeApi(); if (!api) return; - const thread = threads.find((entry) => entry.id === threadId); + const thread = useStore.getState().threads.find((entry) => entry.id === threadId); if (!thread) return; if (thread.session?.status === "running" && thread.session.activeTurnId != null) { throw new Error("Cannot archive a running thread."); @@ -53,7 +51,7 @@ export function useThreadActions() { await handleNewThread(thread.projectId); } }, - [handleNewThread, routeThreadId, threads], + [handleNewThread, routeThreadId], ); const unarchiveThread = useCallback(async (threadId: ThreadId) => { @@ -70,6 +68,7 @@ export function useThreadActions() { async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet } = {}) => { const api = readNativeApi(); if (!api) return; + const { projects, threads } = useStore.getState(); const thread = threads.find((entry) => entry.id === threadId); if (!thread) return; const threadProject = projects.find((project) => project.id === thread.projectId); @@ -171,10 +170,8 @@ export function useThreadActions() { clearTerminalState, appSettings.sidebarThreadSortOrder, navigate, - projects, removeWorktreeMutation, routeThreadId, - threads, ], ); @@ -182,7 +179,7 @@ export function useThreadActions() { async (threadId: ThreadId) => { const api = readNativeApi(); if (!api) return; - const thread = threads.find((entry) => entry.id === threadId); + const thread = useStore.getState().threads.find((entry) => entry.id === threadId); if (!thread) return; if (appSettings.confirmThreadDelete) { @@ -199,7 +196,7 @@ export function useThreadActions() { await deleteThread(threadId); }, - [appSettings.confirmThreadDelete, deleteThread, threads], + [appSettings.confirmThreadDelete, deleteThread], ); return { diff --git a/apps/web/src/orchestrationEventEffects.test.ts b/apps/web/src/orchestrationEventEffects.test.ts new file mode 100644 index 0000000000..263610bb95 --- /dev/null +++ b/apps/web/src/orchestrationEventEffects.test.ts @@ -0,0 +1,108 @@ +import { + CheckpointRef, + EventId, + MessageId, + ProjectId, + ThreadId, + TurnId, + type OrchestrationEvent, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; + +import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects"; + +function makeEvent( + type: T, + payload: Extract["payload"], + overrides: Partial> = {}, +): Extract { + const sequence = overrides.sequence ?? 1; + return { + sequence, + eventId: EventId.makeUnsafe(`event-${sequence}`), + aggregateKind: "thread", + aggregateId: + "threadId" in payload + ? payload.threadId + : "projectId" in payload + ? payload.projectId + : ProjectId.makeUnsafe("project-1"), + occurredAt: "2026-02-27T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type, + payload, + ...overrides, + } as Extract; +} + +describe("deriveOrchestrationBatchEffects", () => { + it("targets draft promotion and terminal cleanup from thread lifecycle events", () => { + const createdThreadId = ThreadId.makeUnsafe("thread-created"); + const deletedThreadId = ThreadId.makeUnsafe("thread-deleted"); + + const effects = deriveOrchestrationBatchEffects([ + makeEvent("thread.created", { + threadId: createdThreadId, + projectId: ProjectId.makeUnsafe("project-1"), + title: "Created thread", + modelSelection: { provider: "codex", model: "gpt-5-codex" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-02-27T00:00:00.000Z", + updatedAt: "2026-02-27T00:00:00.000Z", + }), + makeEvent("thread.deleted", { + threadId: deletedThreadId, + deletedAt: "2026-02-27T00:00:01.000Z", + }), + ]); + + expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]); + expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]); + expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]); + expect(effects.needsProviderInvalidation).toBe(false); + }); + + it("keeps only the final lifecycle outcome for a thread within one batch", () => { + const threadId = ThreadId.makeUnsafe("thread-1"); + + const effects = deriveOrchestrationBatchEffects([ + makeEvent("thread.deleted", { + threadId, + deletedAt: "2026-02-27T00:00:01.000Z", + }), + makeEvent("thread.created", { + threadId, + projectId: ProjectId.makeUnsafe("project-1"), + title: "Recreated thread", + modelSelection: { provider: "codex", model: "gpt-5-codex" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-02-27T00:00:02.000Z", + updatedAt: "2026-02-27T00:00:02.000Z", + }), + makeEvent("thread.turn-diff-completed", { + threadId, + turnId: TurnId.makeUnsafe("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-1"), + completedAt: "2026-02-27T00:00:03.000Z", + }), + ]); + + expect(effects.clearPromotedDraftThreadIds).toEqual([threadId]); + expect(effects.clearDeletedThreadIds).toEqual([]); + expect(effects.removeTerminalStateThreadIds).toEqual([]); + expect(effects.needsProviderInvalidation).toBe(true); + }); +}); diff --git a/apps/web/src/orchestrationEventEffects.ts b/apps/web/src/orchestrationEventEffects.ts new file mode 100644 index 0000000000..d4dda76d9e --- /dev/null +++ b/apps/web/src/orchestrationEventEffects.ts @@ -0,0 +1,76 @@ +import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts"; + +export interface OrchestrationBatchEffects { + clearPromotedDraftThreadIds: ThreadId[]; + clearDeletedThreadIds: ThreadId[]; + removeTerminalStateThreadIds: ThreadId[]; + needsProviderInvalidation: boolean; +} + +export function deriveOrchestrationBatchEffects( + events: readonly OrchestrationEvent[], +): OrchestrationBatchEffects { + const threadLifecycleEffects = new Map< + ThreadId, + { + clearPromotedDraft: boolean; + clearDeletedThread: boolean; + removeTerminalState: 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, + removeTerminalState: false, + }); + break; + } + + case "thread.deleted": { + threadLifecycleEffects.set(event.payload.threadId, { + clearPromotedDraft: false, + clearDeletedThread: true, + removeTerminalState: true, + }); + break; + } + + default: { + break; + } + } + } + + const clearPromotedDraftThreadIds: ThreadId[] = []; + const clearDeletedThreadIds: ThreadId[] = []; + const removeTerminalStateThreadIds: ThreadId[] = []; + for (const [threadId, effect] of threadLifecycleEffects) { + if (effect.clearPromotedDraft) { + clearPromotedDraftThreadIds.push(threadId); + } + if (effect.clearDeletedThread) { + clearDeletedThreadIds.push(threadId); + } + if (effect.removeTerminalState) { + removeTerminalStateThreadIds.push(threadId); + } + } + + return { + clearPromotedDraftThreadIds, + clearDeletedThreadIds, + removeTerminalStateThreadIds, + needsProviderInvalidation, + }; +} diff --git a/apps/web/src/orchestrationRecovery.test.ts b/apps/web/src/orchestrationRecovery.test.ts new file mode 100644 index 0000000000..bea16cdbce --- /dev/null +++ b/apps/web/src/orchestrationRecovery.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from "vitest"; + +import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery"; + +describe("createOrchestrationRecoveryCoordinator", () => { + it("defers live events until bootstrap completes and then requests replay", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true); + expect(coordinator.classifyDomainEvent(4)).toBe("defer"); + + expect(coordinator.completeSnapshotRecovery(2)).toBe(true); + expect(coordinator.getState()).toMatchObject({ + latestSequence: 2, + highestObservedSequence: 4, + bootstrapped: true, + pendingReplay: false, + inFlight: null, + }); + }); + + it("classifies sequence gaps as recovery-only replay work", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + + expect(coordinator.classifyDomainEvent(5)).toBe("recover"); + expect(coordinator.beginReplayRecovery("sequence-gap")).toBe(true); + expect(coordinator.getState().inFlight).toEqual({ + kind: "replay", + reason: "sequence-gap", + }); + }); + + it("tracks live event batches without entering recovery", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + + expect(coordinator.classifyDomainEvent(4)).toBe("apply"); + expect(coordinator.markEventBatchApplied([{ sequence: 4 }])).toEqual([{ sequence: 4 }]); + expect(coordinator.getState()).toMatchObject({ + latestSequence: 4, + highestObservedSequence: 4, + bootstrapped: true, + inFlight: null, + }); + }); + + it("requests another replay when deferred events arrive during replay recovery", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + coordinator.classifyDomainEvent(5); + coordinator.beginReplayRecovery("sequence-gap"); + coordinator.classifyDomainEvent(7); + coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]); + + expect(coordinator.completeReplayRecovery()).toBe(true); + }); + + it("does not immediately replay again when replay returns no new events", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + coordinator.classifyDomainEvent(5); + coordinator.beginReplayRecovery("sequence-gap"); + + expect(coordinator.completeReplayRecovery()).toBe(false); + expect(coordinator.getState()).toMatchObject({ + latestSequence: 3, + highestObservedSequence: 5, + pendingReplay: false, + inFlight: null, + }); + }); + + it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => { + const coordinator = createOrchestrationRecoveryCoordinator(); + + coordinator.beginSnapshotRecovery("bootstrap"); + coordinator.completeSnapshotRecovery(3); + coordinator.beginReplayRecovery("sequence-gap"); + coordinator.failReplayRecovery(); + + expect(coordinator.getState()).toMatchObject({ + bootstrapped: false, + inFlight: null, + }); + expect(coordinator.beginSnapshotRecovery("replay-failed")).toBe(true); + expect(coordinator.getState().inFlight).toEqual({ + kind: "snapshot", + reason: "replay-failed", + }); + }); +}); diff --git a/apps/web/src/orchestrationRecovery.ts b/apps/web/src/orchestrationRecovery.ts new file mode 100644 index 0000000000..ee81d5d539 --- /dev/null +++ b/apps/web/src/orchestrationRecovery.ts @@ -0,0 +1,136 @@ +export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed"; + +export interface OrchestrationRecoveryPhase { + kind: "snapshot" | "replay"; + reason: OrchestrationRecoveryReason; +} + +export interface OrchestrationRecoveryState { + latestSequence: number; + highestObservedSequence: number; + bootstrapped: boolean; + pendingReplay: boolean; + inFlight: OrchestrationRecoveryPhase | null; +} + +type SequencedEvent = Readonly<{ sequence: number }>; + +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 shouldReplayAfterRecovery = (): boolean => { + const shouldReplay = + state.pendingReplay || state.highestObservedSequence > state.latestSequence; + state.pendingReplay = false; + return shouldReplay; + }; + + 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(events: ReadonlyArray): ReadonlyArray { + 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 shouldReplayAfterRecovery(); + }, + + 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(): boolean { + const replayMadeProgress = + replayStartSequence !== null && state.latestSequence > replayStartSequence; + replayStartSequence = null; + state.inFlight = null; + if (!replayMadeProgress) { + state.pendingReplay = false; + return false; + } + return shouldReplayAfterRecovery(); + }, + + failReplayRecovery(): void { + replayStartSequence = null; + state.bootstrapped = false; + state.inFlight = null; + }, + }; +} diff --git a/apps/web/src/router.ts b/apps/web/src/router.ts index 0192ee0c6c..16b78e69dc 100644 --- a/apps/web/src/router.ts +++ b/apps/web/src/router.ts @@ -1,11 +1,8 @@ import { createElement } from "react"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { createRouter } from "@tanstack/react-router"; +import { createRouter, RouterHistory } from "@tanstack/react-router"; import { routeTree } from "./routeTree.gen"; -import { StoreProvider } from "./store"; - -type RouterHistory = NonNullable[0]["history"]>; export function getRouter(history: RouterHistory) { const queryClient = new QueryClient(); @@ -16,12 +13,7 @@ export function getRouter(history: RouterHistory) { context: { queryClient, }, - Wrap: ({ children }) => - createElement( - QueryClientProvider, - { client: queryClient }, - createElement(StoreProvider, null, children), - ), + Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children), }); } diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index e99ec50226..4765b0a8e6 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -1,4 +1,4 @@ -import { ThreadId } from "@t3tools/contracts"; +import { OrchestrationEvent, ThreadId } from "@t3tools/contracts"; import { Outlet, createRootRouteWithContext, @@ -17,8 +17,13 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component import { resolveAndPersistPreferredEditor } from "../editorPreferences"; import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery"; import { readNativeApi } from "../nativeApi"; -import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore"; +import { + clearPromotedDraftThread, + clearPromotedDraftThreads, + useComposerDraftStore, +} from "../composerDraftStore"; import { useStore } from "../store"; +import { useUiStateStore } from "../uiStateStore"; import { useTerminalStateStore } from "../terminalStateStore"; import { terminalRunningSubprocessFromEvent } from "../terminalActivity"; import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi"; @@ -26,6 +31,8 @@ import { migrateLocalSettingsToServer } from "../hooks/useSettings"; import { providerQueryKeys } from "../lib/providerReactQuery"; import { projectQueryKeys } from "../lib/projectReactQuery"; import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup"; +import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects"; +import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery"; export const Route = createRootRouteWithContext<{ queryClient: QueryClient; @@ -135,8 +142,13 @@ function errorDetails(error: unknown): string { } function EventRouter() { + const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents); const syncServerReadModel = useStore((store) => store.syncServerReadModel); - const setProjectExpanded = useStore((store) => store.setProjectExpanded); + const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded); + const syncProjects = useUiStateStore((store) => store.syncProjects); + const syncThreads = useUiStateStore((store) => store.syncThreads); + const clearThreadUi = useUiStateStore((store) => store.clearThreadUi); + const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState); const removeOrphanedTerminalStates = useTerminalStateStore( (store) => store.removeOrphanedTerminalStates, ); @@ -152,56 +164,40 @@ function EventRouter() { const api = readNativeApi(); if (!api) return; let disposed = false; - let latestSequence = 0; - let syncing = false; - let pending = false; + const recovery = createOrchestrationRecoveryCoordinator(); let needsProviderInvalidation = false; - const flushSnapshotSync = async (): Promise => { - const snapshot = await api.orchestration.getSnapshot(); - if (disposed) return; - latestSequence = Math.max(latestSequence, snapshot.snapshotSequence); - syncServerReadModel(snapshot); - clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id))); + const reconcileSnapshotDerivedState = () => { + const threads = useStore.getState().threads; + const projects = useStore.getState().projects; + syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd }))); + syncThreads( + threads.map((thread) => ({ + id: thread.id, + seedVisitedAt: thread.updatedAt ?? thread.createdAt, + })), + ); + clearPromotedDraftThreads(threads.map((thread) => thread.id)); const draftThreadIds = Object.keys( useComposerDraftStore.getState().draftThreadsByThreadId, ) as ThreadId[]; const activeThreadIds = collectActiveTerminalThreadIds({ - snapshotThreads: snapshot.threads, + snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })), draftThreadIds, }); removeOrphanedTerminalStates(activeThreadIds); - if (pending) { - pending = false; - await flushSnapshotSync(); - } }; - const syncSnapshot = async () => { - if (syncing) { - pending = true; - return; - } - syncing = true; - pending = false; - try { - await flushSnapshotSync(); - } catch { - // Keep prior state and wait for next domain event to trigger a resync. - } - syncing = false; - }; - - const domainEventFlushThrottler = new Throttler( + const queryInvalidationThrottler = new Throttler( () => { - if (needsProviderInvalidation) { - needsProviderInvalidation = false; - void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all }); - // Invalidate workspace entry queries so the @-mention file picker - // reflects files created, deleted, or restored during this turn. - void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all }); + if (!needsProviderInvalidation) { + return; } - void syncSnapshot(); + needsProviderInvalidation = false; + void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all }); + // Invalidate workspace entry queries so the @-mention file picker + // reflects files created, deleted, or restored during this turn. + void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all }); }, { wait: 100, @@ -210,15 +206,113 @@ function EventRouter() { }, ); - const unsubDomainEvent = api.orchestration.onDomainEvent((event) => { - if (event.sequence <= latestSequence) { + const applyEventBatch = (events: ReadonlyArray) => { + const nextEvents = recovery.markEventBatchApplied(events); + if (nextEvents.length === 0) { return; } - latestSequence = event.sequence; - if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") { + + const batchEffects = deriveOrchestrationBatchEffects(nextEvents); + const needsProjectUiSync = nextEvents.some( + (event) => + event.type === "project.created" || + event.type === "project.meta-updated" || + event.type === "project.deleted", + ); + + if (batchEffects.needsProviderInvalidation) { needsProviderInvalidation = true; + void queryInvalidationThrottler.maybeExecute(); + } + + applyOrchestrationEvents(nextEvents); + if (needsProjectUiSync) { + const projects = useStore.getState().projects; + syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd }))); + } + const needsThreadUiSync = nextEvents.some( + (event) => event.type === "thread.created" || event.type === "thread.deleted", + ); + if (needsThreadUiSync) { + const threads = useStore.getState().threads; + syncThreads( + threads.map((thread) => ({ + id: thread.id, + seedVisitedAt: thread.updatedAt ?? thread.createdAt, + })), + ); + } + const draftStore = useComposerDraftStore.getState(); + for (const threadId of batchEffects.clearPromotedDraftThreadIds) { + clearPromotedDraftThread(threadId); + } + for (const threadId of batchEffects.clearDeletedThreadIds) { + draftStore.clearDraftThread(threadId); + clearThreadUi(threadId); + } + for (const threadId of batchEffects.removeTerminalStateThreadIds) { + removeTerminalState(threadId); + } + }; + + const recoverFromSequenceGap = async (): Promise => { + if (!recovery.beginReplayRecovery("sequence-gap")) { + return; + } + + try { + const events = await api.orchestration.replayEvents(recovery.getState().latestSequence); + if (!disposed) { + applyEventBatch(events); + } + } catch { + recovery.failReplayRecovery(); + void fallbackToSnapshotRecovery(); + return; + } + + if (!disposed && recovery.completeReplayRecovery()) { + void recoverFromSequenceGap(); + } + }; + + const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise => { + if (!recovery.beginSnapshotRecovery(reason)) { + return; + } + + try { + const snapshot = await api.orchestration.getSnapshot(); + if (!disposed) { + syncServerReadModel(snapshot); + reconcileSnapshotDerivedState(); + if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) { + void recoverFromSequenceGap(); + } + } + } catch { + // Keep prior state and wait for welcome or a later replay attempt. + recovery.failSnapshotRecovery(); + } + }; + + const bootstrapFromSnapshot = async (): Promise => { + await runSnapshotRecovery("bootstrap"); + }; + + const fallbackToSnapshotRecovery = async (): Promise => { + await runSnapshotRecovery("replay-failed"); + }; + + const unsubDomainEvent = api.orchestration.onDomainEvent((event) => { + const action = recovery.classifyDomainEvent(event.sequence); + if (action === "apply") { + applyEventBatch([event]); + return; + } + if (action === "recover") { + void recoverFromSequenceGap(); } - domainEventFlushThrottler.maybeExecute(); }); const unsubTerminalEvent = api.terminal.onEvent((event) => { const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event); @@ -237,7 +331,7 @@ function EventRouter() { // Migrate old localStorage settings to server on first connect migrateLocalSettingsToServer(); void (async () => { - await syncSnapshot(); + await bootstrapFromSnapshot(); if (disposed) { return; } @@ -319,7 +413,7 @@ function EventRouter() { return () => { disposed = true; needsProviderInvalidation = false; - domainEventFlushThrottler.cancel(); + queryInvalidationThrottler.cancel(); unsubDomainEvent(); unsubTerminalEvent(); unsubWelcome(); @@ -327,11 +421,16 @@ function EventRouter() { unsubProvidersUpdated(); }; }, [ + applyOrchestrationEvents, navigate, queryClient, + removeTerminalState, removeOrphanedTerminalStates, + clearThreadUi, setProjectExpanded, + syncProjects, syncServerReadModel, + syncThreads, ]); return null; diff --git a/apps/web/src/routes/_chat.$threadId.tsx b/apps/web/src/routes/_chat.$threadId.tsx index 8e7a5d3ba8..b95d1ef7b0 100644 --- a/apps/web/src/routes/_chat.$threadId.tsx +++ b/apps/web/src/routes/_chat.$threadId.tsx @@ -161,7 +161,7 @@ const DiffPanelInlineSidebar = (props: { }; function ChatThreadRouteView() { - const threadsHydrated = useStore((store) => store.threadsHydrated); + const bootstrapComplete = useStore((store) => store.bootstrapComplete); const navigate = useNavigate(); const threadId = Route.useParams({ select: (params) => ThreadId.makeUnsafe(params.threadId), @@ -202,7 +202,7 @@ function ChatThreadRouteView() { }, [diffOpen]); useEffect(() => { - if (!threadsHydrated) { + if (!bootstrapComplete) { return; } @@ -210,9 +210,9 @@ function ChatThreadRouteView() { void navigate({ to: "/", replace: true }); return; } - }, [navigate, routeThreadExists, threadsHydrated, threadId]); + }, [bootstrapComplete, navigate, routeThreadExists, threadId]); - if (!threadsHydrated || !routeThreadExists) { + if (!bootstrapComplete || !routeThreadExists) { return null; } diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsx index 3c86ab42f3..245ed9c576 100644 --- a/apps/web/src/routes/_chat.tsx +++ b/apps/web/src/routes/_chat.tsx @@ -17,7 +17,7 @@ const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = []; function ChatRouteGlobalShortcuts() { const clearSelection = useThreadSelectionStore((state) => state.clearSelection); const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size); - const { activeDraftThread, activeThread, handleNewThread, projects, routeThreadId } = + const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } = useHandleNewThread(); const serverConfigQuery = useQuery(serverConfigQueryOptions()); const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS; @@ -38,7 +38,7 @@ function ChatRouteGlobalShortcuts() { return; } - const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id; + const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId; if (!projectId) return; const command = resolveShortcutCommand(event, keybindings, { @@ -59,14 +59,17 @@ function ChatRouteGlobalShortcuts() { return; } - if (command !== "chat.new") return; - event.preventDefault(); - event.stopPropagation(); - void handleNewThread(projectId, { - branch: activeThread?.branch ?? activeDraftThread?.branch ?? null, - worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null, - envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"), - }); + if (command === "chat.new") { + event.preventDefault(); + event.stopPropagation(); + void handleNewThread(projectId, { + branch: activeThread?.branch ?? activeDraftThread?.branch ?? null, + worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null, + envMode: + activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"), + }); + return; + } }; window.addEventListener("keydown", onWindowKeyDown); @@ -79,7 +82,7 @@ function ChatRouteGlobalShortcuts() { clearSelection, handleNewThread, keybindings, - projects, + defaultProjectId, selectedThreadIdsSize, terminalOpen, appSettings.defaultThreadEnvMode, diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index c786ffc72b..e05c3b5e93 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -8,6 +8,7 @@ import { import { describe, expect, it } from "vitest"; import { + deriveCompletionDividerBeforeEntryId, deriveActiveWorkStartedAt, deriveActivePlanState, PROVIDER_OPTIONS, @@ -964,6 +965,37 @@ describe("deriveTimelineEntries", () => { }, }); }); + + it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => { + const entries = deriveTimelineEntries( + [ + { + id: MessageId.makeUnsafe("assistant-earlier"), + role: "assistant", + text: "progress update", + createdAt: "2026-02-23T00:00:01.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("assistant-final"), + role: "assistant", + text: "final answer", + createdAt: "2026-02-23T00:00:01.000Z", + streaming: false, + }, + ], + [], + [], + ); + + expect( + deriveCompletionDividerBeforeEntryId(entries, { + assistantMessageId: MessageId.makeUnsafe("assistant-final"), + startedAt: "2026-02-23T00:00:00.000Z", + completedAt: "2026-02-23T00:00:02.000Z", + }), + ).toBe("assistant-final"); + }); }); describe("deriveWorkLogEntries context window handling", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 83a95d6313..fc33827014 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -852,6 +852,53 @@ export function deriveTimelineEntries( ); } +export function deriveCompletionDividerBeforeEntryId( + timelineEntries: ReadonlyArray, + latestTurn: Pick< + OrchestrationLatestTurn, + "assistantMessageId" | "startedAt" | "completedAt" + > | null, +): string | null { + if (!latestTurn?.startedAt || !latestTurn.completedAt) { + return null; + } + + if (latestTurn.assistantMessageId) { + const exactMatch = timelineEntries.find( + (timelineEntry) => + timelineEntry.kind === "message" && + timelineEntry.message.role === "assistant" && + timelineEntry.message.id === latestTurn.assistantMessageId, + ); + if (exactMatch) { + return exactMatch.id; + } + } + + const turnStartedAt = Date.parse(latestTurn.startedAt); + const turnCompletedAt = Date.parse(latestTurn.completedAt); + if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) { + return null; + } + + let inRangeMatch: string | null = null; + let fallbackMatch: string | null = null; + for (const timelineEntry of timelineEntries) { + if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") { + continue; + } + const messageAt = Date.parse(timelineEntry.message.createdAt); + if (Number.isNaN(messageAt) || messageAt < turnStartedAt) { + continue; + } + fallbackMatch = timelineEntry.id; + if (messageAt <= turnCompletedAt) { + inRangeMatch = timelineEntry.id; + } + } + return inRangeMatch ?? fallbackMatch; +} + export function inferCheckpointTurnCountByTurnId( summaries: TurnDiffSummary[], ): Record { diff --git a/apps/web/src/store.test.ts b/apps/web/src/store.test.ts index db62bad523..6e909b38f0 100644 --- a/apps/web/src/store.test.ts +++ b/apps/web/src/store.test.ts @@ -1,13 +1,22 @@ import { + CheckpointRef, DEFAULT_MODEL_BY_PROVIDER, + EventId, + MessageId, ProjectId, ThreadId, TurnId, + type OrchestrationEvent, type OrchestrationReadModel, } from "@t3tools/contracts"; import { describe, expect, it } from "vitest"; -import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store"; +import { + applyOrchestrationEvent, + applyOrchestrationEvents, + syncServerReadModel, + type AppState, +} from "./store"; import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types"; function makeThread(overrides: Partial = {}): Thread { @@ -48,15 +57,41 @@ function makeState(thread: Thread): AppState { provider: "codex", model: "gpt-5-codex", }, - expanded: true, scripts: [], }, ], threads: [thread], - threadsHydrated: true, + bootstrapComplete: true, }; } +function makeEvent( + type: T, + payload: Extract["payload"], + overrides: Partial> = {}, +): Extract { + const sequence = overrides.sequence ?? 1; + return { + sequence, + eventId: EventId.makeUnsafe(`event-${sequence}`), + aggregateKind: "thread", + aggregateId: + "threadId" in payload + ? payload.threadId + : "projectId" in payload + ? payload.projectId + : ProjectId.makeUnsafe("project-1"), + occurredAt: "2026-02-27T00:00:00.000Z", + commandId: null, + causationEventId: null, + correlationId: null, + metadata: {}, + type, + payload, + ...overrides, + } as Extract; +} + function makeReadModelThread(overrides: Partial) { return { id: ThreadId.makeUnsafe("thread-1"), @@ -126,97 +161,18 @@ function makeReadModelProject( }; } -describe("store pure functions", () => { - it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => { - const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; - const initialState = makeState( - makeThread({ - latestTurn: { - turnId: TurnId.makeUnsafe("turn-1"), - state: "completed", - requestedAt: "2026-02-25T12:28:00.000Z", - startedAt: "2026-02-25T12:28:30.000Z", - completedAt: latestTurnCompletedAt, - assistantMessageId: null, - }, - lastVisitedAt: "2026-02-25T12:35:00.000Z", - }), - ); - - const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1")); - - const updatedThread = next.threads[0]; - expect(updatedThread).toBeDefined(); - expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z"); - expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan( - Date.parse(latestTurnCompletedAt), - ); - }); - - it("markThreadUnread does not change a thread without a completed turn", () => { - const initialState = makeState( - makeThread({ - latestTurn: null, - lastVisitedAt: "2026-02-25T12:35:00.000Z", - }), - ); - - const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1")); - - expect(next).toEqual(initialState); - }); - - it("reorderProjects moves a project to a target index", () => { - const project1 = ProjectId.makeUnsafe("project-1"); - const project2 = ProjectId.makeUnsafe("project-2"); - const project3 = ProjectId.makeUnsafe("project-3"); - const state: AppState = { - projects: [ - { - id: project1, - name: "Project 1", - cwd: "/tmp/project-1", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - { - id: project2, - name: "Project 2", - cwd: "/tmp/project-2", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - { - id: project3, - name: "Project 3", - cwd: "/tmp/project-3", - defaultModelSelection: { - provider: "codex", - model: DEFAULT_MODEL_BY_PROVIDER.codex, - }, - expanded: true, - scripts: [], - }, - ], - threads: [], - threadsHydrated: true, +describe("store read model sync", () => { + it("marks bootstrap complete after snapshot sync", () => { + const initialState: AppState = { + ...makeState(makeThread()), + bootstrapComplete: false, }; - const next = reorderProjects(state, project1, project3); + const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({}))); - expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]); + expect(next.bootstrapComplete).toBe(true); }); -}); -describe("store read model sync", () => { it("preserves claude model slugs without an active session", () => { const initialState = makeState(makeThread()); const readModel = makeReadModel( @@ -287,7 +243,7 @@ describe("store read model sync", () => { expect(next.threads[0]?.archivedAt).toBe(archivedAt); }); - it("preserves the current project order when syncing incoming read model updates", () => { + it("replaces projects using snapshot order during recovery", () => { const project1 = ProjectId.makeUnsafe("project-1"); const project2 = ProjectId.makeUnsafe("project-2"); const project3 = ProjectId.makeUnsafe("project-3"); @@ -301,7 +257,6 @@ describe("store read model sync", () => { provider: "codex", model: DEFAULT_MODEL_BY_PROVIDER.codex, }, - expanded: true, scripts: [], }, { @@ -312,12 +267,11 @@ describe("store read model sync", () => { provider: "codex", model: DEFAULT_MODEL_BY_PROVIDER.codex, }, - expanded: true, scripts: [], }, ], threads: [], - threadsHydrated: true, + bootstrapComplete: true, }; const readModel: OrchestrationReadModel = { snapshotSequence: 2, @@ -344,6 +298,446 @@ describe("store read model sync", () => { const next = syncServerReadModel(initialState, readModel); - expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]); + expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]); + }); +}); + +describe("incremental orchestration updates", () => { + it("does not mark bootstrap complete for incremental events", () => { + const state: AppState = { + ...makeState(makeThread()), + bootstrapComplete: false, + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.meta-updated", { + threadId: ThreadId.makeUnsafe("thread-1"), + title: "Updated title", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.bootstrapComplete).toBe(false); + }); + + it("preserves state identity for no-op project and thread deletes", () => { + const thread = makeThread(); + const state = makeState(thread); + + const nextAfterProjectDelete = applyOrchestrationEvent( + state, + makeEvent("project.deleted", { + projectId: ProjectId.makeUnsafe("project-missing"), + deletedAt: "2026-02-27T00:00:01.000Z", + }), + ); + const nextAfterThreadDelete = applyOrchestrationEvent( + state, + makeEvent("thread.deleted", { + threadId: ThreadId.makeUnsafe("thread-missing"), + deletedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(nextAfterProjectDelete).toBe(state); + expect(nextAfterThreadDelete).toBe(state); + }); + + it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => { + const originalProjectId = ProjectId.makeUnsafe("project-1"); + const recreatedProjectId = ProjectId.makeUnsafe("project-2"); + const state: AppState = { + projects: [ + { + id: originalProjectId, + name: "Project", + cwd: "/tmp/project", + defaultModelSelection: { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }, + scripts: [], + }, + ], + threads: [], + bootstrapComplete: true, + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("project.created", { + projectId: recreatedProjectId, + title: "Project Recreated", + workspaceRoot: "/tmp/project", + defaultModelSelection: { + provider: "codex", + model: DEFAULT_MODEL_BY_PROVIDER.codex, + }, + scripts: [], + createdAt: "2026-02-27T00:00:01.000Z", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.projects).toHaveLength(1); + expect(next.projects[0]?.id).toBe(recreatedProjectId); + expect(next.projects[0]?.cwd).toBe("/tmp/project"); + expect(next.projects[0]?.name).toBe("Project Recreated"); + }); + + it("updates only the affected thread for message events", () => { + const thread1 = makeThread({ + id: ThreadId.makeUnsafe("thread-1"), + messages: [ + { + id: MessageId.makeUnsafe("message-1"), + role: "assistant", + text: "hello", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:00.000Z", + streaming: false, + }, + ], + }); + const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") }); + const state: AppState = { + ...makeState(thread1), + threads: [thread1, thread2], + }; + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.message-sent", { + threadId: thread1.id, + messageId: MessageId.makeUnsafe("message-1"), + role: "assistant", + text: " world", + turnId: TurnId.makeUnsafe("turn-1"), + streaming: true, + createdAt: "2026-02-27T00:00:01.000Z", + updatedAt: "2026-02-27T00:00:01.000Z", + }), + ); + + expect(next.threads[0]?.messages[0]?.text).toBe("hello world"); + expect(next.threads[0]?.latestTurn?.state).toBe("running"); + expect(next.threads[1]).toBe(thread2); + }); + + it("applies replay batches in sequence and updates session state", () => { + const thread = makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-1"), + state: "running", + requestedAt: "2026-02-27T00:00:00.000Z", + startedAt: "2026-02-27T00:00:00.000Z", + completedAt: null, + assistantMessageId: null, + }, + }); + const state = makeState(thread); + + const next = applyOrchestrationEvents(state, [ + makeEvent( + "thread.session-set", + { + threadId: thread.id, + session: { + threadId: thread.id, + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.makeUnsafe("turn-1"), + lastError: null, + updatedAt: "2026-02-27T00:00:02.000Z", + }, + }, + { sequence: 2 }, + ), + makeEvent( + "thread.message-sent", + { + threadId: thread.id, + messageId: MessageId.makeUnsafe("assistant-1"), + role: "assistant", + text: "done", + turnId: TurnId.makeUnsafe("turn-1"), + streaming: false, + createdAt: "2026-02-27T00:00:03.000Z", + updatedAt: "2026-02-27T00:00:03.000Z", + }, + { sequence: 3 }, + ), + ]); + + expect(next.threads[0]?.session?.status).toBe("running"); + expect(next.threads[0]?.latestTurn?.state).toBe("completed"); + expect(next.threads[0]?.messages).toHaveLength(1); + }); + + it("does not regress latestTurn when an older turn diff completes late", () => { + const state = makeState( + makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-2"), + state: "running", + requestedAt: "2026-02-27T00:00:02.000Z", + startedAt: "2026-02-27T00:00:03.000Z", + completedAt: null, + assistantMessageId: null, + }, + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.turn-diff-completed", { + threadId: ThreadId.makeUnsafe("thread-1"), + turnId: TurnId.makeUnsafe("turn-1"), + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"), + status: "ready", + files: [], + assistantMessageId: MessageId.makeUnsafe("assistant-1"), + completedAt: "2026-02-27T00:00:04.000Z", + }), + ); + + expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1); + expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn); + }); + + it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => { + const turnId = TurnId.makeUnsafe("turn-1"); + const state = makeState( + makeThread({ + latestTurn: { + turnId, + state: "completed", + requestedAt: "2026-02-27T00:00:00.000Z", + startedAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:02.000Z", + assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"), + }, + turnDiffSummaries: [ + { + turnId, + completedAt: "2026-02-27T00:00:02.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"), + assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"), + files: [{ path: "src/app.ts", additions: 1, deletions: 0 }], + }, + ], + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.message-sent", { + threadId: ThreadId.makeUnsafe("thread-1"), + messageId: MessageId.makeUnsafe("assistant-real"), + role: "assistant", + text: "final answer", + turnId, + streaming: false, + createdAt: "2026-02-27T00:00:03.000Z", + updatedAt: "2026-02-27T00:00:03.000Z", + }), + ); + + expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe( + MessageId.makeUnsafe("assistant-real"), + ); + expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe( + MessageId.makeUnsafe("assistant-real"), + ); + }); + + it("reverts messages, plans, activities, and checkpoints by retained turns", () => { + const state = makeState( + makeThread({ + messages: [ + { + id: MessageId.makeUnsafe("user-1"), + role: "user", + text: "first", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + completedAt: "2026-02-27T00:00:00.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("assistant-1"), + role: "assistant", + text: "first reply", + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:01.000Z", + completedAt: "2026-02-27T00:00:01.000Z", + streaming: false, + }, + { + id: MessageId.makeUnsafe("user-2"), + role: "user", + text: "second", + turnId: TurnId.makeUnsafe("turn-2"), + createdAt: "2026-02-27T00:00:02.000Z", + completedAt: "2026-02-27T00:00:02.000Z", + streaming: false, + }, + ], + proposedPlans: [ + { + id: "plan-1", + turnId: TurnId.makeUnsafe("turn-1"), + planMarkdown: "plan 1", + implementedAt: null, + implementationThreadId: null, + createdAt: "2026-02-27T00:00:00.000Z", + updatedAt: "2026-02-27T00:00:00.000Z", + }, + { + id: "plan-2", + turnId: TurnId.makeUnsafe("turn-2"), + planMarkdown: "plan 2", + implementedAt: null, + implementationThreadId: null, + createdAt: "2026-02-27T00:00:02.000Z", + updatedAt: "2026-02-27T00:00:02.000Z", + }, + ], + activities: [ + { + id: EventId.makeUnsafe("activity-1"), + tone: "info", + kind: "step", + summary: "one", + payload: {}, + turnId: TurnId.makeUnsafe("turn-1"), + createdAt: "2026-02-27T00:00:00.000Z", + }, + { + id: EventId.makeUnsafe("activity-2"), + tone: "info", + kind: "step", + summary: "two", + payload: {}, + turnId: TurnId.makeUnsafe("turn-2"), + createdAt: "2026-02-27T00:00:02.000Z", + }, + ], + turnDiffSummaries: [ + { + turnId: TurnId.makeUnsafe("turn-1"), + completedAt: "2026-02-27T00:00:01.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("ref-1"), + files: [], + }, + { + turnId: TurnId.makeUnsafe("turn-2"), + completedAt: "2026-02-27T00:00:03.000Z", + status: "ready", + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("ref-2"), + files: [], + }, + ], + }), + ); + + const next = applyOrchestrationEvent( + state, + makeEvent("thread.reverted", { + threadId: ThreadId.makeUnsafe("thread-1"), + turnCount: 1, + }), + ); + + expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([ + "user-1", + "assistant-1", + ]); + expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]); + expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([ + EventId.makeUnsafe("activity-1"), + ]); + expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([ + TurnId.makeUnsafe("turn-1"), + ]); + }); + + it("clears pending source proposed plans after revert before a new session-set event", () => { + const thread = makeThread({ + latestTurn: { + turnId: TurnId.makeUnsafe("turn-2"), + state: "completed", + requestedAt: "2026-02-27T00:00:02.000Z", + startedAt: "2026-02-27T00:00:02.000Z", + completedAt: "2026-02-27T00:00:03.000Z", + assistantMessageId: MessageId.makeUnsafe("assistant-2"), + sourceProposedPlan: { + threadId: ThreadId.makeUnsafe("thread-source"), + planId: "plan-2" as never, + }, + }, + pendingSourceProposedPlan: { + threadId: ThreadId.makeUnsafe("thread-source"), + planId: "plan-2" as never, + }, + turnDiffSummaries: [ + { + turnId: TurnId.makeUnsafe("turn-1"), + completedAt: "2026-02-27T00:00:01.000Z", + status: "ready", + checkpointTurnCount: 1, + checkpointRef: CheckpointRef.makeUnsafe("ref-1"), + files: [], + }, + { + turnId: TurnId.makeUnsafe("turn-2"), + completedAt: "2026-02-27T00:00:03.000Z", + status: "ready", + checkpointTurnCount: 2, + checkpointRef: CheckpointRef.makeUnsafe("ref-2"), + files: [], + }, + ], + }); + const reverted = applyOrchestrationEvent( + makeState(thread), + makeEvent("thread.reverted", { + threadId: thread.id, + turnCount: 1, + }), + ); + + expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined(); + + const next = applyOrchestrationEvent( + reverted, + makeEvent("thread.session-set", { + threadId: thread.id, + session: { + threadId: thread.id, + status: "running", + providerName: "codex", + runtimeMode: "full-access", + activeTurnId: TurnId.makeUnsafe("turn-3"), + lastError: null, + updatedAt: "2026-02-27T00:00:04.000Z", + }, + }), + ); + + expect(next.threads[0]?.latestTurn).toMatchObject({ + turnId: TurnId.makeUnsafe("turn-3"), + state: "running", + }); + expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined(); }); }); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index a5beb5b1bf..eff6a6fd07 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -1,98 +1,36 @@ -import { Fragment, type ReactNode, createElement, useEffect } from "react"; import { + type OrchestrationEvent, + type OrchestrationMessage, + type OrchestrationProposedPlan, type ProviderKind, ThreadId, type OrchestrationReadModel, + type OrchestrationSession, + type OrchestrationCheckpointSummary, + type OrchestrationThread, type OrchestrationSessionStatus, } from "@t3tools/contracts"; import { resolveModelSlugForProvider } from "@t3tools/shared/model"; import { create } from "zustand"; import { type ChatMessage, type Project, type Thread } from "./types"; -import { Debouncer } from "@tanstack/react-pacer"; // ── State ──────────────────────────────────────────────────────────── export interface AppState { projects: Project[]; threads: Thread[]; - threadsHydrated: boolean; + bootstrapComplete: boolean; } -const PERSISTED_STATE_KEY = "t3code:renderer-state:v8"; -const LEGACY_PERSISTED_STATE_KEYS = [ - "t3code:renderer-state:v7", - "t3code:renderer-state:v6", - "t3code:renderer-state:v5", - "t3code:renderer-state:v4", - "t3code:renderer-state:v3", - "codething:renderer-state:v4", - "codething:renderer-state:v3", - "codething:renderer-state:v2", - "codething:renderer-state:v1", -] as const; - const initialState: AppState = { projects: [], threads: [], - threadsHydrated: false, + bootstrapComplete: false, }; -const persistedExpandedProjectCwds = new Set(); -const persistedProjectOrderCwds: string[] = []; - -// ── Persist helpers ────────────────────────────────────────────────── - -function readPersistedState(): AppState { - if (typeof window === "undefined") return initialState; - try { - const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); - if (!raw) return initialState; - const parsed = JSON.parse(raw) as { - expandedProjectCwds?: string[]; - projectOrderCwds?: string[]; - }; - persistedExpandedProjectCwds.clear(); - persistedProjectOrderCwds.length = 0; - for (const cwd of parsed.expandedProjectCwds ?? []) { - if (typeof cwd === "string" && cwd.length > 0) { - persistedExpandedProjectCwds.add(cwd); - } - } - for (const cwd of parsed.projectOrderCwds ?? []) { - if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) { - persistedProjectOrderCwds.push(cwd); - } - } - return { ...initialState }; - } catch { - return initialState; - } -} - -let legacyKeysCleanedUp = false; - -function persistState(state: AppState): void { - if (typeof window === "undefined") return; - try { - window.localStorage.setItem( - PERSISTED_STATE_KEY, - JSON.stringify({ - expandedProjectCwds: state.projects - .filter((project) => project.expanded) - .map((project) => project.cwd), - projectOrderCwds: state.projects.map((project) => project.cwd), - }), - ); - if (!legacyKeysCleanedUp) { - legacyKeysCleanedUp = true; - for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { - window.localStorage.removeItem(legacyKey); - } - } - } catch { - // Ignore quota/storage errors to avoid breaking chat UX. - } -} -const debouncedPersistState = new Debouncer(persistState, { wait: 500 }); +const MAX_THREAD_MESSAGES = 2_000; +const MAX_THREAD_CHECKPOINTS = 500; +const MAX_THREAD_PROPOSED_PLANS = 200; +const MAX_THREAD_ACTIVITIES = 500; // ── Pure helpers ────────────────────────────────────────────────────── @@ -111,66 +49,295 @@ function updateThread( return changed ? next : threads; } -function mapProjectsFromReadModel( - incoming: OrchestrationReadModel["projects"], - previous: Project[], +function updateProject( + projects: Project[], + projectId: Project["id"], + updater: (project: Project) => Project, ): Project[] { - const previousById = new Map(previous.map((project) => [project.id, project] as const)); - const previousByCwd = new Map(previous.map((project) => [project.cwd, project] as const)); - const previousOrderById = new Map(previous.map((project, index) => [project.id, index] as const)); - const previousOrderByCwd = new Map( - previous.map((project, index) => [project.cwd, index] as const), - ); - const persistedOrderByCwd = new Map( - persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const), - ); - const usePersistedOrder = previous.length === 0; - - const mappedProjects = incoming.map((project) => { - const existing = previousById.get(project.id) ?? previousByCwd.get(project.workspaceRoot); - return { - id: project.id, - name: project.title, - cwd: project.workspaceRoot, - defaultModelSelection: - existing?.defaultModelSelection ?? - (project.defaultModelSelection - ? { - ...project.defaultModelSelection, - model: resolveModelSlugForProvider( - project.defaultModelSelection.provider, - project.defaultModelSelection.model, - ), - } - : null), - expanded: - existing?.expanded ?? - (persistedExpandedProjectCwds.size > 0 - ? persistedExpandedProjectCwds.has(project.workspaceRoot) - : true), - createdAt: project.createdAt, - updatedAt: project.updatedAt, - scripts: project.scripts.map((script) => ({ ...script })), - } satisfies Project; + let changed = false; + const next = projects.map((project) => { + if (project.id !== projectId) { + return project; + } + const updated = updater(project); + if (updated !== project) { + changed = true; + } + return updated; }); + return changed ? next : projects; +} - return mappedProjects - .map((project, incomingIndex) => { - const previousIndex = - previousOrderById.get(project.id) ?? previousOrderByCwd.get(project.cwd); - const persistedIndex = usePersistedOrder ? persistedOrderByCwd.get(project.cwd) : undefined; - const orderIndex = - previousIndex ?? - persistedIndex ?? - (usePersistedOrder ? persistedProjectOrderCwds.length : previous.length) + incomingIndex; - return { project, incomingIndex, orderIndex }; - }) - .toSorted((a, b) => { - const byOrder = a.orderIndex - b.orderIndex; - if (byOrder !== 0) return byOrder; - return a.incomingIndex - b.incomingIndex; - }) - .map((entry) => entry.project); +function normalizeModelSelection( + selection: T, +): T { + return { + ...selection, + model: resolveModelSlugForProvider(selection.provider, selection.model), + }; +} + +function mapProjectScripts(scripts: ReadonlyArray): Project["scripts"] { + return scripts.map((script) => ({ ...script })); +} + +function mapSession(session: OrchestrationSession): Thread["session"] { + return { + provider: toLegacyProvider(session.providerName), + status: toLegacySessionStatus(session.status), + orchestrationStatus: session.status, + activeTurnId: session.activeTurnId ?? undefined, + createdAt: session.updatedAt, + updatedAt: session.updatedAt, + ...(session.lastError ? { lastError: session.lastError } : {}), + }; +} + +function mapMessage(message: OrchestrationMessage): ChatMessage { + const attachments = message.attachments?.map((attachment) => ({ + type: "image" as const, + id: attachment.id, + name: attachment.name, + mimeType: attachment.mimeType, + sizeBytes: attachment.sizeBytes, + previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)), + })); + + return { + id: message.id, + role: message.role, + text: message.text, + turnId: message.turnId, + createdAt: message.createdAt, + streaming: message.streaming, + ...(message.streaming ? {} : { completedAt: message.updatedAt }), + ...(attachments && attachments.length > 0 ? { attachments } : {}), + }; +} + +function mapProposedPlan(proposedPlan: OrchestrationProposedPlan): Thread["proposedPlans"][number] { + return { + id: proposedPlan.id, + turnId: proposedPlan.turnId, + planMarkdown: proposedPlan.planMarkdown, + implementedAt: proposedPlan.implementedAt, + implementationThreadId: proposedPlan.implementationThreadId, + createdAt: proposedPlan.createdAt, + updatedAt: proposedPlan.updatedAt, + }; +} + +function mapTurnDiffSummary( + checkpoint: OrchestrationCheckpointSummary, +): Thread["turnDiffSummaries"][number] { + return { + turnId: checkpoint.turnId, + completedAt: checkpoint.completedAt, + status: checkpoint.status, + assistantMessageId: checkpoint.assistantMessageId ?? undefined, + checkpointTurnCount: checkpoint.checkpointTurnCount, + checkpointRef: checkpoint.checkpointRef, + files: checkpoint.files.map((file) => ({ ...file })), + }; +} + +function mapThread(thread: OrchestrationThread): Thread { + return { + id: thread.id, + codexThreadId: null, + projectId: thread.projectId, + title: thread.title, + modelSelection: normalizeModelSelection(thread.modelSelection), + runtimeMode: thread.runtimeMode, + interactionMode: thread.interactionMode, + session: thread.session ? mapSession(thread.session) : null, + messages: thread.messages.map(mapMessage), + proposedPlans: thread.proposedPlans.map(mapProposedPlan), + error: thread.session?.lastError ?? null, + createdAt: thread.createdAt, + archivedAt: thread.archivedAt, + updatedAt: thread.updatedAt, + latestTurn: thread.latestTurn, + pendingSourceProposedPlan: thread.latestTurn?.sourceProposedPlan, + branch: thread.branch, + worktreePath: thread.worktreePath, + turnDiffSummaries: thread.checkpoints.map(mapTurnDiffSummary), + activities: thread.activities.map((activity) => ({ ...activity })), + }; +} + +function mapProject(project: OrchestrationReadModel["projects"][number]): Project { + return { + id: project.id, + name: project.title, + cwd: project.workspaceRoot, + defaultModelSelection: project.defaultModelSelection + ? normalizeModelSelection(project.defaultModelSelection) + : null, + createdAt: project.createdAt, + updatedAt: project.updatedAt, + scripts: mapProjectScripts(project.scripts), + }; +} + +function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") { + if (status === "error") { + return "error" as const; + } + if (status === "missing") { + return "interrupted" as const; + } + return "completed" as const; +} + +function compareActivities( + left: Thread["activities"][number], + right: Thread["activities"][number], +): number { + if (left.sequence !== undefined && right.sequence !== undefined) { + if (left.sequence !== right.sequence) { + return left.sequence - right.sequence; + } + } else if (left.sequence !== undefined) { + return 1; + } else if (right.sequence !== undefined) { + return -1; + } + + return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id); +} + +function buildLatestTurn(params: { + previous: Thread["latestTurn"]; + turnId: NonNullable["turnId"]; + state: NonNullable["state"]; + requestedAt: string; + startedAt: string | null; + completedAt: string | null; + assistantMessageId: NonNullable["assistantMessageId"]; + sourceProposedPlan?: Thread["pendingSourceProposedPlan"]; +}): NonNullable { + const resolvedPlan = + params.previous?.turnId === params.turnId + ? params.previous.sourceProposedPlan + : params.sourceProposedPlan; + return { + turnId: params.turnId, + state: params.state, + requestedAt: params.requestedAt, + startedAt: params.startedAt, + completedAt: params.completedAt, + assistantMessageId: params.assistantMessageId, + ...(resolvedPlan ? { sourceProposedPlan: resolvedPlan } : {}), + }; +} + +function rebindTurnDiffSummariesForAssistantMessage( + turnDiffSummaries: ReadonlyArray, + turnId: Thread["turnDiffSummaries"][number]["turnId"], + assistantMessageId: NonNullable["assistantMessageId"], +): Thread["turnDiffSummaries"] { + let changed = false; + const nextSummaries = turnDiffSummaries.map((summary) => { + if (summary.turnId !== turnId || summary.assistantMessageId === assistantMessageId) { + return summary; + } + changed = true; + return { + ...summary, + assistantMessageId: assistantMessageId ?? undefined, + }; + }); + return changed ? nextSummaries : [...turnDiffSummaries]; +} + +function retainThreadMessagesAfterRevert( + messages: ReadonlyArray, + retainedTurnIds: ReadonlySet, + turnCount: number, +): ChatMessage[] { + const retainedMessageIds = new Set(); + for (const message of messages) { + if (message.role === "system") { + retainedMessageIds.add(message.id); + continue; + } + if ( + message.turnId !== undefined && + message.turnId !== null && + retainedTurnIds.has(message.turnId) + ) { + retainedMessageIds.add(message.id); + } + } + + const retainedUserCount = messages.filter( + (message) => message.role === "user" && retainedMessageIds.has(message.id), + ).length; + const missingUserCount = Math.max(0, turnCount - retainedUserCount); + if (missingUserCount > 0) { + const fallbackUserMessages = messages + .filter( + (message) => + message.role === "user" && + !retainedMessageIds.has(message.id) && + (message.turnId === undefined || + message.turnId === null || + retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingUserCount); + for (const message of fallbackUserMessages) { + retainedMessageIds.add(message.id); + } + } + + const retainedAssistantCount = messages.filter( + (message) => message.role === "assistant" && retainedMessageIds.has(message.id), + ).length; + const missingAssistantCount = Math.max(0, turnCount - retainedAssistantCount); + if (missingAssistantCount > 0) { + const fallbackAssistantMessages = messages + .filter( + (message) => + message.role === "assistant" && + !retainedMessageIds.has(message.id) && + (message.turnId === undefined || + message.turnId === null || + retainedTurnIds.has(message.turnId)), + ) + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(0, missingAssistantCount); + for (const message of fallbackAssistantMessages) { + retainedMessageIds.add(message.id); + } + } + + return messages.filter((message) => retainedMessageIds.has(message.id)); +} + +function retainThreadActivitiesAfterRevert( + activities: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): Thread["activities"] { + return activities.filter( + (activity) => activity.turnId === null || retainedTurnIds.has(activity.turnId), + ); +} + +function retainThreadProposedPlansAfterRevert( + proposedPlans: ReadonlyArray, + retainedTurnIds: ReadonlySet, +): Thread["proposedPlans"] { + return proposedPlans.filter( + (proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId), + ); } function toLegacySessionStatus( @@ -234,166 +401,505 @@ function attachmentPreviewRoutePath(attachmentId: string): string { // ── Pure state transition functions ──────────────────────────────────── export function syncServerReadModel(state: AppState, readModel: OrchestrationReadModel): AppState { - const projects = mapProjectsFromReadModel( - readModel.projects.filter((project) => project.deletedAt === null), - state.projects, - ); - const existingThreadById = new Map(state.threads.map((thread) => [thread.id, thread] as const)); - const threads = readModel.threads - .filter((thread) => thread.deletedAt === null) - .map((thread) => { - const existing = existingThreadById.get(thread.id); - return { - id: thread.id, - codexThreadId: null, - projectId: thread.projectId, - title: thread.title, - modelSelection: { - ...thread.modelSelection, - model: resolveModelSlugForProvider( - thread.modelSelection.provider, - thread.modelSelection.model, - ), - }, - runtimeMode: thread.runtimeMode, - interactionMode: thread.interactionMode, - session: thread.session - ? { - provider: toLegacyProvider(thread.session.providerName), - status: toLegacySessionStatus(thread.session.status), - orchestrationStatus: thread.session.status, - activeTurnId: thread.session.activeTurnId ?? undefined, - createdAt: thread.session.updatedAt, - updatedAt: thread.session.updatedAt, - ...(thread.session.lastError ? { lastError: thread.session.lastError } : {}), - } - : null, - messages: thread.messages.map((message) => { - const attachments = message.attachments?.map((attachment) => ({ - type: "image" as const, - id: attachment.id, - name: attachment.name, - mimeType: attachment.mimeType, - sizeBytes: attachment.sizeBytes, - previewUrl: toAttachmentPreviewUrl(attachmentPreviewRoutePath(attachment.id)), - })); - const normalizedMessage: ChatMessage = { - id: message.id, - role: message.role, - text: message.text, - createdAt: message.createdAt, - streaming: message.streaming, - ...(message.streaming ? {} : { completedAt: message.updatedAt }), - ...(attachments && attachments.length > 0 ? { attachments } : {}), - }; - return normalizedMessage; - }), - proposedPlans: thread.proposedPlans.map((proposedPlan) => ({ - id: proposedPlan.id, - turnId: proposedPlan.turnId, - planMarkdown: proposedPlan.planMarkdown, - implementedAt: proposedPlan.implementedAt, - implementationThreadId: proposedPlan.implementationThreadId, - createdAt: proposedPlan.createdAt, - updatedAt: proposedPlan.updatedAt, - })), - error: thread.session?.lastError ?? null, - createdAt: thread.createdAt, - archivedAt: thread.archivedAt, - updatedAt: thread.updatedAt, - latestTurn: thread.latestTurn, - lastVisitedAt: existing?.lastVisitedAt ?? thread.updatedAt, - branch: thread.branch, - worktreePath: thread.worktreePath, - turnDiffSummaries: thread.checkpoints.map((checkpoint) => ({ - turnId: checkpoint.turnId, - completedAt: checkpoint.completedAt, - status: checkpoint.status, - assistantMessageId: checkpoint.assistantMessageId ?? undefined, - checkpointTurnCount: checkpoint.checkpointTurnCount, - checkpointRef: checkpoint.checkpointRef, - files: checkpoint.files.map((file) => ({ ...file })), - })), - activities: thread.activities.map((activity) => ({ ...activity })), - }; - }); + const projects = readModel.projects + .filter((project) => project.deletedAt === null) + .map(mapProject); + const threads = readModel.threads.filter((thread) => thread.deletedAt === null).map(mapThread); return { ...state, projects, threads, - threadsHydrated: true, + bootstrapComplete: true, }; } -export function markThreadVisited( - state: AppState, - threadId: ThreadId, - visitedAt?: string, -): AppState { - const at = visitedAt ?? new Date().toISOString(); - const visitedAtMs = Date.parse(at); - const threads = updateThread(state.threads, threadId, (thread) => { - const previousVisitedAtMs = thread.lastVisitedAt ? Date.parse(thread.lastVisitedAt) : NaN; - if ( - Number.isFinite(previousVisitedAtMs) && - Number.isFinite(visitedAtMs) && - previousVisitedAtMs >= visitedAtMs - ) { - return thread; +export function applyOrchestrationEvent(state: AppState, event: OrchestrationEvent): AppState { + switch (event.type) { + case "project.created": { + const existingIndex = state.projects.findIndex( + (project) => + project.id === event.payload.projectId || project.cwd === event.payload.workspaceRoot, + ); + const nextProject = mapProject({ + id: event.payload.projectId, + title: event.payload.title, + workspaceRoot: event.payload.workspaceRoot, + defaultModelSelection: event.payload.defaultModelSelection, + scripts: event.payload.scripts, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + deletedAt: null, + }); + const projects = + existingIndex >= 0 + ? state.projects.map((project, index) => + index === existingIndex ? nextProject : project, + ) + : [...state.projects, nextProject]; + return { ...state, projects }; } - return { ...thread, lastVisitedAt: at }; - }); - return threads === state.threads ? state : { ...state, threads }; + + case "project.meta-updated": { + const projects = updateProject(state.projects, event.payload.projectId, (project) => ({ + ...project, + ...(event.payload.title !== undefined ? { name: event.payload.title } : {}), + ...(event.payload.workspaceRoot !== undefined ? { cwd: event.payload.workspaceRoot } : {}), + ...(event.payload.defaultModelSelection !== undefined + ? { + defaultModelSelection: event.payload.defaultModelSelection + ? normalizeModelSelection(event.payload.defaultModelSelection) + : null, + } + : {}), + ...(event.payload.scripts !== undefined + ? { scripts: mapProjectScripts(event.payload.scripts) } + : {}), + updatedAt: event.payload.updatedAt, + })); + return projects === state.projects ? state : { ...state, projects }; + } + + case "project.deleted": { + const projects = state.projects.filter((project) => project.id !== event.payload.projectId); + return projects.length === state.projects.length ? state : { ...state, projects }; + } + + case "thread.created": { + const existing = state.threads.find((thread) => thread.id === event.payload.threadId); + const nextThread = mapThread({ + id: event.payload.threadId, + projectId: event.payload.projectId, + title: event.payload.title, + modelSelection: event.payload.modelSelection, + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + branch: event.payload.branch, + worktreePath: event.payload.worktreePath, + latestTurn: null, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + archivedAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + session: null, + }); + const threads = existing + ? state.threads.map((thread) => (thread.id === nextThread.id ? nextThread : thread)) + : [...state.threads, nextThread]; + return { ...state, threads }; + } + + case "thread.deleted": { + const threads = state.threads.filter((thread) => thread.id !== event.payload.threadId); + return threads.length === state.threads.length ? state : { ...state, threads }; + } + + case "thread.archived": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + archivedAt: event.payload.archivedAt, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.unarchived": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + archivedAt: null, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.meta-updated": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + ...(event.payload.title !== undefined ? { title: event.payload.title } : {}), + ...(event.payload.modelSelection !== undefined + ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) } + : {}), + ...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}), + ...(event.payload.worktreePath !== undefined + ? { worktreePath: event.payload.worktreePath } + : {}), + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.runtime-mode-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + runtimeMode: event.payload.runtimeMode, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.interaction-mode-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + interactionMode: event.payload.interactionMode, + updatedAt: event.payload.updatedAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-start-requested": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + ...(event.payload.modelSelection !== undefined + ? { modelSelection: normalizeModelSelection(event.payload.modelSelection) } + : {}), + runtimeMode: event.payload.runtimeMode, + interactionMode: event.payload.interactionMode, + pendingSourceProposedPlan: event.payload.sourceProposedPlan, + updatedAt: event.occurredAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-interrupt-requested": { + if (event.payload.turnId === undefined) { + return state; + } + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const latestTurn = thread.latestTurn; + if (latestTurn === null || latestTurn.turnId !== event.payload.turnId) { + return thread; + } + return { + ...thread, + latestTurn: buildLatestTurn({ + previous: latestTurn, + turnId: event.payload.turnId, + state: "interrupted", + requestedAt: latestTurn.requestedAt, + startedAt: latestTurn.startedAt ?? event.payload.createdAt, + completedAt: latestTurn.completedAt ?? event.payload.createdAt, + assistantMessageId: latestTurn.assistantMessageId, + }), + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.message-sent": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const message = mapMessage({ + id: event.payload.messageId, + role: event.payload.role, + text: event.payload.text, + ...(event.payload.attachments !== undefined + ? { attachments: event.payload.attachments } + : {}), + turnId: event.payload.turnId, + streaming: event.payload.streaming, + createdAt: event.payload.createdAt, + updatedAt: event.payload.updatedAt, + }); + const existingMessage = thread.messages.find((entry) => entry.id === message.id); + const messages = existingMessage + ? thread.messages.map((entry) => + entry.id !== message.id + ? entry + : { + ...entry, + text: message.streaming + ? `${entry.text}${message.text}` + : message.text.length > 0 + ? message.text + : entry.text, + streaming: message.streaming, + ...(message.turnId !== undefined ? { turnId: message.turnId } : {}), + ...(message.streaming + ? entry.completedAt !== undefined + ? { completedAt: entry.completedAt } + : {} + : message.completedAt !== undefined + ? { completedAt: message.completedAt } + : {}), + ...(message.attachments !== undefined + ? { attachments: message.attachments } + : {}), + }, + ) + : [...thread.messages, message]; + const cappedMessages = messages.slice(-MAX_THREAD_MESSAGES); + const turnDiffSummaries = + event.payload.role === "assistant" && event.payload.turnId !== null + ? rebindTurnDiffSummariesForAssistantMessage( + thread.turnDiffSummaries, + event.payload.turnId, + event.payload.messageId, + ) + : thread.turnDiffSummaries; + const latestTurn: Thread["latestTurn"] = + event.payload.role === "assistant" && + event.payload.turnId !== null && + (thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId) + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.turnId, + state: event.payload.streaming + ? "running" + : thread.latestTurn?.state === "interrupted" + ? "interrupted" + : thread.latestTurn?.state === "error" + ? "error" + : "completed", + requestedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? thread.latestTurn.requestedAt + : event.payload.createdAt, + startedAt: + thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.startedAt ?? event.payload.createdAt) + : event.payload.createdAt, + sourceProposedPlan: thread.pendingSourceProposedPlan, + completedAt: event.payload.streaming + ? thread.latestTurn?.turnId === event.payload.turnId + ? (thread.latestTurn.completedAt ?? null) + : null + : event.payload.updatedAt, + assistantMessageId: event.payload.messageId, + }) + : thread.latestTurn; + return { + ...thread, + messages: cappedMessages, + turnDiffSummaries, + latestTurn, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.session-set": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => ({ + ...thread, + session: mapSession(event.payload.session), + error: event.payload.session.lastError ?? null, + latestTurn: + event.payload.session.status === "running" && event.payload.session.activeTurnId !== null + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.session.activeTurnId, + state: "running", + requestedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.requestedAt + : event.payload.session.updatedAt, + startedAt: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? (thread.latestTurn.startedAt ?? event.payload.session.updatedAt) + : event.payload.session.updatedAt, + completedAt: null, + assistantMessageId: + thread.latestTurn?.turnId === event.payload.session.activeTurnId + ? thread.latestTurn.assistantMessageId + : null, + sourceProposedPlan: thread.pendingSourceProposedPlan, + }) + : thread.latestTurn, + updatedAt: event.occurredAt, + })); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.session-stop-requested": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => + thread.session === null + ? thread + : { + ...thread, + session: { + ...thread.session, + status: "closed", + orchestrationStatus: "stopped", + activeTurnId: undefined, + updatedAt: event.payload.createdAt, + }, + updatedAt: event.occurredAt, + }, + ); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.proposed-plan-upserted": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const proposedPlan = mapProposedPlan(event.payload.proposedPlan); + const proposedPlans = [ + ...thread.proposedPlans.filter((entry) => entry.id !== proposedPlan.id), + proposedPlan, + ] + .toSorted( + (left, right) => + left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id), + ) + .slice(-MAX_THREAD_PROPOSED_PLANS); + return { + ...thread, + proposedPlans, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.turn-diff-completed": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const checkpoint = mapTurnDiffSummary({ + turnId: event.payload.turnId, + checkpointTurnCount: event.payload.checkpointTurnCount, + checkpointRef: event.payload.checkpointRef, + status: event.payload.status, + files: event.payload.files, + assistantMessageId: event.payload.assistantMessageId, + completedAt: event.payload.completedAt, + }); + const existing = thread.turnDiffSummaries.find( + (entry) => entry.turnId === checkpoint.turnId, + ); + if (existing && existing.status !== "missing" && checkpoint.status === "missing") { + return thread; + } + const turnDiffSummaries = [ + ...thread.turnDiffSummaries.filter((entry) => entry.turnId !== checkpoint.turnId), + checkpoint, + ] + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-MAX_THREAD_CHECKPOINTS); + const latestTurn = + thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId + ? buildLatestTurn({ + previous: thread.latestTurn, + turnId: event.payload.turnId, + state: checkpointStatusToLatestTurnState(event.payload.status), + requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt, + startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt, + completedAt: event.payload.completedAt, + assistantMessageId: event.payload.assistantMessageId, + sourceProposedPlan: thread.pendingSourceProposedPlan, + }) + : thread.latestTurn; + return { + ...thread, + turnDiffSummaries, + latestTurn, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.reverted": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const turnDiffSummaries = thread.turnDiffSummaries + .filter( + (entry) => + entry.checkpointTurnCount !== undefined && + entry.checkpointTurnCount <= event.payload.turnCount, + ) + .toSorted( + (left, right) => + (left.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER) - + (right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER), + ) + .slice(-MAX_THREAD_CHECKPOINTS); + const retainedTurnIds = new Set(turnDiffSummaries.map((entry) => entry.turnId)); + const messages = retainThreadMessagesAfterRevert( + thread.messages, + retainedTurnIds, + event.payload.turnCount, + ).slice(-MAX_THREAD_MESSAGES); + const proposedPlans = retainThreadProposedPlansAfterRevert( + thread.proposedPlans, + retainedTurnIds, + ).slice(-MAX_THREAD_PROPOSED_PLANS); + const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds); + const latestCheckpoint = turnDiffSummaries.at(-1) ?? null; + + return { + ...thread, + turnDiffSummaries, + messages, + proposedPlans, + activities, + pendingSourceProposedPlan: undefined, + latestTurn: + latestCheckpoint === null + ? null + : { + turnId: latestCheckpoint.turnId, + state: checkpointStatusToLatestTurnState( + (latestCheckpoint.status ?? "ready") as "ready" | "missing" | "error", + ), + requestedAt: latestCheckpoint.completedAt, + startedAt: latestCheckpoint.completedAt, + completedAt: latestCheckpoint.completedAt, + assistantMessageId: latestCheckpoint.assistantMessageId ?? null, + }, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.activity-appended": { + const threads = updateThread(state.threads, event.payload.threadId, (thread) => { + const activities = [ + ...thread.activities.filter((activity) => activity.id !== event.payload.activity.id), + { ...event.payload.activity }, + ] + .toSorted(compareActivities) + .slice(-MAX_THREAD_ACTIVITIES); + return { + ...thread, + activities, + updatedAt: event.occurredAt, + }; + }); + return threads === state.threads ? state : { ...state, threads }; + } + + case "thread.approval-response-requested": + case "thread.user-input-response-requested": + return state; + } + + return state; } -export function markThreadUnread(state: AppState, threadId: ThreadId): AppState { - const threads = updateThread(state.threads, threadId, (thread) => { - if (!thread.latestTurn?.completedAt) return thread; - const latestTurnCompletedAtMs = Date.parse(thread.latestTurn.completedAt); - if (Number.isNaN(latestTurnCompletedAtMs)) return thread; - const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString(); - if (thread.lastVisitedAt === unreadVisitedAt) return thread; - return { ...thread, lastVisitedAt: unreadVisitedAt }; - }); - return threads === state.threads ? state : { ...state, threads }; -} - -export function toggleProject(state: AppState, projectId: Project["id"]): AppState { - return { - ...state, - projects: state.projects.map((p) => (p.id === projectId ? { ...p, expanded: !p.expanded } : p)), - }; -} - -export function setProjectExpanded( +export function applyOrchestrationEvents( state: AppState, - projectId: Project["id"], - expanded: boolean, + events: ReadonlyArray, ): AppState { - let changed = false; - const projects = state.projects.map((p) => { - if (p.id !== projectId || p.expanded === expanded) return p; - changed = true; - return { ...p, expanded }; - }); - return changed ? { ...state, projects } : state; + if (events.length === 0) { + return state; + } + return events.reduce((nextState, event) => applyOrchestrationEvent(nextState, event), state); } -export function reorderProjects( - state: AppState, - draggedProjectId: Project["id"], - targetProjectId: Project["id"], -): AppState { - if (draggedProjectId === targetProjectId) return state; - const draggedIndex = state.projects.findIndex((project) => project.id === draggedProjectId); - const targetIndex = state.projects.findIndex((project) => project.id === targetProjectId); - if (draggedIndex < 0 || targetIndex < 0) return state; - const projects = [...state.projects]; - const [draggedProject] = projects.splice(draggedIndex, 1); - if (!draggedProject) return state; - projects.splice(targetIndex, 0, draggedProject); - return { ...state, projects }; -} +export const selectProjectById = + (projectId: Project["id"] | null | undefined) => + (state: AppState): Project | undefined => + projectId ? state.projects.find((project) => project.id === projectId) : undefined; + +export const selectThreadById = + (threadId: ThreadId | null | undefined) => + (state: AppState): Thread | undefined => + threadId ? state.threads.find((thread) => thread.id === threadId) : undefined; export function setError(state: AppState, threadId: ThreadId, error: string | null): AppState { const threads = updateThread(state.threads, threadId, (t) => { @@ -426,44 +932,18 @@ export function setThreadBranch( interface AppStore extends AppState { syncServerReadModel: (readModel: OrchestrationReadModel) => void; - markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void; - markThreadUnread: (threadId: ThreadId) => void; - toggleProject: (projectId: Project["id"]) => void; - setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void; - reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void; + applyOrchestrationEvent: (event: OrchestrationEvent) => void; + applyOrchestrationEvents: (events: ReadonlyArray) => void; setError: (threadId: ThreadId, error: string | null) => void; setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void; } export const useStore = create((set) => ({ - ...readPersistedState(), + ...initialState, syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)), - markThreadVisited: (threadId, visitedAt) => - set((state) => markThreadVisited(state, threadId, visitedAt)), - markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)), - toggleProject: (projectId) => set((state) => toggleProject(state, projectId)), - setProjectExpanded: (projectId, expanded) => - set((state) => setProjectExpanded(state, projectId, expanded)), - reorderProjects: (draggedProjectId, targetProjectId) => - set((state) => reorderProjects(state, draggedProjectId, targetProjectId)), + applyOrchestrationEvent: (event) => set((state) => applyOrchestrationEvent(state, event)), + applyOrchestrationEvents: (events) => set((state) => applyOrchestrationEvents(state, events)), setError: (threadId, error) => set((state) => setError(state, threadId, error)), setThreadBranch: (threadId, branch, worktreePath) => set((state) => setThreadBranch(state, threadId, branch, worktreePath)), })); - -// Persist state changes with debouncing to avoid localStorage thrashing -useStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); - -// Flush pending writes synchronously before page unload to prevent data loss. -if (typeof window !== "undefined") { - window.addEventListener("beforeunload", () => { - debouncedPersistState.flush(); - }); -} - -export function StoreProvider({ children }: { children: ReactNode }) { - useEffect(() => { - persistState(useStore.getState()); - }, []); - return createElement(Fragment, null, children); -} diff --git a/apps/web/src/storeSelectors.ts b/apps/web/src/storeSelectors.ts new file mode 100644 index 0000000000..271fbb256b --- /dev/null +++ b/apps/web/src/storeSelectors.ts @@ -0,0 +1,14 @@ +import { type ThreadId } from "@t3tools/contracts"; +import { useMemo } from "react"; +import { selectProjectById, selectThreadById, useStore } from "./store"; +import { type Project, type Thread } from "./types"; + +export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined { + const selector = useMemo(() => selectProjectById(projectId), [projectId]); + return useStore(selector); +} + +export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined { + const selector = useMemo(() => selectThreadById(threadId), [threadId]); + return useStore(selector); +} diff --git a/apps/web/src/terminalStateStore.ts b/apps/web/src/terminalStateStore.ts index 4f51e2ed8d..62e0883516 100644 --- a/apps/web/src/terminalStateStore.ts +++ b/apps/web/src/terminalStateStore.ts @@ -485,6 +485,7 @@ interface TerminalStateStoreState { hasRunningSubprocess: boolean, ) => void; clearTerminalState: (threadId: ThreadId) => void; + removeTerminalState: (threadId: ThreadId) => void; removeOrphanedTerminalStates: (activeThreadIds: Set) => void; } @@ -530,6 +531,15 @@ export const useTerminalStateStore = create()( ), clearTerminalState: (threadId) => updateTerminal(threadId, () => createDefaultThreadTerminalState()), + removeTerminalState: (threadId) => + set((state) => { + if (state.terminalStateByThreadId[threadId] === undefined) { + return state; + } + const next = { ...state.terminalStateByThreadId }; + delete next[threadId]; + return { terminalStateByThreadId: next }; + }), removeOrphanedTerminalStates: (activeThreadIds) => set((state) => { const orphanedIds = Object.keys(state.terminalStateByThreadId).filter( diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index e6cb1efea6..0ebf150310 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -45,6 +45,7 @@ export interface ChatMessage { role: "user" | "assistant" | "system"; text: string; attachments?: ChatAttachment[]; + turnId?: TurnId | null; createdAt: string; completedAt?: string | undefined; streaming: boolean; @@ -82,7 +83,6 @@ export interface Project { name: string; cwd: string; defaultModelSelection: ModelSelection | null; - expanded: boolean; createdAt?: string | undefined; updatedAt?: string | undefined; scripts: ProjectScript[]; @@ -104,7 +104,7 @@ export interface Thread { archivedAt: string | null; updatedAt?: string | undefined; latestTurn: OrchestrationLatestTurn | null; - lastVisitedAt?: string | undefined; + pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"]; branch: string | null; worktreePath: string | null; turnDiffSummaries: TurnDiffSummary[]; diff --git a/apps/web/src/uiStateStore.test.ts b/apps/web/src/uiStateStore.test.ts new file mode 100644 index 0000000000..b0b19f763a --- /dev/null +++ b/apps/web/src/uiStateStore.test.ts @@ -0,0 +1,192 @@ +import { ProjectId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vitest"; + +import { + clearThreadUi, + markThreadUnread, + reorderProjects, + setProjectExpanded, + syncProjects, + syncThreads, + type UiState, +} from "./uiStateStore"; + +function makeUiState(overrides: Partial = {}): UiState { + return { + projectExpandedById: {}, + projectOrder: [], + threadLastVisitedAtById: {}, + ...overrides, + }; +} + +describe("uiStateStore pure functions", () => { + it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => { + const threadId = ThreadId.makeUnsafe("thread-1"); + const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z"; + const initialState = makeUiState({ + threadLastVisitedAtById: { + [threadId]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt); + + expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z"); + }); + + it("markThreadUnread does not change a thread without a completed turn", () => { + const threadId = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [threadId]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = markThreadUnread(initialState, threadId, null); + + expect(next).toBe(initialState); + }); + + it("reorderProjects moves a project to a target index", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const project2 = ProjectId.makeUnsafe("project-2"); + const project3 = ProjectId.makeUnsafe("project-3"); + const initialState = makeUiState({ + projectOrder: [project1, project2, project3], + }); + + const next = reorderProjects(initialState, project1, project3); + + expect(next.projectOrder).toEqual([project2, project3, project1]); + }); + + it("syncProjects preserves current project order during snapshot recovery", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const project2 = ProjectId.makeUnsafe("project-2"); + const project3 = ProjectId.makeUnsafe("project-3"); + const initialState = makeUiState({ + projectExpandedById: { + [project1]: true, + [project2]: false, + }, + projectOrder: [project2, project1], + }); + + const next = syncProjects(initialState, [ + { id: project1, cwd: "/tmp/project-1" }, + { id: project2, cwd: "/tmp/project-2" }, + { id: project3, cwd: "/tmp/project-3" }, + ]); + + expect(next.projectOrder).toEqual([project2, project1, project3]); + expect(next.projectExpandedById[project2]).toBe(false); + }); + + it("syncProjects preserves manual order when a project is recreated with the same cwd", () => { + const oldProject1 = ProjectId.makeUnsafe("project-1"); + const oldProject2 = ProjectId.makeUnsafe("project-2"); + const recreatedProject2 = ProjectId.makeUnsafe("project-2b"); + const initialState = syncProjects( + makeUiState({ + projectExpandedById: { + [oldProject1]: true, + [oldProject2]: false, + }, + projectOrder: [oldProject2, oldProject1], + }), + [ + { id: oldProject1, cwd: "/tmp/project-1" }, + { id: oldProject2, cwd: "/tmp/project-2" }, + ], + ); + + const next = syncProjects(initialState, [ + { id: oldProject1, cwd: "/tmp/project-1" }, + { id: recreatedProject2, cwd: "/tmp/project-2" }, + ]); + + expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]); + expect(next.projectExpandedById[recreatedProject2]).toBe(false); + }); + + it("syncProjects returns a new state when only project cwd changes", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const initialState = syncProjects( + makeUiState({ + projectExpandedById: { + [project1]: false, + }, + projectOrder: [project1], + }), + [{ id: project1, cwd: "/tmp/project-1" }], + ); + + const next = syncProjects(initialState, [{ id: project1, cwd: "/tmp/project-1-renamed" }]); + + expect(next).not.toBe(initialState); + expect(next.projectOrder).toEqual([project1]); + expect(next.projectExpandedById[project1]).toBe(false); + }); + + it("syncThreads prunes missing thread UI state", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const thread2 = ThreadId.makeUnsafe("thread-2"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [thread1]: "2026-02-25T12:35:00.000Z", + [thread2]: "2026-02-25T12:36:00.000Z", + }, + }); + + const next = syncThreads(initialState, [{ id: thread1 }]); + + expect(next.threadLastVisitedAtById).toEqual({ + [thread1]: "2026-02-25T12:35:00.000Z", + }); + }); + + it("syncThreads seeds visit state for unseen snapshot threads", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState(); + + const next = syncThreads(initialState, [ + { + id: thread1, + seedVisitedAt: "2026-02-25T12:35:00.000Z", + }, + ]); + + expect(next.threadLastVisitedAtById).toEqual({ + [thread1]: "2026-02-25T12:35:00.000Z", + }); + }); + + it("setProjectExpanded updates expansion without touching order", () => { + const project1 = ProjectId.makeUnsafe("project-1"); + const initialState = makeUiState({ + projectExpandedById: { + [project1]: true, + }, + projectOrder: [project1], + }); + + const next = setProjectExpanded(initialState, project1, false); + + expect(next.projectExpandedById[project1]).toBe(false); + expect(next.projectOrder).toEqual([project1]); + }); + + it("clearThreadUi removes visit state for deleted threads", () => { + const thread1 = ThreadId.makeUnsafe("thread-1"); + const initialState = makeUiState({ + threadLastVisitedAtById: { + [thread1]: "2026-02-25T12:35:00.000Z", + }, + }); + + const next = clearThreadUi(initialState, thread1); + + expect(next.threadLastVisitedAtById).toEqual({}); + }); +}); diff --git a/apps/web/src/uiStateStore.ts b/apps/web/src/uiStateStore.ts new file mode 100644 index 0000000000..342f2db18f --- /dev/null +++ b/apps/web/src/uiStateStore.ts @@ -0,0 +1,417 @@ +import { Debouncer } from "@tanstack/react-pacer"; +import { type ProjectId, type ThreadId } from "@t3tools/contracts"; +import { create } from "zustand"; + +const PERSISTED_STATE_KEY = "t3code:ui-state:v1"; +const LEGACY_PERSISTED_STATE_KEYS = [ + "t3code:renderer-state:v8", + "t3code:renderer-state:v7", + "t3code:renderer-state:v6", + "t3code:renderer-state:v5", + "t3code:renderer-state:v4", + "t3code:renderer-state:v3", + "codething:renderer-state:v4", + "codething:renderer-state:v3", + "codething:renderer-state:v2", + "codething:renderer-state:v1", +] as const; + +interface PersistedUiState { + expandedProjectCwds?: string[]; + projectOrderCwds?: string[]; +} + +export interface UiProjectState { + projectExpandedById: Record; + projectOrder: ProjectId[]; +} + +export interface UiThreadState { + threadLastVisitedAtById: Record; +} + +export interface UiState extends UiProjectState, UiThreadState {} + +export interface SyncProjectInput { + id: ProjectId; + cwd: string; +} + +export interface SyncThreadInput { + id: ThreadId; + seedVisitedAt?: string | undefined; +} + +const initialState: UiState = { + projectExpandedById: {}, + projectOrder: [], + threadLastVisitedAtById: {}, +}; + +const persistedExpandedProjectCwds = new Set(); +const persistedProjectOrderCwds: string[] = []; +const currentProjectCwdById = new Map(); +let legacyKeysCleanedUp = false; + +function readPersistedState(): UiState { + if (typeof window === "undefined") { + return initialState; + } + try { + const raw = window.localStorage.getItem(PERSISTED_STATE_KEY); + if (!raw) { + for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { + const legacyRaw = window.localStorage.getItem(legacyKey); + if (!legacyRaw) { + continue; + } + hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState); + return initialState; + } + return initialState; + } + hydratePersistedProjectState(JSON.parse(raw) as PersistedUiState); + return initialState; + } catch { + return initialState; + } +} + +function hydratePersistedProjectState(parsed: PersistedUiState): void { + persistedExpandedProjectCwds.clear(); + persistedProjectOrderCwds.length = 0; + for (const cwd of parsed.expandedProjectCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0) { + persistedExpandedProjectCwds.add(cwd); + } + } + for (const cwd of parsed.projectOrderCwds ?? []) { + if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) { + persistedProjectOrderCwds.push(cwd); + } + } +} + +function persistState(state: UiState): void { + if (typeof window === "undefined") { + return; + } + try { + const expandedProjectCwds = Object.entries(state.projectExpandedById) + .filter(([, expanded]) => expanded) + .flatMap(([projectId]) => { + const cwd = currentProjectCwdById.get(projectId as ProjectId); + return cwd ? [cwd] : []; + }); + const projectOrderCwds = state.projectOrder.flatMap((projectId) => { + const cwd = currentProjectCwdById.get(projectId); + return cwd ? [cwd] : []; + }); + window.localStorage.setItem( + PERSISTED_STATE_KEY, + JSON.stringify({ + expandedProjectCwds, + projectOrderCwds, + } satisfies PersistedUiState), + ); + if (!legacyKeysCleanedUp) { + legacyKeysCleanedUp = true; + for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) { + window.localStorage.removeItem(legacyKey); + } + } + } catch { + // Ignore quota/storage errors to avoid breaking chat UX. + } +} + +const debouncedPersistState = new Debouncer(persistState, { wait: 500 }); + +function recordsEqual(left: Record, right: Record): boolean { + const leftEntries = Object.entries(left); + const rightEntries = Object.entries(right); + if (leftEntries.length !== rightEntries.length) { + return false; + } + for (const [key, value] of leftEntries) { + if (right[key] !== value) { + return false; + } + } + return true; +} + +function projectOrdersEqual(left: readonly ProjectId[], right: readonly ProjectId[]): boolean { + return ( + left.length === right.length && left.every((projectId, index) => projectId === right[index]) + ); +} + +export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState { + const previousProjectCwdById = new Map(currentProjectCwdById); + const previousProjectIdByCwd = new Map( + [...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const), + ); + currentProjectCwdById.clear(); + for (const project of projects) { + currentProjectCwdById.set(project.id, project.cwd); + } + const cwdMappingChanged = + previousProjectCwdById.size !== currentProjectCwdById.size || + projects.some((project) => previousProjectCwdById.get(project.id) !== project.cwd); + + const nextExpandedById: Record = {}; + const previousExpandedById = state.projectExpandedById; + const persistedOrderByCwd = new Map( + persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const), + ); + const mappedProjects = projects.map((project, index) => { + const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd); + const expanded = + previousExpandedById[project.id] ?? + (previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ?? + (persistedExpandedProjectCwds.size > 0 + ? persistedExpandedProjectCwds.has(project.cwd) + : true); + nextExpandedById[project.id] = expanded; + return { + id: project.id, + cwd: project.cwd, + incomingIndex: index, + }; + }); + + const nextProjectOrder = + state.projectOrder.length > 0 + ? (() => { + const nextProjectIdByCwd = new Map( + mappedProjects.map((project) => [project.cwd, project.id] as const), + ); + const usedProjectIds = new Set(); + const orderedProjectIds: ProjectId[] = []; + + for (const projectId of state.projectOrder) { + const matchedProjectId = + (projectId in nextExpandedById ? projectId : undefined) ?? + (() => { + const previousCwd = previousProjectCwdById.get(projectId); + return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined; + })(); + if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) { + continue; + } + usedProjectIds.add(matchedProjectId); + orderedProjectIds.push(matchedProjectId); + } + + for (const project of mappedProjects) { + if (usedProjectIds.has(project.id)) { + continue; + } + orderedProjectIds.push(project.id); + } + + return orderedProjectIds; + })() + : mappedProjects + .map((project) => ({ + id: project.id, + incomingIndex: project.incomingIndex, + orderIndex: + persistedOrderByCwd.get(project.cwd) ?? + persistedProjectOrderCwds.length + project.incomingIndex, + })) + .toSorted((left, right) => { + const byOrder = left.orderIndex - right.orderIndex; + if (byOrder !== 0) { + return byOrder; + } + return left.incomingIndex - right.incomingIndex; + }) + .map((project) => project.id); + + if ( + recordsEqual(state.projectExpandedById, nextExpandedById) && + projectOrdersEqual(state.projectOrder, nextProjectOrder) && + !cwdMappingChanged + ) { + return state; + } + + return { + ...state, + projectExpandedById: nextExpandedById, + projectOrder: nextProjectOrder, + }; +} + +export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState { + const retainedThreadIds = new Set(threads.map((thread) => thread.id)); + const nextThreadLastVisitedAtById = Object.fromEntries( + Object.entries(state.threadLastVisitedAtById).filter(([threadId]) => + retainedThreadIds.has(threadId as ThreadId), + ), + ); + for (const thread of threads) { + if ( + nextThreadLastVisitedAtById[thread.id] === undefined && + thread.seedVisitedAt !== undefined && + thread.seedVisitedAt.length > 0 + ) { + nextThreadLastVisitedAtById[thread.id] = thread.seedVisitedAt; + } + } + if (recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById)) { + return state; + } + return { + ...state, + threadLastVisitedAtById: nextThreadLastVisitedAtById, + }; +} + +export function markThreadVisited(state: UiState, threadId: ThreadId, visitedAt?: string): UiState { + const at = visitedAt ?? new Date().toISOString(); + const visitedAtMs = Date.parse(at); + const previousVisitedAt = state.threadLastVisitedAtById[threadId]; + const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN; + if ( + Number.isFinite(previousVisitedAtMs) && + Number.isFinite(visitedAtMs) && + previousVisitedAtMs >= visitedAtMs + ) { + return state; + } + return { + ...state, + threadLastVisitedAtById: { + ...state.threadLastVisitedAtById, + [threadId]: at, + }, + }; +} + +export function markThreadUnread( + state: UiState, + threadId: ThreadId, + latestTurnCompletedAt: string | null | undefined, +): UiState { + if (!latestTurnCompletedAt) { + return state; + } + const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt); + if (Number.isNaN(latestTurnCompletedAtMs)) { + return state; + } + const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString(); + if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) { + return state; + } + return { + ...state, + threadLastVisitedAtById: { + ...state.threadLastVisitedAtById, + [threadId]: unreadVisitedAt, + }, + }; +} + +export function clearThreadUi(state: UiState, threadId: ThreadId): UiState { + if (!(threadId in state.threadLastVisitedAtById)) { + return state; + } + const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById }; + delete nextThreadLastVisitedAtById[threadId]; + return { + ...state, + threadLastVisitedAtById: nextThreadLastVisitedAtById, + }; +} + +export function toggleProject(state: UiState, projectId: ProjectId): UiState { + const expanded = state.projectExpandedById[projectId] ?? true; + return { + ...state, + projectExpandedById: { + ...state.projectExpandedById, + [projectId]: !expanded, + }, + }; +} + +export function setProjectExpanded( + state: UiState, + projectId: ProjectId, + expanded: boolean, +): UiState { + if ((state.projectExpandedById[projectId] ?? true) === expanded) { + return state; + } + return { + ...state, + projectExpandedById: { + ...state.projectExpandedById, + [projectId]: expanded, + }, + }; +} + +export function reorderProjects( + state: UiState, + draggedProjectId: ProjectId, + targetProjectId: ProjectId, +): UiState { + if (draggedProjectId === targetProjectId) { + return state; + } + const draggedIndex = state.projectOrder.findIndex((projectId) => projectId === draggedProjectId); + const targetIndex = state.projectOrder.findIndex((projectId) => projectId === targetProjectId); + if (draggedIndex < 0 || targetIndex < 0) { + return state; + } + const projectOrder = [...state.projectOrder]; + const [draggedProject] = projectOrder.splice(draggedIndex, 1); + if (!draggedProject) { + return state; + } + projectOrder.splice(targetIndex, 0, draggedProject); + return { + ...state, + projectOrder, + }; +} + +interface UiStateStore extends UiState { + syncProjects: (projects: readonly SyncProjectInput[]) => void; + syncThreads: (threads: readonly SyncThreadInput[]) => void; + markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void; + markThreadUnread: (threadId: ThreadId, latestTurnCompletedAt: string | null | undefined) => void; + clearThreadUi: (threadId: ThreadId) => void; + toggleProject: (projectId: ProjectId) => void; + setProjectExpanded: (projectId: ProjectId, expanded: boolean) => void; + reorderProjects: (draggedProjectId: ProjectId, targetProjectId: ProjectId) => void; +} + +export const useUiStateStore = create((set) => ({ + ...readPersistedState(), + syncProjects: (projects) => set((state) => syncProjects(state, projects)), + syncThreads: (threads) => set((state) => syncThreads(state, threads)), + markThreadVisited: (threadId, visitedAt) => + set((state) => markThreadVisited(state, threadId, visitedAt)), + markThreadUnread: (threadId, latestTurnCompletedAt) => + set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)), + clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)), + toggleProject: (projectId) => set((state) => toggleProject(state, projectId)), + setProjectExpanded: (projectId, expanded) => + set((state) => setProjectExpanded(state, projectId, expanded)), + reorderProjects: (draggedProjectId, targetProjectId) => + set((state) => reorderProjects(state, draggedProjectId, targetProjectId)), +})); + +useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state)); + +if (typeof window !== "undefined") { + window.addEventListener("beforeunload", () => { + debouncedPersistState.flush(); + }); +} From 48fc85e7fe69e3d28c0020adb950ad6b7cf79511 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Mar 2026 15:08:25 -0700 Subject: [PATCH 58/66] Bump Effect catalog dependencies (#1594) --- bun.lock | 22 +++++++++++----------- package.json | 10 +++++----- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/bun.lock b/bun.lock index e13245b727..91cdc8ac97 100644 --- a/bun.lock +++ b/bun.lock @@ -176,13 +176,13 @@ "vite": "^8.0.0", }, "catalog": { - "@effect/language-service": "0.84.1", - "@effect/platform-node": "4.0.0-beta.42", - "@effect/sql-sqlite-bun": "4.0.0-beta.42", - "@effect/vitest": "4.0.0-beta.42", + "@effect/language-service": "0.84.2", + "@effect/platform-node": "4.0.0-beta.43", + "@effect/sql-sqlite-bun": "4.0.0-beta.43", + "@effect/vitest": "4.0.0-beta.43", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", - "effect": "4.0.0-beta.42", + "effect": "4.0.0-beta.43", "tsdown": "^0.20.3", "typescript": "^5.7.3", "vitest": "^4.0.0", @@ -268,15 +268,15 @@ "@dnd-kit/utilities": ["@dnd-kit/utilities@3.2.2", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="], - "@effect/language-service": ["@effect/language-service@0.84.1", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-YUqjJU24HeYgPV453cR2fDqkZ+zZKMuxGnmxWAPscWJ6gt6FB7JZohMCOczRTIOGPrQMcloJX7BjCaPu+RNhpw=="], + "@effect/language-service": ["@effect/language-service@0.84.2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="], - "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.42", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.42", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42", "ioredis": "^5.7.0" } }, "sha512-kbdRML2FBa4q8U8rZQcnmLKZ5zN/z1bAA7t5D1/UsBHZqJgnfRgu1CP6kaEfb1Nie6YyaWshxTktZQryjvW/Yg=="], + "@effect/platform-node": ["@effect/platform-node@4.0.0-beta.43", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43", "ioredis": "^5.7.0" } }, "sha512-Uq6E1rjaIpjHauzjwoB2HzAg3battYt2Boy8XO50GoHiWCXKE6WapYZ0/AnaBx5v5qg2sOfqpuiLsUf9ZgxOkA=="], - "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.42", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-PC+lxLsrwob3+nBChAPrQq32olCeyApgXBvs1NrRsoArLViNT76T/68CttuCAksCZj5e1bZ1ZibLPel3vUmx2g=="], + "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-beta.43", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-A9q0GEb61pYcQ06Dr6gXj1nKlDI3KHsar1sk3qb1ZY+kVSR64tBAylI8zGon23KY+NPtTUj/sEIToB7jc3Qt5w=="], - "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.42", "", { "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-Ah2QfkeV+I9r5OBVJijSDnFXCv51giBXngSwhju5gefc0uWiM3G1tsYAqrNX24HlvFFEnOAZqNf/Sq1h4NqOAA=="], + "@effect/sql-sqlite-bun": ["@effect/sql-sqlite-bun@4.0.0-beta.43", "", { "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-Ryb7x0rBjW5NHegbzvz9y2Yv4KpwZ1UiPk7/Rv+Mkux74Qkjdmotmrvy9P+M5A9TZyL2Av+GpaLTPJKsL0PG+Q=="], - "@effect/vitest": ["@effect/vitest@4.0.0-beta.42", "", { "peerDependencies": { "effect": "^4.0.0-beta.42", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-/11arjUnCRhIrBRvOn/nrbg5p/FadjAPvStddZlpl1VrCxtB2s0n39cbG9uTyDdf1ZrRBG73Upo1ZDF1CTWy8w=="], + "@effect/vitest": ["@effect/vitest@4.0.0-beta.43", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-XN2LAwiUWPqbV2jrsYYRjrVydQ8MIgwr83MVImtUaOQco4vk43+8OHlXQMRN/u2HnGK29KT+O2yTMMBdk2Q6Sw=="], "@electron/get": ["@electron/get@2.0.3", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="], @@ -1020,7 +1020,7 @@ "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], - "effect": ["effect@4.0.0-beta.42", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-c1UrRP+tLzyHb4Fepl8XBDJlLQLkrcMXrRBba441GQRxMbeQ/aIOSFcBwSda1iMJ5l9F0lYc3Bhe33/whrmavQ=="], + "effect": ["effect@4.0.0-beta.43", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="], "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], diff --git a/package.json b/package.json index 6f14f7b77f..aad78f7d4b 100644 --- a/package.json +++ b/package.json @@ -8,11 +8,11 @@ "scripts" ], "catalog": { - "effect": "4.0.0-beta.42", - "@effect/platform-node": "4.0.0-beta.42", - "@effect/sql-sqlite-bun": "4.0.0-beta.42", - "@effect/vitest": "4.0.0-beta.42", - "@effect/language-service": "0.84.1", + "effect": "4.0.0-beta.43", + "@effect/platform-node": "4.0.0-beta.43", + "@effect/sql-sqlite-bun": "4.0.0-beta.43", + "@effect/vitest": "4.0.0-beta.43", + "@effect/language-service": "0.84.2", "@types/bun": "^1.3.9", "@types/node": "^24.10.13", "tsdown": "^0.20.3", From d303ac39cbd97a94489b460f62eac153ad1857ad Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Mon, 30 Mar 2026 23:17:33 -0700 Subject: [PATCH 59/66] Replace wait-on with internal desktop resource polling (#1600) --- apps/desktop/package.json | 3 +- apps/desktop/scripts/dev-electron.mjs | 8 +- apps/desktop/scripts/wait-for-resources.mjs | 119 ++++++++++++++++++++ bun.lock | 63 ----------- 4 files changed, 125 insertions(+), 68 deletions(-) create mode 100644 apps/desktop/scripts/wait-for-resources.mjs diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 7ecb81c791..dfa3bde2f8 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -24,8 +24,7 @@ "@types/node": "catalog:", "tsdown": "catalog:", "typescript": "catalog:", - "vitest": "catalog:", - "wait-on": "^8.0.2" + "vitest": "catalog:" }, "productName": "T3 Code (Alpha)" } diff --git a/apps/desktop/scripts/dev-electron.mjs b/apps/desktop/scripts/dev-electron.mjs index 12d4753509..1506d80e9f 100644 --- a/apps/desktop/scripts/dev-electron.mjs +++ b/apps/desktop/scripts/dev-electron.mjs @@ -1,9 +1,9 @@ import { spawn, spawnSync } from "node:child_process"; import { watch } from "node:fs"; import { join } from "node:path"; -import waitOn from "wait-on"; import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs"; +import { waitForResources } from "./wait-for-resources.mjs"; const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733); const devServerUrl = `http://localhost:${port}`; @@ -20,8 +20,10 @@ const forcedShutdownTimeoutMs = 1_500; const restartDebounceMs = 120; const childTreeGracePeriodMs = 1_200; -await waitOn({ - resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)], +await waitForResources({ + baseDir: desktopDir, + files: requiredFiles, + tcpPort: port, }); const childEnv = { ...process.env }; diff --git a/apps/desktop/scripts/wait-for-resources.mjs b/apps/desktop/scripts/wait-for-resources.mjs new file mode 100644 index 0000000000..2b0a60c5d9 --- /dev/null +++ b/apps/desktop/scripts/wait-for-resources.mjs @@ -0,0 +1,119 @@ +import * as FileSystem from "node:fs/promises"; +import * as Net from "node:net"; +import * as Path from "node:path"; +import * as Timers from "node:timers/promises"; + +const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"]; + +async function fileExists(filePath) { + try { + await FileSystem.access(filePath); + return true; + } catch { + return false; + } +} + +function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) { + return new Promise((resolveReady) => { + const socket = Net.createConnection({ host, port }); + let settled = false; + + const finish = (ready) => { + if (settled) { + return; + } + + settled = true; + socket.removeAllListeners(); + socket.destroy(); + resolveReady(ready); + }; + + socket.once("connect", () => { + finish(true); + }); + socket.once("timeout", () => { + finish(false); + }); + socket.once("error", () => { + finish(false); + }); + socket.setTimeout(connectTimeoutMs); + }); +} + +async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) { + const pendingFiles = []; + + for (const relativeFilePath of files) { + const ready = await fileExists(Path.resolve(baseDir, relativeFilePath)); + if (!ready) { + pendingFiles.push(relativeFilePath); + } + } + + let tcpReady = false; + for (const host of tcpHosts) { + tcpReady = await tcpPortIsReady({ + host, + port: tcpPort, + connectTimeoutMs, + }); + if (tcpReady) { + break; + } + } + + return { + pendingFiles, + tcpReady, + }; +} + +export async function waitForResources({ + baseDir, + files = [], + intervalMs = 100, + timeoutMs = 120_000, + tcpHost, + tcpPort, + connectTimeoutMs = 500, +}) { + if (!Number.isInteger(tcpPort) || tcpPort <= 0) { + throw new TypeError("waitForResources requires a positive integer tcpPort"); + } + + const startedAt = Date.now(); + const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts; + + while (true) { + const { pendingFiles, tcpReady } = await resolvePendingResources({ + baseDir, + files, + tcpPort, + tcpHosts, + connectTimeoutMs, + }); + + if (pendingFiles.length === 0 && tcpReady) { + return; + } + + if (Date.now() - startedAt >= timeoutMs) { + const pendingResources = []; + if (!tcpReady) { + pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`); + } + for (const filePath of pendingFiles) { + pendingResources.push(`file:${filePath}`); + } + + throw new Error( + `Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`, + ); + } + + await Timers.setTimeout(intervalMs); + } +} diff --git a/bun.lock b/bun.lock index 91cdc8ac97..ee56cd52de 100644 --- a/bun.lock +++ b/bun.lock @@ -27,7 +27,6 @@ "tsdown": "catalog:", "typescript": "catalog:", "vitest": "catalog:", - "wait-on": "^8.0.2", }, }, "apps/marketing": { @@ -364,18 +363,6 @@ "@formkit/auto-animate": ["@formkit/auto-animate@0.9.0", "", {}, "sha512-VhP4zEAacXS3dfTpJpJ88QdLqMTcabMg0jwpOSxZ/VzfQVfl3GkZSCZThhGC5uhq/TxPHPzW0dzr4H9Bb1OgKA=="], - "@hapi/address": ["@hapi/address@5.1.1", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-A+po2d/dVoY7cYajycYI43ZbYMXukuopIsqCjh5QzsBCipDtdofHntljDlpccMjIfTy6UOkg+5KPriwYch2bXA=="], - - "@hapi/formula": ["@hapi/formula@3.0.2", "", {}, "sha512-hY5YPNXzw1He7s0iqkRQi+uMGh383CGdyyIGYtB+W5N3KHPXoqychklvHhKCC9M3Xtv0OCs/IHw+r4dcHtBYWw=="], - - "@hapi/hoek": ["@hapi/hoek@11.0.7", "", {}, "sha512-HV5undWkKzcB4RZUusqOpcgxOaq6VOAH7zhhIr2g3G8NF/MlFO75SjOr2NfuSx0Mh40+1FqCkagKLJRykUWoFQ=="], - - "@hapi/pinpoint": ["@hapi/pinpoint@2.0.1", "", {}, "sha512-EKQmr16tM8s16vTT3cA5L0kZZcTMU5DUOZTuvpnY738m+jyP3JIUj+Mm1xc1rsLkGBQ/gVnfKYPwOmPg1tUR4Q=="], - - "@hapi/tlds": ["@hapi/tlds@1.1.6", "", {}, "sha512-xdi7A/4NZokvV0ewovme3aUO5kQhW9pQ2YD1hRqZGhhSi5rBv4usHYidVocXSi9eihYsznZxLtAiEYYUL6VBGw=="], - - "@hapi/topo": ["@hapi/topo@6.0.2", "", { "dependencies": { "@hapi/hoek": "^11.0.2" } }, "sha512-KR3rD5inZbGMrHmgPxsJ9dbi6zEK+C3ZwUwTa+eMwWLz7oijWUTWD2pMSNNYJAU6Qq+65NkxXjqHr/7LM2Xkqg=="], - "@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="], "@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="], @@ -864,10 +851,6 @@ "astro": ["astro@6.0.5", "", { "dependencies": { "@astrojs/compiler": "^3.0.0", "@astrojs/internal-helpers": "0.8.0", "@astrojs/markdown-remark": "7.0.0", "@astrojs/telemetry": "3.3.0", "@capsizecss/unpack": "^4.0.0", "@clack/prompts": "^1.0.1", "@oslojs/encoding": "^1.1.0", "@rollup/pluginutils": "^5.3.0", "aria-query": "^5.3.2", "axobject-query": "^4.1.0", "ci-info": "^4.4.0", "clsx": "^2.1.1", "common-ancestor-path": "^2.0.0", "cookie": "^1.1.1", "devalue": "^5.6.3", "diff": "^8.0.3", "dlv": "^1.1.3", "dset": "^3.1.4", "es-module-lexer": "^2.0.0", "esbuild": "^0.27.3", "flattie": "^1.1.1", "fontace": "~0.4.1", "github-slugger": "^2.0.0", "html-escaper": "3.0.3", "http-cache-semantics": "^4.2.0", "js-yaml": "^4.1.1", "magic-string": "^0.30.21", "magicast": "^0.5.2", "mrmime": "^2.0.1", "neotraverse": "^0.6.18", "obug": "^2.1.1", "p-limit": "^7.3.0", "p-queue": "^9.1.0", "package-manager-detector": "^1.6.0", "piccolore": "^0.1.3", "picomatch": "^4.0.3", "rehype": "^13.0.2", "semver": "^7.7.4", "shiki": "^4.0.0", "smol-toml": "^1.6.0", "svgo": "^4.0.0", "tinyclip": "^0.1.6", "tinyexec": "^1.0.2", "tinyglobby": "^0.2.15", "tsconfck": "^3.1.6", "ultrahtml": "^1.6.0", "unifont": "~0.7.4", "unist-util-visit": "^5.1.0", "unstorage": "^1.17.4", "vfile": "^6.0.3", "vite": "^7.3.1", "vitefu": "^1.1.2", "xxhash-wasm": "^1.1.0", "yargs-parser": "^22.0.0", "zod": "^4.3.6" }, "optionalDependencies": { "sharp": "^0.34.0" }, "bin": { "astro": "bin/astro.mjs" } }, "sha512-JnLCwaoCaRXIHuIB8yNztJrd7M3hXrHUMAoQmeXtEBKxRu/738REhaCZ1lapjrS9HlpHsWTu3JUXTERB/0PA7g=="], - "asynckit": ["asynckit@0.4.0", "", {}, "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="], - - "axios": ["axios@1.13.6", "", { "dependencies": { "follow-redirects": "^1.15.11", "form-data": "^4.0.5", "proxy-from-env": "^1.1.0" } }, "sha512-ChTCHMouEe2kn713WHbQGcuYrr6fXTBiu460OTwWrWob16g1bXn4vtz07Ope7ewMozJAnEquLk5lWQWtBig9DQ=="], - "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], @@ -904,8 +887,6 @@ "cacheable-request": ["cacheable-request@7.0.4", "", { "dependencies": { "clone-response": "^1.0.2", "get-stream": "^5.1.0", "http-cache-semantics": "^4.0.0", "keyv": "^4.0.0", "lowercase-keys": "^2.0.0", "normalize-url": "^6.0.1", "responselike": "^2.0.0" } }, "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg=="], - "call-bind-apply-helpers": ["call-bind-apply-helpers@1.0.2", "", { "dependencies": { "es-errors": "^1.3.0", "function-bind": "^1.1.2" } }, "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ=="], - "caniuse-lite": ["caniuse-lite@1.0.30001779", "", {}, "sha512-U5og2PN7V4DMgF50YPNtnZJGWVLFjjsN3zb6uMT5VGYIewieDj1upwfuVNXf4Kor+89c3iCRJnSzMD5LmTvsfA=="], "ccount": ["ccount@2.0.1", "", {}, "sha512-eyrF0jiFpY+3drT6383f1qhkbGsLSifNAjA61IUjZjmLCWjItY6LB9ft9YhoDgwfmclB2zhu51Lc7+95b8NRAg=="], @@ -940,8 +921,6 @@ "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], - "combined-stream": ["combined-stream@1.0.8", "", { "dependencies": { "delayed-stream": "~1.0.0" } }, "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg=="], - "comma-separated-tokens": ["comma-separated-tokens@2.0.3", "", {}, "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg=="], "commander": ["commander@11.1.0", "", {}, "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ=="], @@ -986,8 +965,6 @@ "defu": ["defu@6.1.4", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="], - "delayed-stream": ["delayed-stream@1.0.0", "", {}, "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ=="], - "denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="], "dequal": ["dequal@2.0.3", "", {}, "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA=="], @@ -1018,8 +995,6 @@ "dts-resolver": ["dts-resolver@2.1.3", "", { "peerDependencies": { "oxc-resolver": ">=11.0.0" }, "optionalPeers": ["oxc-resolver"] }, "sha512-bihc7jPC90VrosXNzK0LTE2cuLP6jr0Ro8jk+kMugHReJVLIpHz/xadeq3MhuwyO4TD4OA3L1Q8pBBFRc08Tsw=="], - "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], - "effect": ["effect@4.0.0-beta.43", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="], "electron": ["electron@40.6.0", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="], @@ -1048,10 +1023,6 @@ "es-module-lexer": ["es-module-lexer@2.0.0", "", {}, "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw=="], - "es-object-atoms": ["es-object-atoms@1.1.1", "", { "dependencies": { "es-errors": "^1.3.0" } }, "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA=="], - - "es-set-tostringtag": ["es-set-tostringtag@2.1.0", "", { "dependencies": { "es-errors": "^1.3.0", "get-intrinsic": "^1.2.6", "has-tostringtag": "^1.0.2", "hasown": "^2.0.2" } }, "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA=="], - "es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="], "esbuild": ["esbuild@0.27.4", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.4", "@esbuild/android-arm": "0.27.4", "@esbuild/android-arm64": "0.27.4", "@esbuild/android-x64": "0.27.4", "@esbuild/darwin-arm64": "0.27.4", "@esbuild/darwin-x64": "0.27.4", "@esbuild/freebsd-arm64": "0.27.4", "@esbuild/freebsd-x64": "0.27.4", "@esbuild/linux-arm": "0.27.4", "@esbuild/linux-arm64": "0.27.4", "@esbuild/linux-ia32": "0.27.4", "@esbuild/linux-loong64": "0.27.4", "@esbuild/linux-mips64el": "0.27.4", "@esbuild/linux-ppc64": "0.27.4", "@esbuild/linux-riscv64": "0.27.4", "@esbuild/linux-s390x": "0.27.4", "@esbuild/linux-x64": "0.27.4", "@esbuild/netbsd-arm64": "0.27.4", "@esbuild/netbsd-x64": "0.27.4", "@esbuild/openbsd-arm64": "0.27.4", "@esbuild/openbsd-x64": "0.27.4", "@esbuild/openharmony-arm64": "0.27.4", "@esbuild/sunos-x64": "0.27.4", "@esbuild/win32-arm64": "0.27.4", "@esbuild/win32-ia32": "0.27.4", "@esbuild/win32-x64": "0.27.4" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-Rq4vbHnYkK5fws5NF7MYTU68FPRE1ajX7heQ/8QXXWqNgqqJ/GkmmyxIzUnf2Sr/bakf8l54716CcMGHYhMrrQ=="], @@ -1090,28 +1061,18 @@ "flattie": ["flattie@1.1.1", "", {}, "sha512-9UbaD6XdAL97+k/n+N7JwX46K/M6Zc6KcFYskrYL8wbBV/Uyk0CTAMY0VT+qiK5PM7AIc9aTWYtq65U7T+aCNQ=="], - "follow-redirects": ["follow-redirects@1.15.11", "", {}, "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ=="], - "fontace": ["fontace@0.4.1", "", { "dependencies": { "fontkitten": "^1.0.2" } }, "sha512-lDMvbAzSnHmbYMTEld5qdtvNH2/pWpICOqpean9IgC7vUbUJc3k+k5Dokp85CegamqQpFbXf0rAVkbzpyTA8aw=="], "fontkitten": ["fontkitten@1.0.3", "", { "dependencies": { "tiny-inflate": "^1.0.3" } }, "sha512-Wp1zXWPVUPBmfoa3Cqc9ctaKuzKAV6uLstRqlR56kSjplf5uAce+qeyYym7F+PHbGTk+tCEdkCW6RD7DX/gBZw=="], - "form-data": ["form-data@4.0.5", "", { "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", "hasown": "^2.0.2", "mime-types": "^2.1.12" } }, "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w=="], - "fs-extra": ["fs-extra@10.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-oRXApq54ETRj4eMiFzGnHWGy+zo5raudjuxN0b8H7s/RU2oW0Wvsx9O0ACRN/kRq9E8Vu/ReskGB5o3ji+FzHQ=="], "fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="], - "function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="], - "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], - "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], - - "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], - "get-stream": ["get-stream@5.2.0", "", { "dependencies": { "pump": "^3.0.0" } }, "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA=="], "get-tsconfig": ["get-tsconfig@4.13.6", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-shZT/QMiSHc/YBLxxOkMtgSid5HFoauqCE3/exfsEcwg1WkeqjG+V40yBbBrsD+jW2HDXcs28xOfcbm2jI8Ddw=="], @@ -1136,12 +1097,6 @@ "has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="], - "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], - - "has-tostringtag": ["has-tostringtag@1.0.2", "", { "dependencies": { "has-symbols": "^1.0.3" } }, "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw=="], - - "hasown": ["hasown@2.0.2", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ=="], - "hast-util-from-html": ["hast-util-from-html@2.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "devlop": "^1.1.0", "hast-util-from-parse5": "^8.0.0", "parse5": "^7.0.0", "vfile": "^6.0.0", "vfile-message": "^4.0.0" } }, "sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw=="], "hast-util-from-parse5": ["hast-util-from-parse5@8.0.3", "", { "dependencies": { "@types/hast": "^3.0.0", "@types/unist": "^3.0.0", "devlop": "^1.0.0", "hastscript": "^9.0.0", "property-information": "^7.0.0", "vfile": "^6.0.0", "vfile-location": "^5.0.0", "web-namespaces": "^2.0.0" } }, "sha512-3kxEVkEKt0zvcZ3hCRYI8rqrgwtlIOFMWkbclACvjlDw8Li9S2hk/d51OI0nr/gIpdMHNepwgOKqZ/sy0Clpyg=="], @@ -1222,8 +1177,6 @@ "jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="], - "joi": ["joi@18.0.2", "", { "dependencies": { "@hapi/address": "^5.1.1", "@hapi/formula": "^3.0.2", "@hapi/hoek": "^11.0.7", "@hapi/pinpoint": "^2.0.1", "@hapi/tlds": "^1.1.1", "@hapi/topo": "^6.0.2", "@standard-schema/spec": "^1.0.0" } }, "sha512-RuCOQMIt78LWnktPoeBL0GErkNaJPTBGcYuyaBvUOQSpcpcLfWrHPPihYdOGbV5pam9VTWbeoF7TsGiHugcjGA=="], - "js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], "js-yaml": ["js-yaml@4.1.1", "", { "dependencies": { "argparse": "^2.0.1" }, "bin": { "js-yaml": "bin/js-yaml.js" } }, "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA=="], @@ -1278,8 +1231,6 @@ "lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="], - "lodash": ["lodash@4.17.23", "", {}, "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w=="], - "lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="], "lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="], @@ -1306,8 +1257,6 @@ "matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="], - "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], - "mdast-util-definitions": ["mdast-util-definitions@6.0.0", "", { "dependencies": { "@types/mdast": "^4.0.0", "@types/unist": "^3.0.0", "unist-util-visit": "^5.0.0" } }, "sha512-scTllyX6pnYNZH/AIp/0ePz6s4cZtARxImwoPJ7kS42n+MnVsI4XbnG6d4ibehRIldYMWM2LD7ImQblVhUejVQ=="], "mdast-util-find-and-replace": ["mdast-util-find-and-replace@3.0.2", "", { "dependencies": { "@types/mdast": "^4.0.0", "escape-string-regexp": "^5.0.0", "unist-util-is": "^6.0.0", "unist-util-visit-parents": "^6.0.0" } }, "sha512-Tmd1Vg/m3Xz43afeNxDIhWRtFZgM2VLyaf4vSTYwudTyeuTneoL3qtWMA5jeLyz/O1vDJmmV4QuScFCA2tBPwg=="], @@ -1400,14 +1349,8 @@ "mime": ["mime@4.1.0", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="], - "mime-db": ["mime-db@1.52.0", "", {}, "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg=="], - - "mime-types": ["mime-types@2.1.35", "", { "dependencies": { "mime-db": "1.52.0" } }, "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw=="], - "mimic-response": ["mimic-response@3.1.0", "", {}, "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="], - "minimist": ["minimist@1.2.8", "", {}, "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA=="], - "mrmime": ["mrmime@2.0.1", "", {}, "sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], @@ -1516,8 +1459,6 @@ "property-information": ["property-information@7.1.0", "", {}, "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ=="], - "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], - "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], "pure-rand": ["pure-rand@8.1.0", "", {}, "sha512-53B3MB8wetRdD6JZ4W/0gDKaOvKwuXrEmV1auQc0hASWge8rieKV4PCCVNVbJ+i24miiubb4c/B+dg8Ho0ikYw=="], @@ -1600,8 +1541,6 @@ "run-applescript": ["run-applescript@7.1.0", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="], - "rxjs": ["rxjs@7.8.2", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="], - "sax": ["sax@1.5.0", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="], "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], @@ -1840,8 +1779,6 @@ "vscode-uri": ["vscode-uri@3.1.0", "", {}, "sha512-/BpdSx+yCQGnCvecbyXdxHDkuk55/G3xwnC0GqY4gmQ3j+A+g8kzzgB4Nk/SINjqn6+waqw3EgbVF2QKExkRxQ=="], - "wait-on": ["wait-on@8.0.5", "", { "dependencies": { "axios": "^1.12.1", "joi": "^18.0.1", "lodash": "^4.17.21", "minimist": "^1.2.8", "rxjs": "^7.8.2" }, "bin": { "wait-on": "bin/wait-on" } }, "sha512-J3WlS0txVHkhLRb2FsmRg3dkMTCV1+M6Xra3Ho7HzZDHpE7DCOnoSoCJsZotrmW3uRMhvIJGSKUKrh/MeF4iag=="], - "web-namespaces": ["web-namespaces@2.0.1", "", {}, "sha512-bKr1DkiNa2krS7qxNtdrtHAmzuYGFQLiQ13TsorsdT6ULTkPLKuu5+GsFpDlg6JFjUTwX2DyhMPG2be8uPrqsQ=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], From 2d03847ccd53ffcd5ba74301ce85aef2afe58ad5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 31 Mar 2026 00:08:51 -0700 Subject: [PATCH 60/66] Extract project/workspace related functionality to Effect services (#1524) --- .../OrchestrationEngineHarness.integration.ts | 7 + apps/server/src/git/Layers/GitCore.test.ts | 90 ++- apps/server/src/git/Layers/GitCore.ts | 160 ++++- apps/server/src/git/Services/GitCore.ts | 28 + .../Layers/CheckpointReactor.test.ts | 5 +- .../orchestration/Layers/CheckpointReactor.ts | 7 +- .../Layers/ProjectFaviconResolver.test.ts | 74 +++ .../project/Layers/ProjectFaviconResolver.ts | 129 ++++ .../Services/ProjectFaviconResolver.ts | 30 + apps/server/src/projectFaviconRoute.test.ts | 28 +- apps/server/src/projectFaviconRoute.ts | 211 ++----- apps/server/src/serverLayers.ts | 25 +- .../workspace/Layers/WorkspaceEntries.test.ts | 264 ++++++++ .../src/workspace/Layers/WorkspaceEntries.ts | 478 +++++++++++++++ .../Layers/WorkspaceFileSystem.test.ts | 135 +++++ .../workspace/Layers/WorkspaceFileSystem.ts | 55 ++ .../workspace/Layers/WorkspacePaths.test.ts | 113 ++++ .../src/workspace/Layers/WorkspacePaths.ts | 89 +++ .../workspace/Services/WorkspaceEntries.ts | 48 ++ .../workspace/Services/WorkspaceFileSystem.ts | 50 ++ .../src/workspace/Services/WorkspacePaths.ts | 85 +++ .../src/workspaceEntries.chunking.test.ts | 81 --- apps/server/src/workspaceEntries.test.ts | 202 ------- apps/server/src/workspaceEntries.ts | 565 ------------------ apps/server/src/wsServer.test.ts | 144 ++++- apps/server/src/wsServer.ts | 118 +--- 26 files changed, 2079 insertions(+), 1142 deletions(-) create mode 100644 apps/server/src/project/Layers/ProjectFaviconResolver.test.ts create mode 100644 apps/server/src/project/Layers/ProjectFaviconResolver.ts create mode 100644 apps/server/src/project/Services/ProjectFaviconResolver.ts create mode 100644 apps/server/src/workspace/Layers/WorkspaceEntries.test.ts create mode 100644 apps/server/src/workspace/Layers/WorkspaceEntries.ts create mode 100644 apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts create mode 100644 apps/server/src/workspace/Layers/WorkspaceFileSystem.ts create mode 100644 apps/server/src/workspace/Layers/WorkspacePaths.test.ts create mode 100644 apps/server/src/workspace/Layers/WorkspacePaths.ts create mode 100644 apps/server/src/workspace/Services/WorkspaceEntries.ts create mode 100644 apps/server/src/workspace/Services/WorkspaceFileSystem.ts create mode 100644 apps/server/src/workspace/Services/WorkspacePaths.ts delete mode 100644 apps/server/src/workspaceEntries.chunking.test.ts delete mode 100644 apps/server/src/workspaceEntries.test.ts delete mode 100644 apps/server/src/workspaceEntries.ts diff --git a/apps/server/integration/OrchestrationEngineHarness.integration.ts b/apps/server/integration/OrchestrationEngineHarness.integration.ts index e66a214fb7..9340b9460d 100644 --- a/apps/server/integration/OrchestrationEngineHarness.integration.ts +++ b/apps/server/integration/OrchestrationEngineHarness.integration.ts @@ -68,6 +68,7 @@ import { type TestProviderAdapterHarness, } from "./TestProviderAdapter.integration.ts"; import { deriveServerPaths, ServerConfig } from "../src/config.ts"; +import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts"; function runGit(cwd: string, args: ReadonlyArray) { return execFileSync("git", args, { @@ -317,6 +318,12 @@ export const makeOrchestrationIntegrationHarness = ( ); const checkpointReactorLayer = CheckpointReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge( + WorkspaceEntriesLive.pipe( + Layer.provideMerge(gitCoreLayer), + Layer.provide(NodeServices.layer), + ), + ), ); const orchestrationReactorLayer = OrchestrationReactorLive.pipe( Layer.provideMerge(runtimeIngestionLayer), diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 547a69e7e1..135834f891 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -138,6 +138,13 @@ function buildLargeText(lineCount = 20_000): string { .concat("\n"); } +function splitNullSeparatedPaths(input: string): string[] { + return input + .split("\0") + .map((value) => value.trim()) + .filter((value) => value.length > 0); +} + // ── Tests ── it.layer(TestLayer)("git integration", (it) => { @@ -181,6 +188,55 @@ it.layer(TestLayer)("git integration", (it) => { ); }); + describe("workspace helpers", () => { + it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () => + Effect.gen(function* () { + const cwd = "/virtual/repo"; + const relativePaths = Array.from({ length: 340 }, (_, index) => { + const prefix = index % 3 === 0 ? "ignored" : "kept"; + return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`; + }); + const expectedPaths = relativePaths.filter( + (relativePath) => !relativePath.startsWith("ignored/"), + ); + + const seenChunks: string[][] = []; + const core = yield* makeIsolatedGitCore((input) => { + if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") { + return Effect.fail( + new GitCommandError({ + operation: input.operation, + command: `git ${input.args.join(" ")}`, + cwd: input.cwd, + detail: "unexpected git command in chunking test", + }), + ); + } + + const chunkPaths = splitNullSeparatedPaths(input.stdin ?? ""); + seenChunks.push(chunkPaths); + const ignoredPaths = chunkPaths.filter((relativePath) => + relativePath.startsWith("ignored/"), + ); + + return Effect.succeed({ + code: ignoredPaths.length > 0 ? 0 : 1, + stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); + }); + + const result = yield* core.filterIgnoredPaths(cwd, relativePaths); + + expect(seenChunks.length).toBeGreaterThan(1); + expect(seenChunks.flat()).toEqual(relativePaths); + expect(result).toEqual(expectedPaths); + }), + ); + }); + // ── listGitBranches ── describe("listGitBranches", () => { @@ -457,12 +513,18 @@ it.layer(TestLayer)("git integration", (it) => { yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch }); const core = yield* GitCore; yield* Effect.promise(() => - vi.waitFor(async () => { - const details = await runPromise(core.statusDetails(source)); - expect(details.branch).toBe(featureBranch); - expect(details.aheadCount).toBe(0); - expect(details.behindCount).toBe(1); - }), + vi.waitFor( + async () => { + const details = await runPromise(core.statusDetails(source)); + expect(details.branch).toBe(featureBranch); + expect(details.aheadCount).toBe(0); + expect(details.behindCount).toBe(1); + }, + { + timeout: 10_000, + interval: 100, + }, + ), ); }), ); @@ -541,7 +603,13 @@ it.layer(TestLayer)("git integration", (it) => { const core = yield* makeIsolatedGitCore((input) => { if (input.args[0] === "fetch") { fetchArgs = [...input.args]; - return Effect.succeed({ code: 0, stdout: "", stderr: "" }); + return Effect.succeed({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + }); } return realGitCore.execute(input); }); @@ -594,7 +662,13 @@ it.layer(TestLayer)("git integration", (it) => { if (input.args[0] === "fetch") { fetchStarted = true; return Effect.promise(() => - waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })), + waitForReleasePromise.then(() => ({ + code: 0, + stdout: "", + stderr: "", + stdoutTruncated: false, + stderrTruncated: false, + })), ); } return realGitCore.execute(input); diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 64ed409508..81d6cbb549 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -37,6 +37,8 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000; const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000; const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000; +const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; +const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; @@ -55,6 +57,7 @@ class StatusUpstreamRefreshCacheKey extends Data.Class<{ }> {} interface ExecuteGitOptions { + stdin?: string | undefined; timeoutMs?: number | undefined; allowNonZeroExit?: boolean | undefined; fallbackErrorMessage?: string | undefined; @@ -96,6 +99,47 @@ function parseNumstatEntries( return entries; } +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: readonly string[]): string[][] { + const chunks: string[][] = []; + let chunk: string[] = []; + let chunkBytes = 0; + + for (const relativePath of relativePaths) { + const relativePathBytes = Buffer.byteLength(relativePath) + 1; + if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + + chunk.push(relativePath); + chunkBytes += relativePathBytes; + + if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) { + chunks.push(chunk); + chunk = []; + chunkBytes = 0; + } + } + + if (chunk.length > 0) { + chunks.push(chunk); + } + + return chunks; +} + function parsePorcelainPath(line: string): string | null { if (line.startsWith("? ") || line.startsWith("! ")) { const simple = line.slice(2).trim(); @@ -445,7 +489,7 @@ const collectOutput = Effect.fn("collectOutput")(function* ( maxOutputBytes: number, truncateOutputAtMaxBytes: boolean, onLine: ((line: string) => Effect.Effect) | undefined, -): Effect.fn.Return { +): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> { const decoder = new TextDecoder(); let bytes = 0; let text = ""; @@ -507,7 +551,10 @@ const collectOutput = Effect.fn("collectOutput")(function* ( text += remainder; lineBuffer += remainder; yield* emitCompleteLines(true); - return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text; + return { + text, + truncated, + }; }); export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { @@ -571,13 +618,18 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { Effect.map((value) => Number(value)), Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")), ), + input.stdin === undefined + ? Effect.void + : Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe( + Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")), + ), ], { concurrency: "unbounded" }, - ); + ).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const)); yield* trace2Monitor.flush; if (!input.allowNonZeroExit && exitCode !== 0) { - const trimmedStderr = stderr.trim(); + const trimmedStderr = stderr.text.trim(); return yield* new GitCommandError({ operation: commandInput.operation, command: quoteGitCommand(commandInput.args), @@ -589,7 +641,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { }); } - return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult; + return { + code: exitCode, + stdout: stdout.text, + stderr: stderr.text, + stdoutTruncated: stdout.truncated, + stderrTruncated: stderr.truncated, + } satisfies ExecuteGitResult; }); return yield* runGitCommand().pipe( @@ -618,11 +676,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { cwd: string, args: readonly string[], options: ExecuteGitOptions = {}, - ): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> => + ): Effect.Effect => execute({ operation, cwd, args, + ...(options.stdin !== undefined ? { stdin: options.stdin } : {}), allowNonZeroExit: true, ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}), ...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}), @@ -679,7 +738,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { args: readonly string[], options: ExecuteGitOptions = {}, ): Effect.Effect => - executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout)); + executeGit(operation, cwd, args, options).pipe( + Effect.map((result) => + result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout, + ), + ); const branchExists = (cwd: string, branch: string): Effect.Effect => executeGit( @@ -1416,6 +1479,86 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)), ); + const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) => + executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], { + allowNonZeroExit: true, + timeoutMs: 5_000, + maxOutputBytes: 4_096, + }).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true")); + + const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) => + executeGit( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + { + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ).pipe( + Effect.flatMap((result) => + result.code === 0 + ? Effect.succeed({ + paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated), + truncated: result.stdoutTruncated, + }) + : Effect.fail( + createGitCommandError( + "GitCore.listWorkspaceFiles", + cwd, + ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed", + ), + ), + ), + ); + + const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) => + Effect.gen(function* () { + if (relativePaths.length === 0) { + return relativePaths; + } + + const ignoredPaths = new Set(); + const chunks = chunkPathsForGitCheckIgnore(relativePaths); + + for (const chunk of chunks) { + const result = yield* executeGit( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + { + stdin: `${chunk.join("\0")}\0`, + allowNonZeroExit: true, + timeoutMs: 20_000, + maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES, + truncateOutputAtMaxBytes: true, + }, + ); + + if (result.code !== 0 && result.code !== 1) { + return yield* createGitCommandError( + "GitCore.filterIgnoredPaths", + cwd, + ["check-ignore", "--no-index", "-z", "--stdin"], + result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed", + ); + } + + for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) { + ignoredPaths.add(ignoredPath); + } + } + + if (ignoredPaths.size === 0) { + return relativePaths; + } + + return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); + }); + const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) { const branchRecencyPromise = readBranchRecency(input.cwd).pipe( Effect.catch(() => Effect.succeed(new Map())), @@ -1834,6 +1977,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { pullCurrentBranch, readRangeContext, readConfigValue, + isInsideWorkTree, + listWorkspaceFiles, + filterIgnoredPaths, listBranches, createWorktree, fetchPullRequestBranch, diff --git a/apps/server/src/git/Services/GitCore.ts b/apps/server/src/git/Services/GitCore.ts index f1a4e065cd..3c30f17121 100644 --- a/apps/server/src/git/Services/GitCore.ts +++ b/apps/server/src/git/Services/GitCore.ts @@ -28,6 +28,7 @@ export interface ExecuteGitInput { readonly operation: string; readonly cwd: string; readonly args: ReadonlyArray; + readonly stdin?: string; readonly env?: NodeJS.ProcessEnv; readonly allowNonZeroExit?: boolean; readonly timeoutMs?: number; @@ -40,6 +41,8 @@ export interface ExecuteGitResult { readonly code: number; readonly stdout: string; readonly stderr: string; + readonly stdoutTruncated: boolean; + readonly stderrTruncated: boolean; } export interface GitStatusDetails extends Omit { @@ -93,6 +96,11 @@ export interface GitRangeContext { diffPatch: string; } +export interface GitListWorkspaceFilesResult { + readonly paths: ReadonlyArray; + readonly truncated: boolean; +} + export interface GitRenameBranchInput { cwd: string; oldBranch: string; @@ -190,6 +198,26 @@ export interface GitCoreShape { key: string, ) => Effect.Effect; + /** + * Determine whether the provided cwd is inside a git work tree. + */ + readonly isInsideWorkTree: (cwd: string) => Effect.Effect; + + /** + * List tracked and untracked workspace file paths relative to cwd. + */ + readonly listWorkspaceFiles: ( + cwd: string, + ) => Effect.Effect; + + /** + * Remove gitignored paths from a relative path list. + */ + readonly filterIgnoredPaths: ( + cwd: string, + relativePaths: ReadonlyArray, + ) => Effect.Effect, GitCommandError>; + /** * List local + remote branches and branch metadata. */ diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts index 075f62f889..7c201af375 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts @@ -38,6 +38,7 @@ import { } from "../../provider/Services/ProviderService.ts"; import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts"; import { ServerConfig } from "../../config.ts"; +import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts"; const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value); const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value); @@ -261,7 +262,9 @@ describe("CheckpointReactor", () => { Layer.provideMerge(orchestrationLayer), Layer.provideMerge(RuntimeReceiptBusLive), Layer.provideMerge(Layer.succeed(ProviderService, provider.service)), - Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))), + Layer.provideMerge(CheckpointStoreLive), + Layer.provideMerge(WorkspaceEntriesLive), + Layer.provideMerge(GitCoreLive), Layer.provideMerge(ServerConfigLayer), Layer.provideMerge(NodeServices.layer), ); diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts index 561626b8de..28609cecb3 100644 --- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts +++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts @@ -16,7 +16,6 @@ import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd, } from "../../checkpointing/Utils.ts"; -import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts"; import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts"; import { ProviderService } from "../../provider/Services/ProviderService.ts"; import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts"; @@ -25,6 +24,7 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts"; import { CheckpointStoreError } from "../../checkpointing/Errors.ts"; import { OrchestrationDispatchError } from "../Errors.ts"; import { isGitRepository } from "../../git/Utils.ts"; +import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts"; type ReactorInput = | { @@ -68,6 +68,7 @@ const make = Effect.gen(function* () { const providerService = yield* ProviderService; const checkpointStore = yield* CheckpointStore; const receiptBus = yield* RuntimeReceiptBus; + const workspaceEntries = yield* WorkspaceEntries; const appendRevertFailureActivity = (input: { readonly threadId: ThreadId; @@ -226,7 +227,7 @@ const make = Effect.gen(function* () { // Invalidate the workspace entry cache so the @-mention file picker // reflects files created or deleted during this turn. - clearWorkspaceIndexCache(input.cwd); + yield* workspaceEntries.invalidate(input.cwd); const files = yield* checkpointStore .diffCheckpoints({ @@ -642,7 +643,7 @@ const make = Effect.gen(function* () { // Invalidate the workspace entry cache so the @-mention file picker // reflects the reverted filesystem state. - clearWorkspaceIndexCache(sessionRuntime.value.cwd); + yield* workspaceEntries.invalidate(sessionRuntime.value.cwd); const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount); if (rolledBackTurns > 0) { diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts new file mode 100644 index 0000000000..29b30739b9 --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.test.ts @@ -0,0 +1,74 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts"; +import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectFaviconResolverLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-favicon-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents: string, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => { + describe("resolvePath", () => { + it.effect("prefers well-known favicon files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "favicon.svg", "favicon"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("favicon.svg"); + }), + ); + + it.effect("resolves icon hrefs from project source files", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "index.html", ''); + yield* writeTextFile(cwd, "public/brand/logo.svg", "brand"); + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).not.toBeNull(); + expect(resolved).toContain("public/brand/logo.svg"); + }), + ); + + it.effect("returns null when no icon is present", () => + Effect.gen(function* () { + const resolver = yield* ProjectFaviconResolver; + const cwd = yield* makeTempDir; + + const resolved = yield* resolver.resolvePath(cwd); + + expect(resolved).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/project/Layers/ProjectFaviconResolver.ts b/apps/server/src/project/Layers/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..3004a7a45c --- /dev/null +++ b/apps/server/src/project/Layers/ProjectFaviconResolver.ts @@ -0,0 +1,129 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + ProjectFaviconResolver, + type ProjectFaviconResolverShape, +} from "../Services/ProjectFaviconResolver.ts"; + +// Well-known favicon paths checked in order. +const FAVICON_CANDIDATES = [ + "favicon.svg", + "favicon.ico", + "favicon.png", + "public/favicon.svg", + "public/favicon.ico", + "public/favicon.png", + "app/favicon.ico", + "app/favicon.png", + "app/icon.svg", + "app/icon.png", + "app/icon.ico", + "src/favicon.ico", + "src/favicon.svg", + "src/app/favicon.ico", + "src/app/icon.svg", + "src/app/icon.png", + "assets/icon.svg", + "assets/icon.png", + "assets/logo.svg", + "assets/logo.png", +] as const; + +// Files that may contain a or icon metadata declaration. +const ICON_SOURCE_FILES = [ + "index.html", + "public/index.html", + "app/routes/__root.tsx", + "src/routes/__root.tsx", + "app/root.tsx", + "src/root.tsx", + "src/index.html", +] as const; + +// Matches tags or object-like icon metadata where rel/href can appear in any order. +const LINK_ICON_HTML_RE = + /]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; +const LINK_ICON_OBJ_RE = + /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i; + +function extractIconHref(source: string): string | null { + const htmlMatch = source.match(LINK_ICON_HTML_RE); + if (htmlMatch?.[1]) return htmlMatch[1]; + const objMatch = source.match(LINK_ICON_OBJ_RE); + if (objMatch?.[1]) return objMatch[1]; + return null; +} + +export const makeProjectFaviconResolver = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const resolveIconHref = (projectCwd: string, href: string): string[] => { + const clean = href.replace(/^\//, ""); + return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; + }; + + const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => { + const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath)); + return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); + }; + + const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* ( + projectCwd: string, + candidates: ReadonlyArray, + ): Effect.fn.Return { + for (const candidate of candidates) { + if (!isPathWithinProject(projectCwd, candidate)) { + continue; + } + const stats = yield* fileSystem + .stat(candidate) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (stats?.type === "File") { + return candidate; + } + } + return null; + }); + + const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn( + "ProjectFaviconResolver.resolvePath", + )(function* (cwd: string): Effect.fn.Return { + for (const candidate of FAVICON_CANDIDATES) { + const resolved = path.join(cwd, candidate); + const existing = yield* findExistingFile(cwd, [resolved]); + if (existing) { + return existing; + } + } + + for (const sourceFile of ICON_SOURCE_FILES) { + const sourcePath = path.join(cwd, sourceFile); + const source = yield* fileSystem + .readFileString(sourcePath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!source) { + continue; + } + const href = extractIconHref(source); + if (!href) { + continue; + } + const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href)); + if (existing) { + return existing; + } + } + + return null; + }); + + return { + resolvePath, + } satisfies ProjectFaviconResolverShape; +}); + +export const ProjectFaviconResolverLive = Layer.effect( + ProjectFaviconResolver, + makeProjectFaviconResolver, +); diff --git a/apps/server/src/project/Services/ProjectFaviconResolver.ts b/apps/server/src/project/Services/ProjectFaviconResolver.ts new file mode 100644 index 0000000000..f6a8e22c0d --- /dev/null +++ b/apps/server/src/project/Services/ProjectFaviconResolver.ts @@ -0,0 +1,30 @@ +/** + * ProjectFaviconResolver - Effect service contract for project icon discovery. + * + * Resolves a representative favicon or app icon file for a workspace by + * checking common file locations and project source metadata. + * + * @module ProjectFaviconResolver + */ +import { ServiceMap } from "effect"; +import type { Effect } from "effect"; + +/** + * ProjectFaviconResolverShape - Service API for project favicon lookup. + */ +export interface ProjectFaviconResolverShape { + /** + * Resolve a favicon or icon file path for the provided workspace root. + * + * Returns `null` when no candidate icon file can be found. + */ + readonly resolvePath: (cwd: string) => Effect.Effect; +} + +/** + * ProjectFaviconResolver - Service tag for project favicon resolution. + */ +export class ProjectFaviconResolver extends ServiceMap.Service< + ProjectFaviconResolver, + ProjectFaviconResolverShape +>()("t3/project/Services/ProjectFaviconResolver") {} diff --git a/apps/server/src/projectFaviconRoute.test.ts b/apps/server/src/projectFaviconRoute.test.ts index a346e513eb..99b61aedc9 100644 --- a/apps/server/src/projectFaviconRoute.test.ts +++ b/apps/server/src/projectFaviconRoute.test.ts @@ -3,7 +3,11 @@ import http from "node:http"; import os from "node:os"; import path from "node:path"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { Effect } from "effect"; import { afterEach, describe, expect, it } from "vitest"; + +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute"; interface HttpResponse { @@ -23,11 +27,25 @@ function makeTempDir(prefix: string): string { async function withRouteServer(run: (baseUrl: string) => Promise): Promise { const server = http.createServer((req, res) => { const url = new URL(req.url ?? "/", "http://127.0.0.1"); - if (tryHandleProjectFaviconRequest(url, res)) { - return; - } - res.writeHead(404, { "Content-Type": "text/plain" }); - res.end("Not Found"); + void Effect.runPromise( + tryHandleProjectFaviconRequest(url, res).pipe( + Effect.provide(ProjectFaviconResolverLive), + Effect.provide(NodeServices.layer), + Effect.flatMap((handled) => + handled + ? Effect.void + : Effect.sync(() => { + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + }), + ), + ), + ).catch(() => { + if (!res.headersSent) { + res.writeHead(500, { "Content-Type": "text/plain" }); + res.end("Internal Server Error"); + } + }); }); await new Promise((resolve, reject) => { diff --git a/apps/server/src/projectFaviconRoute.ts b/apps/server/src/projectFaviconRoute.ts index cf234ad894..56a9fc9035 100644 --- a/apps/server/src/projectFaviconRoute.ts +++ b/apps/server/src/projectFaviconRoute.ts @@ -1,6 +1,8 @@ -import fs from "node:fs"; import http from "node:http"; import path from "node:path"; +import { Effect, FileSystem } from "effect"; + +import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts"; const FAVICON_MIME_TYPES: Record = { ".png": "image/png", @@ -11,161 +13,64 @@ const FAVICON_MIME_TYPES: Record = { const FALLBACK_FAVICON_SVG = ``; -// Well-known favicon paths checked in order. -const FAVICON_CANDIDATES = [ - "favicon.svg", - "favicon.ico", - "favicon.png", - "public/favicon.svg", - "public/favicon.ico", - "public/favicon.png", - "app/favicon.ico", - "app/favicon.png", - "app/icon.svg", - "app/icon.png", - "app/icon.ico", - "src/favicon.ico", - "src/favicon.svg", - "src/app/favicon.ico", - "src/app/icon.svg", - "src/app/icon.png", - "assets/icon.svg", - "assets/icon.png", - "assets/logo.svg", - "assets/logo.png", -]; +export const tryHandleProjectFaviconRequest = Effect.fn("tryHandleProjectFaviconRequest")( + function* ( + url: URL, + res: http.ServerResponse, + ): Effect.fn.Return { + const respond = ( + statusCode: number, + headers: Record, + body: string | Uint8Array, + ) => { + res.writeHead(statusCode, headers); + res.end(body); + }; -// Files that may contain a or icon metadata declaration. -const ICON_SOURCE_FILES = [ - "index.html", - "public/index.html", - "app/routes/__root.tsx", - "src/routes/__root.tsx", - "app/root.tsx", - "src/root.tsx", - "src/index.html", -]; - -// Matches tags or object-like icon metadata where rel/href can appear in any order. -const LINK_ICON_HTML_RE = - /]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i; -const LINK_ICON_OBJ_RE = - /(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i; - -function extractIconHref(source: string): string | null { - const htmlMatch = source.match(LINK_ICON_HTML_RE); - if (htmlMatch?.[1]) return htmlMatch[1]; - const objMatch = source.match(LINK_ICON_OBJ_RE); - if (objMatch?.[1]) return objMatch[1]; - return null; -} - -function resolveIconHref(projectCwd: string, href: string): string[] { - const clean = href.replace(/^\//, ""); - return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)]; -} - -function isPathWithinProject(projectCwd: string, candidatePath: string): boolean { - const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath)); - return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)); -} - -function serveFaviconFile(filePath: string, res: http.ServerResponse): void { - const ext = path.extname(filePath).toLowerCase(); - const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream"; - fs.readFile(filePath, (readErr, data) => { - if (readErr) { - res.writeHead(500, { "Content-Type": "text/plain" }); - res.end("Read error"); - return; + if (url.pathname !== "/api/project-favicon") { + return false; } - res.writeHead(200, { - "Content-Type": contentType, - "Cache-Control": "public, max-age=3600", - }); - res.end(data); - }); -} -function serveFallbackFavicon(res: http.ServerResponse): void { - res.writeHead(200, { - "Content-Type": "image/svg+xml", - "Cache-Control": "public, max-age=3600", - }); - res.end(FALLBACK_FAVICON_SVG); -} + const projectCwd = url.searchParams.get("cwd"); + if (!projectCwd) { + respond(400, { "Content-Type": "text/plain" }, "Missing cwd parameter"); + return true; + } -export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean { - if (url.pathname !== "/api/project-favicon") { - return false; - } + const fileSystem = yield* FileSystem.FileSystem; + const faviconResolver = yield* ProjectFaviconResolver; + const resolvedPath = yield* faviconResolver.resolvePath(projectCwd); - const projectCwd = url.searchParams.get("cwd"); - if (!projectCwd) { - res.writeHead(400, { "Content-Type": "text/plain" }); - res.end("Missing cwd parameter"); + if (!resolvedPath) { + respond( + 200, + { + "Content-Type": "image/svg+xml", + "Cache-Control": "public, max-age=3600", + }, + FALLBACK_FAVICON_SVG, + ); + return true; + } + + const data = yield* fileSystem + .readFile(resolvedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!data) { + respond(500, { "Content-Type": "text/plain" }, "Read error"); + return true; + } + + const ext = path.extname(resolvedPath).toLowerCase(); + const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream"; + respond( + 200, + { + "Content-Type": contentType, + "Cache-Control": "public, max-age=3600", + }, + data, + ); return true; - } - - const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => { - if (index >= paths.length) { - onExhausted(); - return; - } - const candidate = paths[index]!; - if (!isPathWithinProject(projectCwd, candidate)) { - tryResolvedPaths(paths, index + 1, onExhausted); - return; - } - fs.stat(candidate, (err, stats) => { - if (err || !stats?.isFile()) { - tryResolvedPaths(paths, index + 1, onExhausted); - return; - } - serveFaviconFile(candidate, res); - }); - }; - - const trySourceFiles = (index: number): void => { - if (index >= ICON_SOURCE_FILES.length) { - serveFallbackFavicon(res); - return; - } - const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!); - fs.readFile(sourceFile, "utf8", (err, content) => { - if (err) { - trySourceFiles(index + 1); - return; - } - const href = extractIconHref(content); - if (!href) { - trySourceFiles(index + 1); - return; - } - const candidates = resolveIconHref(projectCwd, href); - tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1)); - }); - }; - - const tryCandidates = (index: number): void => { - if (index >= FAVICON_CANDIDATES.length) { - trySourceFiles(0); - return; - } - const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!); - if (!isPathWithinProject(projectCwd, candidate)) { - tryCandidates(index + 1); - return; - } - fs.stat(candidate, (err, stats) => { - if (err || !stats?.isFile()) { - tryCandidates(index + 1); - return; - } - serveFaviconFile(candidate, res); - }); - }; - - tryCandidates(0); - return true; -} + }, +); diff --git a/apps/server/src/serverLayers.ts b/apps/server/src/serverLayers.ts index a8c1a13f7f..f745d553a1 100644 --- a/apps/server/src/serverLayers.ts +++ b/apps/server/src/serverLayers.ts @@ -34,6 +34,10 @@ import { GitHubCliLive } from "./git/Layers/GitHubCli"; import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration"; import { PtyAdapter } from "./terminal/Services/PTY"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService"; +import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts"; +import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts"; type RuntimePtyAdapterLoader = { layer: Layer.Layer; @@ -91,7 +95,8 @@ export function makeServerProviderLayer(): Layer.Layer< export function makeServerRuntimeServicesLayer() { const textGenerationLayer = RoutingTextGenerationLive; - const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive)); + const gitCoreLayer = GitCoreLive; + const checkpointStoreLayer = CheckpointStoreLive; const orchestrationLayer = OrchestrationEngineLive.pipe( Layer.provide(OrchestrationProjectionPipelineLive), @@ -116,11 +121,11 @@ export function makeServerRuntimeServicesLayer() { ); const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), - Layer.provideMerge(GitCoreLive), Layer.provideMerge(textGenerationLayer), ); const checkpointReactorLayer = CheckpointReactorLive.pipe( Layer.provideMerge(runtimeServicesLayer), + Layer.provideMerge(WorkspaceEntriesLive), ); const orchestrationReactorLayer = OrchestrationReactorLive.pipe( Layer.provideMerge(runtimeIngestionLayer), @@ -131,16 +136,26 @@ export function makeServerRuntimeServicesLayer() { const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer())); const gitManagerLayer = GitManagerLive.pipe( - Layer.provideMerge(GitCoreLive), Layer.provideMerge(GitHubCliLive), Layer.provideMerge(textGenerationLayer), ); + const workspacePathsLayer = WorkspacePathsLive; + const workspaceEntriesLayer = WorkspaceEntriesLive; + const workspaceFileSystemLayer = WorkspaceFileSystemLive.pipe( + Layer.provide(workspacePathsLayer), + Layer.provide(workspaceEntriesLayer), + ); + const projectFaviconResolverLayer = ProjectFaviconResolverLive; + return Layer.mergeAll( orchestrationReactorLayer, - GitCoreLive, + workspacePathsLayer, + workspaceEntriesLayer, + workspaceFileSystemLayer, + projectFaviconResolverLayer, gitManagerLayer, terminalLayer, KeybindingsLive, - ).pipe(Layer.provideMerge(NodeServices.layer)); + ).pipe(Layer.provideMerge(gitCoreLayer), Layer.provideMerge(NodeServices.layer)); } diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts new file mode 100644 index 0000000000..1d1eb4f0e2 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.test.ts @@ -0,0 +1,264 @@ +import fsPromises from "node:fs/promises"; + +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, afterEach, describe, expect, vi } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path, PlatformError } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { GitCore } from "../../git/Services/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspaceEntriesLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-entries-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn(function* (opts?: { prefix?: string; git?: boolean }) { + const fileSystem = yield* FileSystem.FileSystem; + const gitCore = yield* GitCore; + const dir = yield* fileSystem.makeTempDirectoryScoped({ + prefix: opts?.prefix ?? "t3code-workspace-entries-", + }); + if (opts?.git) { + yield* gitCore.initRepo({ cwd: dir }); + } + return dir; +}); + +function writeTextFile( + cwd: string, + relativePath: string, + contents = "", +): Effect.Effect { + return Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem.makeDirectory(path.dirname(absolutePath), { recursive: true }); + yield* fileSystem.writeFileString(absolutePath, contents); + }); +} + +const git = (cwd: string, args: ReadonlyArray, env?: NodeJS.ProcessEnv) => + Effect.gen(function* () { + const gitCore = yield* GitCore; + const result = yield* gitCore.execute({ + operation: "WorkspaceEntries.test.git", + cwd, + args, + ...(env ? { env } : {}), + timeoutMs: 10_000, + }); + return result.stdout.trim(); + }); + +const searchWorkspaceEntries = (input: { cwd: string; query: string; limit: number }) => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + return yield* workspaceEntries.search(input); + }); + +it.layer(TestLayer)("WorkspaceEntriesLive", (it) => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + describe("search", () => { + it.effect("returns files and directories relative to cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir(); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/index.ts"); + yield* writeTextFile(cwd, "README.md"); + yield* writeTextFile(cwd, ".git/HEAD"); + yield* writeTextFile(cwd, "node_modules/pkg/index.js"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + expect(paths).toContain("README.md"); + expect(paths.some((entryPath) => entryPath.startsWith(".git"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("node_modules"))).toBe(false); + expect(result.truncated).toBe(false); + }), + ); + + it.effect("filters and ranks entries by query", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); + + expect(result.entries.length).toBeGreaterThan(0); + expect(result.entries.some((entry) => entry.path === "src/components")).toBe(true); + expect(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))).toBe( + true, + ); + }), + ); + + it.effect("supports fuzzy subsequence queries for composer path search", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-query-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); + const paths = result.entries.map((entry) => entry.path); + + expect(result.entries.length).toBeGreaterThan(0); + expect(paths).toContain("src/components"); + expect(paths).toContain("src/components/Composer.tsx"); + }), + ); + + it.effect("tracks truncation without sorting every fuzzy match", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-fuzzy-limit-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + yield* writeTextFile(cwd, "src/components/composePrompt.ts"); + yield* writeTextFile(cwd, "docs/composition.md"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); + + expect(result.entries).toHaveLength(1); + expect(result.truncated).toBe(true); + }), + ); + + it.effect("excludes gitignored paths for git repositories", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-gitignore-", git: true }); + yield* writeTextFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* writeTextFile(cwd, "ignored.txt", "ignore me"); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths).not.toContain("ignored.txt"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + expect(paths.some((entryPath) => entryPath.startsWith("convex/"))).toBe(false); + }), + ); + + it.effect("excludes tracked paths that match ignore rules", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ + prefix: "t3code-workspace-tracked-gitignore-", + git: true, + }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + yield* git(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]); + yield* writeTextFile(cwd, ".gitignore", ".convex/\n"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("excludes .convex in non-git workspaces", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-non-git-convex-" }); + yield* writeTextFile(cwd, ".convex/local-storage/data.json", "{}"); + yield* writeTextFile(cwd, "src/keep.ts", "export {};"); + + const result = yield* searchWorkspaceEntries({ cwd, query: "", limit: 100 }); + const paths = result.entries.map((entry) => entry.path); + + expect(paths).toContain("src"); + expect(paths).toContain("src/keep.ts"); + expect(paths.some((entryPath) => entryPath.startsWith(".convex/"))).toBe(false); + }), + ); + + it.effect("deduplicates concurrent index builds for the same cwd", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-concurrent-build-" }); + yield* writeTextFile(cwd, "src/components/Composer.tsx"); + + let rootReadCount = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + if (args[0] === cwd) { + rootReadCount += 1; + await new Promise((resolve) => setTimeout(resolve, 20)); + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* Effect.all( + [ + searchWorkspaceEntries({ cwd, query: "", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }), + searchWorkspaceEntries({ cwd, query: "src", limit: 100 }), + ], + { concurrency: "unbounded" }, + ); + + expect(rootReadCount).toBe(1); + }), + ); + + it.effect("limits concurrent directory reads while walking the filesystem", () => + Effect.gen(function* () { + const cwd = yield* makeTempDir({ prefix: "t3code-workspace-read-concurrency-" }); + yield* Effect.forEach( + Array.from({ length: 80 }, (_, index) => index), + (index) => writeTextFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"), + { discard: true }, + ); + + let activeReads = 0; + let peakReads = 0; + const originalReaddir = fsPromises.readdir.bind(fsPromises); + vi.spyOn(fsPromises, "readdir").mockImplementation((async ( + ...args: Parameters + ) => { + const target = args[0]; + if (typeof target === "string" && target.startsWith(cwd)) { + activeReads += 1; + peakReads = Math.max(peakReads, activeReads); + await new Promise((resolve) => setTimeout(resolve, 4)); + try { + return await originalReaddir(...args); + } finally { + activeReads -= 1; + } + } + return originalReaddir(...args); + }) as typeof fsPromises.readdir); + + yield* searchWorkspaceEntries({ cwd, query: "", limit: 200 }); + + expect(peakReads).toBeLessThanOrEqual(32); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceEntries.ts b/apps/server/src/workspace/Layers/WorkspaceEntries.ts new file mode 100644 index 0000000000..c64960593c --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceEntries.ts @@ -0,0 +1,478 @@ +import fsPromises from "node:fs/promises"; +import type { Dirent } from "node:fs"; + +import { Cache, Duration, Effect, Exit, Layer, Option, Path } from "effect"; + +import { type ProjectEntry } from "@t3tools/contracts"; + +import { GitCore } from "../../git/Services/GitCore.ts"; +import { + WorkspaceEntries, + WorkspaceEntriesError, + type WorkspaceEntriesShape, +} from "../Services/WorkspaceEntries.ts"; + +const WORKSPACE_CACHE_TTL_MS = 15_000; +const WORKSPACE_CACHE_MAX_KEYS = 4; +const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; +const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32; +const IGNORED_DIRECTORY_NAMES = new Set([ + ".git", + ".convex", + "node_modules", + ".next", + ".turbo", + "dist", + "build", + "out", + ".cache", +]); + +interface WorkspaceIndex { + scannedAt: number; + entries: SearchableWorkspaceEntry[]; + truncated: boolean; +} + +interface SearchableWorkspaceEntry extends ProjectEntry { + normalizedPath: string; + normalizedName: string; +} + +interface RankedWorkspaceEntry { + entry: SearchableWorkspaceEntry; + score: number; +} + +function toPosixPath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function parentPathOf(input: string): string | undefined { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return undefined; + } + return input.slice(0, separatorIndex); +} + +function basenameOf(input: string): string { + const separatorIndex = input.lastIndexOf("/"); + if (separatorIndex === -1) { + return input; + } + return input.slice(separatorIndex + 1); +} + +function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry { + const normalizedPath = entry.path.toLowerCase(); + return { + ...entry, + normalizedPath, + normalizedName: basenameOf(normalizedPath), + }; +} + +function normalizeQuery(input: string): string { + return input + .trim() + .replace(/^[@./]+/, "") + .toLowerCase(); +} + +function scoreSubsequenceMatch(value: string, query: string): number | null { + if (!query) return 0; + + let queryIndex = 0; + let firstMatchIndex = -1; + let previousMatchIndex = -1; + let gapPenalty = 0; + + for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) { + if (value[valueIndex] !== query[queryIndex]) { + continue; + } + + if (firstMatchIndex === -1) { + firstMatchIndex = valueIndex; + } + if (previousMatchIndex !== -1) { + gapPenalty += valueIndex - previousMatchIndex - 1; + } + + previousMatchIndex = valueIndex; + queryIndex += 1; + if (queryIndex === query.length) { + const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length; + const lengthPenalty = Math.min(64, value.length - query.length); + return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty; + } + } + + return null; +} + +function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null { + if (!query) { + return entry.kind === "directory" ? 0 : 1; + } + + const { normalizedPath, normalizedName } = entry; + + if (normalizedName === query) return 0; + if (normalizedPath === query) return 1; + if (normalizedName.startsWith(query)) return 2; + if (normalizedPath.startsWith(query)) return 3; + if (normalizedPath.includes(`/${query}`)) return 4; + if (normalizedName.includes(query)) return 5; + if (normalizedPath.includes(query)) return 6; + + const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); + if (nameFuzzyScore !== null) { + return 100 + nameFuzzyScore; + } + + const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query); + if (pathFuzzyScore !== null) { + return 200 + pathFuzzyScore; + } + + return null; +} + +function compareRankedWorkspaceEntries( + left: RankedWorkspaceEntry, + right: RankedWorkspaceEntry, +): number { + const scoreDelta = left.score - right.score; + if (scoreDelta !== 0) return scoreDelta; + return left.entry.path.localeCompare(right.entry.path); +} + +function findInsertionIndex( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, +): number { + let low = 0; + let high = rankedEntries.length; + + while (low < high) { + const middle = low + Math.floor((high - low) / 2); + const current = rankedEntries[middle]; + if (!current) { + break; + } + + if (compareRankedWorkspaceEntries(candidate, current) < 0) { + high = middle; + } else { + low = middle + 1; + } + } + + return low; +} + +function insertRankedEntry( + rankedEntries: RankedWorkspaceEntry[], + candidate: RankedWorkspaceEntry, + limit: number, +): void { + if (limit <= 0) { + return; + } + + const insertionIndex = findInsertionIndex(rankedEntries, candidate); + if (rankedEntries.length < limit) { + rankedEntries.splice(insertionIndex, 0, candidate); + return; + } + + if (insertionIndex >= limit) { + return; + } + + rankedEntries.splice(insertionIndex, 0, candidate); + rankedEntries.pop(); +} + +function isPathInIgnoredDirectory(relativePath: string): boolean { + const firstSegment = relativePath.split("/")[0]; + if (!firstSegment) return false; + return IGNORED_DIRECTORY_NAMES.has(firstSegment); +} + +function directoryAncestorsOf(relativePath: string): string[] { + const segments = relativePath.split("/").filter((segment) => segment.length > 0); + if (segments.length <= 1) return []; + + const directories: string[] = []; + for (let index = 1; index < segments.length; index += 1) { + directories.push(segments.slice(0, index).join("/")); + } + return directories; +} + +const processErrorDetail = (cause: unknown): string => + cause instanceof Error ? cause.message : String(cause); + +export const makeWorkspaceEntries = Effect.gen(function* () { + const path = yield* Path.Path; + const gitOption = yield* Effect.serviceOption(GitCore); + + const isInsideGitWorkTree = (cwd: string): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => git.isInsideWorkTree(cwd).pipe(Effect.catch(() => Effect.succeed(false))), + onNone: () => Effect.succeed(false), + }); + + const filterGitIgnoredPaths = ( + cwd: string, + relativePaths: string[], + ): Effect.Effect => + Option.match(gitOption, { + onSome: (git) => + git.filterIgnoredPaths(cwd, relativePaths).pipe( + Effect.map((paths) => [...paths]), + Effect.catch(() => Effect.succeed(relativePaths)), + ), + onNone: () => Effect.succeed(relativePaths), + }); + + const buildWorkspaceIndexFromGit = Effect.fn("WorkspaceEntries.buildWorkspaceIndexFromGit")( + function* (cwd: string) { + if (Option.isNone(gitOption)) { + return null; + } + if (!(yield* isInsideGitWorkTree(cwd))) { + return null; + } + + const listedFiles = yield* gitOption.value + .listWorkspaceFiles(cwd) + .pipe(Effect.catch(() => Effect.succeed(null))); + + if (!listedFiles) { + return null; + } + + const listedPaths = [...listedFiles.paths] + .map((entry) => toPosixPath(entry)) + .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); + const filePaths = yield* filterGitIgnoredPaths(cwd, listedPaths); + + const directorySet = new Set(); + for (const filePath of filePaths) { + for (const directoryPath of directoryAncestorsOf(filePath)) { + if (!isPathInIgnoredDirectory(directoryPath)) { + directorySet.add(directoryPath); + } + } + } + + const directoryEntries = [...directorySet] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (directoryPath): ProjectEntry => ({ + path: directoryPath, + kind: "directory", + parentPath: parentPathOf(directoryPath), + }), + ) + .map(toSearchableWorkspaceEntry); + const fileEntries = [...new Set(filePaths)] + .toSorted((left, right) => left.localeCompare(right)) + .map( + (filePath): ProjectEntry => ({ + path: filePath, + kind: "file", + parentPath: parentPathOf(filePath), + }), + ) + .map(toSearchableWorkspaceEntry); + + const entries = [...directoryEntries, ...fileEntries]; + return { + scannedAt: Date.now(), + entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES), + truncated: listedFiles.truncated || entries.length > WORKSPACE_INDEX_MAX_ENTRIES, + }; + }, + ); + + const readDirectoryEntries = Effect.fn("WorkspaceEntries.readDirectoryEntries")(function* ( + cwd: string, + relativeDir: string, + ): Effect.fn.Return< + { readonly relativeDir: string; readonly dirents: Dirent[] | null }, + WorkspaceEntriesError + > { + return yield* Effect.tryPromise({ + try: async () => { + const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd; + const dirents = await fsPromises.readdir(absoluteDir, { withFileTypes: true }); + return { relativeDir, dirents }; + }, + catch: (cause) => + new WorkspaceEntriesError({ + cwd, + operation: "workspaceEntries.readDirectoryEntries", + detail: processErrorDetail(cause), + cause, + }), + }).pipe( + Effect.catchIf( + () => relativeDir.length > 0, + () => Effect.succeed({ relativeDir, dirents: null }), + ), + ); + }); + + const buildWorkspaceIndexFromFilesystem = Effect.fn( + "WorkspaceEntries.buildWorkspaceIndexFromFilesystem", + )(function* (cwd: string): Effect.fn.Return { + const shouldFilterWithGitIgnore = yield* isInsideGitWorkTree(cwd); + + let pendingDirectories: string[] = [""]; + const entries: SearchableWorkspaceEntry[] = []; + let truncated = false; + + while (pendingDirectories.length > 0 && !truncated) { + const currentDirectories = pendingDirectories; + pendingDirectories = []; + + const directoryEntries = yield* Effect.forEach( + currentDirectories, + (relativeDir) => readDirectoryEntries(cwd, relativeDir), + { concurrency: WORKSPACE_SCAN_READDIR_CONCURRENCY }, + ); + + const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => { + const { relativeDir, dirents } = directoryEntry; + if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>; + + dirents.sort((left, right) => left.name.localeCompare(right.name)); + const candidates: Array<{ dirent: Dirent; relativePath: string }> = []; + for (const dirent of dirents) { + if (!dirent.name || dirent.name === "." || dirent.name === "..") { + continue; + } + if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) { + continue; + } + if (!dirent.isDirectory() && !dirent.isFile()) { + continue; + } + + const relativePath = toPosixPath( + relativeDir ? path.join(relativeDir, dirent.name) : dirent.name, + ); + if (isPathInIgnoredDirectory(relativePath)) { + continue; + } + candidates.push({ dirent, relativePath }); + } + return candidates; + }); + + const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) => + candidateEntries.map((entry) => entry.relativePath), + ); + const allowedPathSet = shouldFilterWithGitIgnore + ? new Set(yield* filterGitIgnoredPaths(cwd, candidatePaths)) + : null; + + for (const candidateEntries of candidateEntriesByDirectory) { + for (const candidate of candidateEntries) { + if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) { + continue; + } + + const entry = toSearchableWorkspaceEntry({ + path: candidate.relativePath, + kind: candidate.dirent.isDirectory() ? "directory" : "file", + parentPath: parentPathOf(candidate.relativePath), + }); + entries.push(entry); + + if (candidate.dirent.isDirectory()) { + pendingDirectories.push(candidate.relativePath); + } + + if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) { + truncated = true; + break; + } + } + + if (truncated) { + break; + } + } + } + + return { + scannedAt: Date.now(), + entries, + truncated, + }; + }); + + const buildWorkspaceIndex = Effect.fn("WorkspaceEntries.buildWorkspaceIndex")(function* ( + cwd: string, + ): Effect.fn.Return { + const gitIndexed = yield* buildWorkspaceIndexFromGit(cwd); + if (gitIndexed) { + return gitIndexed; + } + return yield* buildWorkspaceIndexFromFilesystem(cwd); + }); + + const workspaceIndexCache = yield* Cache.makeWith({ + capacity: WORKSPACE_CACHE_MAX_KEYS, + lookup: buildWorkspaceIndex, + timeToLive: (exit) => + Exit.isSuccess(exit) ? Duration.millis(WORKSPACE_CACHE_TTL_MS) : Duration.zero, + }); + + const invalidate: WorkspaceEntriesShape["invalidate"] = Effect.fn("WorkspaceEntries.invalidate")( + function* (cwd) { + return yield* Cache.invalidate(workspaceIndexCache, cwd); + }, + ); + + const search: WorkspaceEntriesShape["search"] = Effect.fn("WorkspaceEntries.search")( + function* (input) { + return yield* Cache.get(workspaceIndexCache, input.cwd).pipe( + Effect.map((index) => { + const normalizedQuery = normalizeQuery(input.query); + const limit = Math.max(0, Math.floor(input.limit)); + const rankedEntries: RankedWorkspaceEntry[] = []; + let matchedEntryCount = 0; + + for (const entry of index.entries) { + const score = scoreEntry(entry, normalizedQuery); + if (score === null) { + continue; + } + + matchedEntryCount += 1; + insertRankedEntry(rankedEntries, { entry, score }, limit); + } + + return { + entries: rankedEntries.map((candidate) => candidate.entry), + truncated: index.truncated || matchedEntryCount > limit, + }; + }), + ); + }, + ); + + return { + invalidate, + search, + } satisfies WorkspaceEntriesShape; +}); + +export const WorkspaceEntriesLive = Layer.effect(WorkspaceEntries, makeWorkspaceEntries); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts new file mode 100644 index 0000000000..9ea8835ba3 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.test.ts @@ -0,0 +1,135 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { ServerConfig } from "../../config.ts"; +import { GitCoreLive } from "../../git/Layers/GitCore.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspaceFileSystem } from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntriesLive } from "./WorkspaceEntries.ts"; +import { WorkspaceFileSystemLive } from "./WorkspaceFileSystem.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const ProjectLayer = WorkspaceFileSystemLive.pipe( + Layer.provide(WorkspacePathsLive), + Layer.provide(WorkspaceEntriesLive), +); + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(ProjectLayer), + Layer.provideMerge(WorkspaceEntriesLive), + Layer.provideMerge(GitCoreLive), + Layer.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-workspace-files-test-", + }), + ), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-workspace-files-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspaceFileSystemLive", (it) => { + describe("writeFile", () => { + it.effect("writes files relative to the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const result = yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + const saved = yield* fileSystem + .readFileString(path.join(cwd, "plans/effect-rpc.md")) + .pipe(Effect.orDie); + + expect(result).toEqual({ relativePath: "plans/effect-rpc.md" }); + expect(saved).toBe("# Plan\n"); + }), + ); + + it.effect("invalidates workspace entry search cache after writes", () => + Effect.gen(function* () { + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + yield* writeTextFile(cwd, "src/existing.ts", "export {};\n"); + + const beforeWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(beforeWrite).toEqual({ + entries: [], + truncated: false, + }); + + yield* workspaceFileSystem.writeFile({ + cwd, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + + const afterWrite = yield* workspaceEntries.search({ + cwd, + query: "rpc", + limit: 10, + }); + expect(afterWrite.entries).toEqual( + expect.arrayContaining([expect.objectContaining({ path: "plans/effect-rpc.md" })]), + ); + expect(afterWrite.truncated).toBe(false); + }), + ); + + it.effect("rejects writes outside the workspace root", () => + Effect.gen(function* () { + const workspaceFileSystem = yield* WorkspaceFileSystem; + const cwd = yield* makeTempDir; + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + + const error = yield* workspaceFileSystem + .writeFile({ + cwd, + relativePath: "../escape.md", + contents: "# nope\n", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + + const escapedPath = path.resolve(cwd, "..", "escape.md"); + const escapedStat = yield* fileSystem + .stat(escapedPath) + .pipe(Effect.catch(() => Effect.succeed(null))); + expect(escapedStat).toBeNull(); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..84e5d9c6d1 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspaceFileSystem.ts @@ -0,0 +1,55 @@ +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspaceFileSystem, + WorkspaceFileSystemError, + type WorkspaceFileSystemShape, +} from "../Services/WorkspaceFileSystem.ts"; +import { WorkspaceEntries } from "../Services/WorkspaceEntries.ts"; +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; + +export const makeWorkspaceFileSystem = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const workspacePaths = yield* WorkspacePaths; + const workspaceEntries = yield* WorkspaceEntries; + + const writeFile: WorkspaceFileSystemShape["writeFile"] = Effect.fn( + "WorkspaceFileSystem.writeFile", + )(function* (input) { + const target = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: input.cwd, + relativePath: input.relativePath, + }); + + yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.makeDirectory", + detail: cause.message, + cause, + }), + ), + ); + yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe( + Effect.mapError( + (cause) => + new WorkspaceFileSystemError({ + cwd: input.cwd, + relativePath: input.relativePath, + operation: "workspaceFileSystem.writeFile", + detail: cause.message, + cause, + }), + ), + ); + yield* workspaceEntries.invalidate(input.cwd); + return { relativePath: target.relativePath }; + }); + return { writeFile } satisfies WorkspaceFileSystemShape; +}); + +export const WorkspaceFileSystemLive = Layer.effect(WorkspaceFileSystem, makeWorkspaceFileSystem); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.test.ts b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts new file mode 100644 index 0000000000..d02a5929d2 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.test.ts @@ -0,0 +1,113 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { it, describe, expect } from "@effect/vitest"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { WorkspacePaths } from "../Services/WorkspacePaths.ts"; +import { WorkspacePathsLive } from "./WorkspacePaths.ts"; + +const TestLayer = Layer.empty.pipe( + Layer.provideMerge(WorkspacePathsLive), + Layer.provideMerge(NodeServices.layer), +); + +const makeTempDir = Effect.fn("makeTempDir")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + return yield* fileSystem.makeTempDirectoryScoped({ + prefix: "t3code-project-paths-", + }); +}); + +const writeTextFile = Effect.fn("writeTextFile")(function* ( + cwd: string, + relativePath: string, + contents = "", +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const absolutePath = path.join(cwd, relativePath); + yield* fileSystem + .makeDirectory(path.dirname(absolutePath), { recursive: true }) + .pipe(Effect.orDie); + yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie); +}); + +it.layer(TestLayer)("WorkspacePathsLive", (it) => { + describe("normalizeWorkspaceRoot", () => { + it.effect("resolves an existing directory", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const resolved = yield* workspacePaths.normalizeWorkspaceRoot(cwd); + + expect(resolved).toBe(cwd); + }), + ); + + it.effect("rejects missing directories", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const error = yield* workspacePaths + .normalizeWorkspaceRoot(path.join(cwd, "missing")) + .pipe(Effect.flip); + + expect(error.message).toContain("Workspace root does not exist:"); + }), + ); + + it.effect("rejects file paths", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + const filePath = path.join(cwd, "README.md"); + yield* writeTextFile(cwd, "README.md", "# hi\n"); + + const error = yield* workspacePaths.normalizeWorkspaceRoot(filePath).pipe(Effect.flip); + + expect(error.message).toContain("Workspace root is not a directory:"); + }), + ); + }); + + describe("resolveRelativePathWithinRoot", () => { + it.effect("resolves relative paths inside the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + const path = yield* Path.Path; + + const resolved = yield* workspacePaths.resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "plans/effect-rpc.md", + }); + + expect(resolved).toEqual({ + absolutePath: path.join(cwd, "plans/effect-rpc.md"), + relativePath: "plans/effect-rpc.md", + }); + }), + ); + + it.effect("rejects paths that escape the workspace root", () => + Effect.gen(function* () { + const workspacePaths = yield* WorkspacePaths; + const cwd = yield* makeTempDir(); + + const error = yield* workspacePaths + .resolveRelativePathWithinRoot({ + workspaceRoot: cwd, + relativePath: "../escape.md", + }) + .pipe(Effect.flip); + + expect(error.message).toContain( + "Workspace file path must be relative to the project root: ../escape.md", + ); + }), + ); + }); +}); diff --git a/apps/server/src/workspace/Layers/WorkspacePaths.ts b/apps/server/src/workspace/Layers/WorkspacePaths.ts new file mode 100644 index 0000000000..fa7a90cf07 --- /dev/null +++ b/apps/server/src/workspace/Layers/WorkspacePaths.ts @@ -0,0 +1,89 @@ +import * as OS from "node:os"; +import { Effect, FileSystem, Layer, Path } from "effect"; + +import { + WorkspacePaths, + WorkspacePathOutsideRootError, + WorkspaceRootNotDirectoryError, + WorkspaceRootNotExistsError, + type WorkspacePathsShape, +} from "../Services/WorkspacePaths.ts"; + +function toPosixRelativePath(input: string): string { + return input.replaceAll("\\", "/"); +} + +function expandHomePath(input: string, path: Path.Path): string { + if (input === "~") { + return OS.homedir(); + } + if (input.startsWith("~/") || input.startsWith("~\\")) { + return path.join(OS.homedir(), input.slice(2)); + } + return input; +} + +export const makeWorkspacePaths = Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + + const normalizeWorkspaceRoot: WorkspacePathsShape["normalizeWorkspaceRoot"] = Effect.fn( + "WorkspacePaths.normalizeWorkspaceRoot", + )(function* (workspaceRoot) { + const normalizedWorkspaceRoot = path.resolve(expandHomePath(workspaceRoot.trim(), path)); + const workspaceStat = yield* fileSystem + .stat(normalizedWorkspaceRoot) + .pipe(Effect.catch(() => Effect.succeed(null))); + if (!workspaceStat) { + return yield* new WorkspaceRootNotExistsError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + if (workspaceStat.type !== "Directory") { + return yield* new WorkspaceRootNotDirectoryError({ + workspaceRoot, + normalizedWorkspaceRoot, + }); + } + return normalizedWorkspaceRoot; + }); + + const resolveRelativePathWithinRoot: WorkspacePathsShape["resolveRelativePathWithinRoot"] = + Effect.fn("WorkspacePaths.resolveRelativePathWithinRoot")(function* (input) { + const normalizedInputPath = input.relativePath.trim(); + if (path.isAbsolute(normalizedInputPath)) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + const absolutePath = path.resolve(input.workspaceRoot, normalizedInputPath); + const relativeToRoot = toPosixRelativePath(path.relative(input.workspaceRoot, absolutePath)); + if ( + relativeToRoot.length === 0 || + relativeToRoot === "." || + relativeToRoot.startsWith("../") || + relativeToRoot === ".." || + path.isAbsolute(relativeToRoot) + ) { + return yield* new WorkspacePathOutsideRootError({ + workspaceRoot: input.workspaceRoot, + relativePath: input.relativePath, + }); + } + + return { + absolutePath, + relativePath: relativeToRoot, + }; + }); + + return { + normalizeWorkspaceRoot, + resolveRelativePathWithinRoot, + } satisfies WorkspacePathsShape; +}); + +export const WorkspacePathsLive = Layer.effect(WorkspacePaths, makeWorkspacePaths); diff --git a/apps/server/src/workspace/Services/WorkspaceEntries.ts b/apps/server/src/workspace/Services/WorkspaceEntries.ts new file mode 100644 index 0000000000..2841b1fe2f --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceEntries.ts @@ -0,0 +1,48 @@ +/** + * WorkspaceEntries - Effect service contract for cached workspace entry search. + * + * Owns indexed workspace entry search plus cache invalidation for workspace + * roots when the underlying filesystem changes. + * + * @module WorkspaceEntries + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectSearchEntriesInput, ProjectSearchEntriesResult } from "@t3tools/contracts"; + +export class WorkspaceEntriesError extends Schema.TaggedErrorClass()( + "WorkspaceEntriesError", + { + cwd: Schema.String, + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceEntriesShape - Service API for workspace entry search and cache + * invalidation. + */ +export interface WorkspaceEntriesShape { + /** + * Search indexed workspace entries for files and directories matching the + * provided query. + */ + readonly search: ( + input: ProjectSearchEntriesInput, + ) => Effect.Effect; + + /** + * Drop any cached workspace entries for the given workspace root. + */ + readonly invalidate: (cwd: string) => Effect.Effect; +} + +/** + * WorkspaceEntries - Service tag for cached workspace entry search. + */ +export class WorkspaceEntries extends ServiceMap.Service()( + "t3/workspace/Services/WorkspaceEntries", +) {} diff --git a/apps/server/src/workspace/Services/WorkspaceFileSystem.ts b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts new file mode 100644 index 0000000000..85db1514a3 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspaceFileSystem.ts @@ -0,0 +1,50 @@ +/** + * WorkspaceFileSystem - Effect service contract for workspace file mutations. + * + * Owns workspace-root-relative file write operations and their associated + * safety checks and cache invalidation hooks. + * + * @module WorkspaceFileSystem + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +import type { ProjectWriteFileInput, ProjectWriteFileResult } from "@t3tools/contracts"; +import { WorkspacePathOutsideRootError } from "./WorkspacePaths.ts"; + +export class WorkspaceFileSystemError extends Schema.TaggedErrorClass()( + "WorkspaceFileSystemError", + { + cwd: Schema.String, + relativePath: Schema.optional(Schema.String), + operation: Schema.String, + detail: Schema.String, + cause: Schema.optional(Schema.Defect), + }, +) {} + +/** + * WorkspaceFileSystemShape - Service API for workspace-relative file operations. + */ +export interface WorkspaceFileSystemShape { + /** + * Write a file relative to the workspace root. + * + * Creates parent directories as needed and rejects paths that escape the + * workspace root. + */ + readonly writeFile: ( + input: ProjectWriteFileInput, + ) => Effect.Effect< + ProjectWriteFileResult, + WorkspaceFileSystemError | WorkspacePathOutsideRootError + >; +} + +/** + * WorkspaceFileSystem - Service tag for workspace file operations. + */ +export class WorkspaceFileSystem extends ServiceMap.Service< + WorkspaceFileSystem, + WorkspaceFileSystemShape +>()("t3/workspace/Services/WorkspaceFileSystem") {} diff --git a/apps/server/src/workspace/Services/WorkspacePaths.ts b/apps/server/src/workspace/Services/WorkspacePaths.ts new file mode 100644 index 0000000000..ad6d9cd3e5 --- /dev/null +++ b/apps/server/src/workspace/Services/WorkspacePaths.ts @@ -0,0 +1,85 @@ +/** + * WorkspacePaths - Effect service contract for workspace path handling. + * + * Owns normalization and validation of workspace roots plus safe resolution of + * workspace-root-relative paths. + * + * @module WorkspacePaths + */ +import { Schema, ServiceMap } from "effect"; +import type { Effect } from "effect"; + +export class WorkspaceRootNotExistsError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotExistsError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root does not exist: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspaceRootNotDirectoryError extends Schema.TaggedErrorClass()( + "WorkspaceRootNotDirectoryError", + { + workspaceRoot: Schema.String, + normalizedWorkspaceRoot: Schema.String, + }, +) { + override get message(): string { + return `Workspace root is not a directory: ${this.normalizedWorkspaceRoot}`; + } +} + +export class WorkspacePathOutsideRootError extends Schema.TaggedErrorClass()( + "WorkspacePathOutsideRootError", + { + workspaceRoot: Schema.String, + relativePath: Schema.String, + }, +) { + override get message(): string { + return `Workspace file path must be relative to the project root: ${this.relativePath}`; + } +} + +export const WorkspacePathsError = Schema.Union([ + WorkspaceRootNotExistsError, + WorkspaceRootNotDirectoryError, + WorkspacePathOutsideRootError, +]); +export type WorkspacePathsError = typeof WorkspacePathsError.Type; + +/** + * WorkspacePathsShape - Service API for workspace path normalization and guards. + */ +export interface WorkspacePathsShape { + /** + * Normalize a user-provided workspace root and verify it exists as a directory. + */ + readonly normalizeWorkspaceRoot: ( + workspaceRoot: string, + ) => Effect.Effect; + + /** + * Resolve a relative path within a validated workspace root. + * + * Rejects absolute paths and traversal attempts outside the workspace root. + */ + readonly resolveRelativePathWithinRoot: (input: { + workspaceRoot: string; + relativePath: string; + }) => Effect.Effect< + { absolutePath: string; relativePath: string }, + WorkspacePathOutsideRootError + >; +} + +/** + * WorkspacePaths - Service tag for workspace path normalization and resolution. + */ +export class WorkspacePaths extends ServiceMap.Service()( + "t3/workspace/Services/WorkspacePaths", +) {} diff --git a/apps/server/src/workspaceEntries.chunking.test.ts b/apps/server/src/workspaceEntries.chunking.test.ts deleted file mode 100644 index f978c5233e..0000000000 --- a/apps/server/src/workspaceEntries.chunking.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { assert, beforeEach, describe, it, vi } from "vitest"; -import type { ProcessRunOptions, ProcessRunResult } from "./processRunner"; - -const { runProcessMock } = vi.hoisted(() => ({ - runProcessMock: - vi.fn< - ( - command: string, - args: readonly string[], - options?: ProcessRunOptions, - ) => Promise - >(), -})); - -vi.mock("./processRunner", () => ({ - runProcess: runProcessMock, -})); - -function processResult( - overrides: Partial & Pick, -): ProcessRunResult { - return { - stdout: overrides.stdout, - code: overrides.code, - stderr: overrides.stderr ?? "", - signal: overrides.signal ?? null, - timedOut: overrides.timedOut ?? false, - stdoutTruncated: overrides.stdoutTruncated ?? false, - stderrTruncated: overrides.stderrTruncated ?? false, - }; -} - -describe("searchWorkspaceEntries git-ignore chunking", () => { - beforeEach(() => { - runProcessMock.mockReset(); - vi.resetModules(); - }); - - it("chunks git check-ignore stdin to avoid building giant strings", async () => { - const ignoredPaths = Array.from( - { length: 5000 }, - (_, index) => `ignored/${index.toString().padStart(5, "0")}/${"x".repeat(80)}.ts`, - ); - const keptPaths = ["src/keep.ts", "docs/readme.md"]; - const listedPaths = [...ignoredPaths, ...keptPaths]; - let checkIgnoreCalls = 0; - - runProcessMock.mockImplementation(async (_command, args, options) => { - if (args[0] === "rev-parse") { - return processResult({ code: 0, stdout: "true\n" }); - } - - if (args[0] === "ls-files") { - return processResult({ code: 0, stdout: `${listedPaths.join("\0")}\0` }); - } - - if (args[0] === "check-ignore") { - checkIgnoreCalls += 1; - const chunkPaths = (options?.stdin ?? "").split("\0").filter((value) => value.length > 0); - const chunkIgnored = chunkPaths.filter((value) => value.startsWith("ignored/")); - return processResult({ - code: chunkIgnored.length > 0 ? 0 : 1, - stdout: chunkIgnored.length > 0 ? `${chunkIgnored.join("\0")}\0` : "", - }); - } - - throw new Error(`Unexpected command: git ${args.join(" ")}`); - }); - - const { searchWorkspaceEntries } = await import("./workspaceEntries"); - const result = await searchWorkspaceEntries({ - cwd: "/virtual/workspace", - query: "", - limit: 100, - }); - - assert.isAbove(checkIgnoreCalls, 1); - assert.isFalse(result.entries.some((entry) => entry.path.startsWith("ignored/"))); - assert.isTrue(result.entries.some((entry) => entry.path === "src/keep.ts")); - }); -}); diff --git a/apps/server/src/workspaceEntries.test.ts b/apps/server/src/workspaceEntries.test.ts deleted file mode 100644 index d867ad910d..0000000000 --- a/apps/server/src/workspaceEntries.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import fs from "node:fs"; -import fsPromises from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import { spawnSync } from "node:child_process"; - -import { afterEach, assert, describe, it, vi } from "vitest"; - -import { searchWorkspaceEntries } from "./workspaceEntries"; - -const tempDirs: string[] = []; - -function makeTempDir(prefix: string): string { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - tempDirs.push(dir); - return dir; -} - -function writeFile(cwd: string, relativePath: string, contents = ""): void { - const absolutePath = path.join(cwd, relativePath); - fs.mkdirSync(path.dirname(absolutePath), { recursive: true }); - fs.writeFileSync(absolutePath, contents, "utf8"); -} - -function runGit(cwd: string, args: string[]): void { - const result = spawnSync("git", args, { cwd, encoding: "utf8" }); - if (result.status !== 0) { - throw new Error(result.stderr || `git ${args.join(" ")} failed`); - } -} - -describe("searchWorkspaceEntries", () => { - afterEach(() => { - vi.restoreAllMocks(); - for (const dir of tempDirs.splice(0, tempDirs.length)) { - fs.rmSync(dir, { recursive: true, force: true }); - } - }); - - it("returns files and directories relative to cwd", async () => { - const cwd = makeTempDir("t3code-workspace-entries-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/index.ts"); - writeFile(cwd, "README.md"); - writeFile(cwd, ".git/HEAD"); - writeFile(cwd, "node_modules/pkg/index.js"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/components"); - assert.include(paths, "src/components/Composer.tsx"); - assert.include(paths, "README.md"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".git"))); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith("node_modules"))); - assert.isFalse(result.truncated); - }); - - it("filters and ranks entries by query", async () => { - const cwd = makeTempDir("t3code-workspace-query-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "compo", limit: 5 }); - - assert.isAbove(result.entries.length, 0); - assert.isTrue(result.entries.some((entry) => entry.path === "src/components")); - assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo"))); - }); - - it("supports fuzzy subsequence queries for composer path search", async () => { - const cwd = makeTempDir("t3code-workspace-fuzzy-query-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 }); - const paths = result.entries.map((entry) => entry.path); - - assert.isAbove(result.entries.length, 0); - assert.include(paths, "src/components"); - assert.include(paths, "src/components/Composer.tsx"); - }); - - it("tracks truncation without sorting every fuzzy match", async () => { - const cwd = makeTempDir("t3code-workspace-fuzzy-limit-"); - writeFile(cwd, "src/components/Composer.tsx"); - writeFile(cwd, "src/components/composePrompt.ts"); - writeFile(cwd, "docs/composition.md"); - - const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 }); - - assert.lengthOf(result.entries, 1); - assert.isTrue(result.truncated); - }); - - it("excludes gitignored paths for git repositories", async () => { - const cwd = makeTempDir("t3code-workspace-gitignore-"); - runGit(cwd, ["init"]); - writeFile(cwd, ".gitignore", ".convex/\nconvex/\nignored.txt\n"); - writeFile(cwd, "src/keep.ts", "export {};"); - writeFile(cwd, "ignored.txt", "ignore me"); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "convex/UOoS-l/convex_local_storage/modules/data.json", "{}"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.notInclude(paths, "ignored.txt"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith("convex/"))); - }); - - it("excludes tracked paths that match ignore rules", async () => { - const cwd = makeTempDir("t3code-workspace-tracked-gitignore-"); - runGit(cwd, ["init"]); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "src/keep.ts", "export {};"); - runGit(cwd, ["add", ".convex/local-storage/data.json", "src/keep.ts"]); - writeFile(cwd, ".gitignore", ".convex/\n"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - }); - - it("excludes .convex in non-git workspaces", async () => { - const cwd = makeTempDir("t3code-workspace-non-git-convex-"); - writeFile(cwd, ".convex/local-storage/data.json", "{}"); - writeFile(cwd, "src/keep.ts", "export {};"); - - const result = await searchWorkspaceEntries({ cwd, query: "", limit: 100 }); - const paths = result.entries.map((entry) => entry.path); - - assert.include(paths, "src"); - assert.include(paths, "src/keep.ts"); - assert.isFalse(paths.some((entryPath) => entryPath.startsWith(".convex/"))); - }); - - it("deduplicates concurrent index builds for the same cwd", async () => { - const cwd = makeTempDir("t3code-workspace-concurrent-build-"); - writeFile(cwd, "src/components/Composer.tsx"); - - let rootReadCount = 0; - const originalReaddir = fsPromises.readdir.bind(fsPromises); - vi.spyOn(fsPromises, "readdir").mockImplementation((async ( - ...args: Parameters - ) => { - if (args[0] === cwd) { - rootReadCount += 1; - await new Promise((resolve) => setTimeout(resolve, 20)); - } - return originalReaddir(...args); - }) as typeof fsPromises.readdir); - - await Promise.all([ - searchWorkspaceEntries({ cwd, query: "", limit: 100 }), - searchWorkspaceEntries({ cwd, query: "comp", limit: 100 }), - searchWorkspaceEntries({ cwd, query: "src", limit: 100 }), - ]); - - assert.equal(rootReadCount, 1); - }); - - it("limits concurrent directory reads while walking the filesystem", async () => { - const cwd = makeTempDir("t3code-workspace-read-concurrency-"); - for (let index = 0; index < 80; index += 1) { - writeFile(cwd, `group-${index}/entry-${index}.ts`, "export {};"); - } - - let activeReads = 0; - let peakReads = 0; - const originalReaddir = fsPromises.readdir.bind(fsPromises); - vi.spyOn(fsPromises, "readdir").mockImplementation((async ( - ...args: Parameters - ) => { - const target = args[0]; - if (typeof target === "string" && target.startsWith(cwd)) { - activeReads += 1; - peakReads = Math.max(peakReads, activeReads); - await new Promise((resolve) => setTimeout(resolve, 4)); - try { - return await originalReaddir(...args); - } finally { - activeReads -= 1; - } - } - return originalReaddir(...args); - }) as typeof fsPromises.readdir); - - await searchWorkspaceEntries({ cwd, query: "", limit: 200 }); - - assert.isAtMost(peakReads, 32); - }); -}); diff --git a/apps/server/src/workspaceEntries.ts b/apps/server/src/workspaceEntries.ts deleted file mode 100644 index 684b005e83..0000000000 --- a/apps/server/src/workspaceEntries.ts +++ /dev/null @@ -1,565 +0,0 @@ -import fs from "node:fs/promises"; -import type { Dirent } from "node:fs"; -import path from "node:path"; -import { runProcess } from "./processRunner"; - -import { - ProjectEntry, - ProjectSearchEntriesInput, - ProjectSearchEntriesResult, -} from "@t3tools/contracts"; - -const WORKSPACE_CACHE_TTL_MS = 15_000; -const WORKSPACE_CACHE_MAX_KEYS = 4; -const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; -const WORKSPACE_SCAN_READDIR_CONCURRENCY = 32; -const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024; -const IGNORED_DIRECTORY_NAMES = new Set([ - ".git", - ".convex", - "node_modules", - ".next", - ".turbo", - "dist", - "build", - "out", - ".cache", -]); - -interface WorkspaceIndex { - scannedAt: number; - entries: SearchableWorkspaceEntry[]; - truncated: boolean; -} - -interface SearchableWorkspaceEntry extends ProjectEntry { - normalizedPath: string; - normalizedName: string; -} - -interface RankedWorkspaceEntry { - entry: SearchableWorkspaceEntry; - score: number; -} - -const workspaceIndexCache = new Map(); -const inFlightWorkspaceIndexBuilds = new Map>(); - -function toPosixPath(input: string): string { - return input.split(path.sep).join("/"); -} - -function parentPathOf(input: string): string | undefined { - const separatorIndex = input.lastIndexOf("/"); - if (separatorIndex === -1) { - return undefined; - } - return input.slice(0, separatorIndex); -} - -function basenameOf(input: string): string { - const separatorIndex = input.lastIndexOf("/"); - if (separatorIndex === -1) { - return input; - } - return input.slice(separatorIndex + 1); -} - -function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry { - const normalizedPath = entry.path.toLowerCase(); - return { - ...entry, - normalizedPath, - normalizedName: basenameOf(normalizedPath), - }; -} - -function normalizeQuery(input: string): string { - return input - .trim() - .replace(/^[@./]+/, "") - .toLowerCase(); -} - -function scoreSubsequenceMatch(value: string, query: string): number | null { - if (!query) return 0; - - let queryIndex = 0; - let firstMatchIndex = -1; - let previousMatchIndex = -1; - let gapPenalty = 0; - - for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) { - if (value[valueIndex] !== query[queryIndex]) { - continue; - } - - if (firstMatchIndex === -1) { - firstMatchIndex = valueIndex; - } - if (previousMatchIndex !== -1) { - gapPenalty += valueIndex - previousMatchIndex - 1; - } - - previousMatchIndex = valueIndex; - queryIndex += 1; - if (queryIndex === query.length) { - const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length; - const lengthPenalty = Math.min(64, value.length - query.length); - return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty; - } - } - - return null; -} - -function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null { - if (!query) { - return entry.kind === "directory" ? 0 : 1; - } - - const { normalizedPath, normalizedName } = entry; - - if (normalizedName === query) return 0; - if (normalizedPath === query) return 1; - if (normalizedName.startsWith(query)) return 2; - if (normalizedPath.startsWith(query)) return 3; - if (normalizedPath.includes(`/${query}`)) return 4; - if (normalizedName.includes(query)) return 5; - if (normalizedPath.includes(query)) return 6; - - const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query); - if (nameFuzzyScore !== null) { - return 100 + nameFuzzyScore; - } - - const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query); - if (pathFuzzyScore !== null) { - return 200 + pathFuzzyScore; - } - - return null; -} - -function compareRankedWorkspaceEntries( - left: RankedWorkspaceEntry, - right: RankedWorkspaceEntry, -): number { - const scoreDelta = left.score - right.score; - if (scoreDelta !== 0) return scoreDelta; - return left.entry.path.localeCompare(right.entry.path); -} - -function findInsertionIndex( - rankedEntries: RankedWorkspaceEntry[], - candidate: RankedWorkspaceEntry, -): number { - let low = 0; - let high = rankedEntries.length; - - while (low < high) { - const middle = low + Math.floor((high - low) / 2); - const current = rankedEntries[middle]; - if (!current) { - break; - } - - if (compareRankedWorkspaceEntries(candidate, current) < 0) { - high = middle; - } else { - low = middle + 1; - } - } - - return low; -} - -function insertRankedEntry( - rankedEntries: RankedWorkspaceEntry[], - candidate: RankedWorkspaceEntry, - limit: number, -): void { - if (limit <= 0) { - return; - } - - const insertionIndex = findInsertionIndex(rankedEntries, candidate); - if (rankedEntries.length < limit) { - rankedEntries.splice(insertionIndex, 0, candidate); - return; - } - - if (insertionIndex >= limit) { - return; - } - - rankedEntries.splice(insertionIndex, 0, candidate); - rankedEntries.pop(); -} - -function isPathInIgnoredDirectory(relativePath: string): boolean { - const firstSegment = relativePath.split("/")[0]; - if (!firstSegment) return false; - return IGNORED_DIRECTORY_NAMES.has(firstSegment); -} - -function splitNullSeparatedPaths(input: string, truncated: boolean): string[] { - const parts = input.split("\0"); - if (parts.length === 0) return []; - - // If output was truncated, the final token can be partial. - if (truncated && parts[parts.length - 1]?.length) { - parts.pop(); - } - - return parts.filter((value) => value.length > 0); -} - -function directoryAncestorsOf(relativePath: string): string[] { - const segments = relativePath.split("/").filter((segment) => segment.length > 0); - if (segments.length <= 1) return []; - const directories: string[] = []; - for (let index = 1; index < segments.length; index += 1) { - directories.push(segments.slice(0, index).join("/")); - } - return directories; -} - -async function mapWithConcurrency( - items: readonly TInput[], - concurrency: number, - mapper: (item: TInput, index: number) => Promise, -): Promise { - if (items.length === 0) { - return []; - } - - const boundedConcurrency = Math.max(1, Math.min(concurrency, items.length)); - const results = Array.from({ length: items.length }) as TOutput[]; - let nextIndex = 0; - - const workers = Array.from({ length: boundedConcurrency }, async () => { - while (nextIndex < items.length) { - const currentIndex = nextIndex; - nextIndex += 1; - results[currentIndex] = await mapper(items[currentIndex] as TInput, currentIndex); - } - }); - - await Promise.all(workers); - return results; -} - -async function isInsideGitWorkTree(cwd: string): Promise { - const insideWorkTree = await runProcess("git", ["rev-parse", "--is-inside-work-tree"], { - cwd, - allowNonZeroExit: true, - timeoutMs: 5_000, - maxBufferBytes: 4_096, - }).catch(() => null); - return Boolean( - insideWorkTree && insideWorkTree.code === 0 && insideWorkTree.stdout.trim() === "true", - ); -} - -async function filterGitIgnoredPaths(cwd: string, relativePaths: string[]): Promise { - if (relativePaths.length === 0) { - return relativePaths; - } - - const ignoredPaths = new Set(); - let chunk: string[] = []; - let chunkBytes = 0; - - const flushChunk = async (): Promise => { - if (chunk.length === 0) { - return true; - } - - const checkIgnore = await runProcess("git", ["check-ignore", "--no-index", "-z", "--stdin"], { - cwd, - allowNonZeroExit: true, - timeoutMs: 20_000, - maxBufferBytes: 16 * 1024 * 1024, - outputMode: "truncate", - stdin: `${chunk.join("\0")}\0`, - }).catch(() => null); - chunk = []; - chunkBytes = 0; - - if (!checkIgnore) { - return false; - } - - // git-check-ignore exits with 1 when no paths match. - if (checkIgnore.code !== 0 && checkIgnore.code !== 1) { - return false; - } - - const matchedIgnoredPaths = splitNullSeparatedPaths( - checkIgnore.stdout, - Boolean(checkIgnore.stdoutTruncated), - ); - for (const ignoredPath of matchedIgnoredPaths) { - ignoredPaths.add(ignoredPath); - } - return true; - }; - - for (const relativePath of relativePaths) { - const relativePathBytes = Buffer.byteLength(relativePath) + 1; - if ( - chunk.length > 0 && - chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES && - !(await flushChunk()) - ) { - return relativePaths; - } - - chunk.push(relativePath); - chunkBytes += relativePathBytes; - - if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES && !(await flushChunk())) { - return relativePaths; - } - } - - if (!(await flushChunk())) { - return relativePaths; - } - - if (ignoredPaths.size === 0) { - return relativePaths; - } - - return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath)); -} - -async function buildWorkspaceIndexFromGit(cwd: string): Promise { - if (!(await isInsideGitWorkTree(cwd))) { - return null; - } - - const listedFiles = await runProcess( - "git", - ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], - { - cwd, - allowNonZeroExit: true, - timeoutMs: 20_000, - maxBufferBytes: 16 * 1024 * 1024, - outputMode: "truncate", - }, - ).catch(() => null); - if (!listedFiles || listedFiles.code !== 0) { - return null; - } - - const listedPaths = splitNullSeparatedPaths( - listedFiles.stdout, - Boolean(listedFiles.stdoutTruncated), - ) - .map((entry) => toPosixPath(entry)) - .filter((entry) => entry.length > 0 && !isPathInIgnoredDirectory(entry)); - const filePaths = await filterGitIgnoredPaths(cwd, listedPaths); - - const directorySet = new Set(); - for (const filePath of filePaths) { - for (const directoryPath of directoryAncestorsOf(filePath)) { - if (!isPathInIgnoredDirectory(directoryPath)) { - directorySet.add(directoryPath); - } - } - } - - const directoryEntries = [...directorySet] - .toSorted((left, right) => left.localeCompare(right)) - .map( - (directoryPath): ProjectEntry => ({ - path: directoryPath, - kind: "directory", - parentPath: parentPathOf(directoryPath), - }), - ) - .map(toSearchableWorkspaceEntry); - const fileEntries = [...new Set(filePaths)] - .toSorted((left, right) => left.localeCompare(right)) - .map( - (filePath): ProjectEntry => ({ - path: filePath, - kind: "file", - parentPath: parentPathOf(filePath), - }), - ) - .map(toSearchableWorkspaceEntry); - - const entries = [...directoryEntries, ...fileEntries]; - return { - scannedAt: Date.now(), - entries: entries.slice(0, WORKSPACE_INDEX_MAX_ENTRIES), - truncated: Boolean(listedFiles.stdoutTruncated) || entries.length > WORKSPACE_INDEX_MAX_ENTRIES, - }; -} - -async function buildWorkspaceIndex(cwd: string): Promise { - const gitIndexed = await buildWorkspaceIndexFromGit(cwd); - if (gitIndexed) { - return gitIndexed; - } - const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd); - - let pendingDirectories: string[] = [""]; - const entries: SearchableWorkspaceEntry[] = []; - let truncated = false; - - while (pendingDirectories.length > 0 && !truncated) { - const currentDirectories = pendingDirectories; - pendingDirectories = []; - const directoryEntries = await mapWithConcurrency( - currentDirectories, - WORKSPACE_SCAN_READDIR_CONCURRENCY, - async (relativeDir) => { - const absoluteDir = relativeDir ? path.join(cwd, relativeDir) : cwd; - try { - const dirents = await fs.readdir(absoluteDir, { withFileTypes: true }); - return { relativeDir, dirents }; - } catch (error) { - if (!relativeDir) { - throw new Error( - `Unable to scan workspace entries at '${cwd}': ${error instanceof Error ? error.message : "unknown error"}`, - { cause: error }, - ); - } - return { relativeDir, dirents: null }; - } - }, - ); - - const candidateEntriesByDirectory = directoryEntries.map((directoryEntry) => { - const { relativeDir, dirents } = directoryEntry; - if (!dirents) return [] as Array<{ dirent: Dirent; relativePath: string }>; - - dirents.sort((left, right) => left.name.localeCompare(right.name)); - const candidates: Array<{ dirent: Dirent; relativePath: string }> = []; - for (const dirent of dirents) { - if (!dirent.name || dirent.name === "." || dirent.name === "..") { - continue; - } - if (dirent.isDirectory() && IGNORED_DIRECTORY_NAMES.has(dirent.name)) { - continue; - } - if (!dirent.isDirectory() && !dirent.isFile()) { - continue; - } - - const relativePath = toPosixPath( - relativeDir ? path.join(relativeDir, dirent.name) : dirent.name, - ); - if (isPathInIgnoredDirectory(relativePath)) { - continue; - } - candidates.push({ dirent, relativePath }); - } - return candidates; - }); - - const candidatePaths = candidateEntriesByDirectory.flatMap((candidateEntries) => - candidateEntries.map((entry) => entry.relativePath), - ); - const allowedPathSet = shouldFilterWithGitIgnore - ? new Set(await filterGitIgnoredPaths(cwd, candidatePaths)) - : null; - - for (const candidateEntries of candidateEntriesByDirectory) { - for (const candidate of candidateEntries) { - if (allowedPathSet && !allowedPathSet.has(candidate.relativePath)) { - continue; - } - - const entry = toSearchableWorkspaceEntry({ - path: candidate.relativePath, - kind: candidate.dirent.isDirectory() ? "directory" : "file", - parentPath: parentPathOf(candidate.relativePath), - }); - entries.push(entry); - - if (candidate.dirent.isDirectory()) { - pendingDirectories.push(candidate.relativePath); - } - - if (entries.length >= WORKSPACE_INDEX_MAX_ENTRIES) { - truncated = true; - break; - } - } - - if (truncated) { - break; - } - } - } - - return { - scannedAt: Date.now(), - entries, - truncated, - }; -} - -async function getWorkspaceIndex(cwd: string): Promise { - const cached = workspaceIndexCache.get(cwd); - if (cached && Date.now() - cached.scannedAt < WORKSPACE_CACHE_TTL_MS) { - return cached; - } - - const inFlight = inFlightWorkspaceIndexBuilds.get(cwd); - if (inFlight) { - return inFlight; - } - - const nextPromise = buildWorkspaceIndex(cwd) - .then((next) => { - workspaceIndexCache.set(cwd, next); - while (workspaceIndexCache.size > WORKSPACE_CACHE_MAX_KEYS) { - const oldestKey = workspaceIndexCache.keys().next().value; - if (!oldestKey) break; - workspaceIndexCache.delete(oldestKey); - } - return next; - }) - .finally(() => { - inFlightWorkspaceIndexBuilds.delete(cwd); - }); - inFlightWorkspaceIndexBuilds.set(cwd, nextPromise); - return nextPromise; -} - -export function clearWorkspaceIndexCache(cwd: string): void { - workspaceIndexCache.delete(cwd); - inFlightWorkspaceIndexBuilds.delete(cwd); -} - -export async function searchWorkspaceEntries( - input: ProjectSearchEntriesInput, -): Promise { - const index = await getWorkspaceIndex(input.cwd); - const normalizedQuery = normalizeQuery(input.query); - const limit = Math.max(0, Math.floor(input.limit)); - const rankedEntries: RankedWorkspaceEntry[] = []; - let matchedEntryCount = 0; - - for (const entry of index.entries) { - const score = scoreEntry(entry, normalizedQuery); - if (score === null) { - continue; - } - - matchedEntryCount += 1; - insertRankedEntry(rankedEntries, { entry, score }, limit); - } - - return { - entries: rankedEntries.map((candidate) => candidate.entry), - truncated: index.truncated || matchedEntryCount > limit, - }; -} diff --git a/apps/server/src/wsServer.test.ts b/apps/server/src/wsServer.test.ts index 0e06650fe6..4fa281d29f 100644 --- a/apps/server/src/wsServer.test.ts +++ b/apps/server/src/wsServer.test.ts @@ -4,7 +4,17 @@ import os from "node:os"; import path from "node:path"; import * as NodeServices from "@effect/platform-node/NodeServices"; -import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect"; +import { + Effect, + Exit, + Fiber, + Layer, + ManagedRuntime, + PlatformError, + PubSub, + Scope, + Stream, +} from "effect"; import { describe, expect, it, afterEach, vi } from "vitest"; import { createServer } from "./wsServer"; import WebSocket from "ws"; @@ -475,6 +485,7 @@ function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) { describe("WebSocket Server", () => { let server: Http.Server | null = null; let serverScope: Scope.Closeable | null = null; + let disposeServerRuntime: (() => Promise) | null = null; const connections: WebSocket[] = []; const tempDirs: string[] = []; @@ -521,6 +532,12 @@ describe("WebSocket Server", () => { options.providerRegistry ?? defaultProviderRegistryService, ); const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService); + const nodeServicesLayer = NodeServices.layer; + const serverSettingsLayer = ServerSettingsService.layerTest(options.serverSettings); + const serverSettingsRuntimeLayer = serverSettingsLayer.pipe( + Layer.provideMerge(nodeServicesLayer), + ); + const analyticsLayer = AnalyticsService.layerTest; const serverConfigLayer = Layer.succeed(ServerConfig, { mode: "web", port: 0, @@ -536,6 +553,11 @@ describe("WebSocket Server", () => { logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl), } satisfies ServerConfigShape); const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer)); + const providerRuntimeLayer = infrastructureLayer.pipe( + Layer.provideMerge(serverConfigLayer), + Layer.provideMerge(serverSettingsRuntimeLayer), + Layer.provideMerge(analyticsLayer), + ); const runtimeOverrides = Layer.mergeAll( options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty, options.gitCore @@ -548,41 +570,49 @@ describe("WebSocket Server", () => { const runtimeLayer = Layer.merge( Layer.merge( - makeServerRuntimeServicesLayer().pipe(Layer.provide(infrastructureLayer)), - infrastructureLayer, + makeServerRuntimeServicesLayer().pipe( + Layer.provideMerge(providerRuntimeLayer), + Layer.provideMerge(serverConfigLayer), + Layer.provideMerge(serverSettingsRuntimeLayer), + Layer.provideMerge(analyticsLayer), + Layer.provideMerge(nodeServicesLayer), + ), + Layer.mergeAll(providerRuntimeLayer, serverSettingsRuntimeLayer, analyticsLayer), ), runtimeOverrides, ); - const dependenciesLayer = Layer.empty.pipe( - Layer.provideMerge(runtimeLayer), - Layer.provideMerge(providerRegistryLayer), - Layer.provideMerge(openLayer), - Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)), - Layer.provideMerge(serverConfigLayer), - Layer.provideMerge(AnalyticsService.layerTest), - Layer.provideMerge(NodeServices.layer), + const dependenciesLayer = Layer.mergeAll( + runtimeLayer, + providerRegistryLayer, + openLayer, + serverConfigLayer, + nodeServicesLayer, ); - const runtimeServices = await Effect.runPromise( - Layer.build(dependenciesLayer).pipe(Scope.provide(scope)), - ); - + const runtime = ManagedRuntime.make(dependenciesLayer); try { - const runtime = await Effect.runPromise( - createServer().pipe(Effect.provide(runtimeServices), Scope.provide(scope)), - ); + const httpServer = await runtime.runPromise(createServer().pipe(Scope.provide(scope))); + disposeServerRuntime = () => runtime.dispose(); serverScope = scope; - return runtime; + return httpServer; } catch (error) { + await runtime.dispose(); await Effect.runPromise(Scope.close(scope, Exit.void)); throw error; } } async function closeTestServer() { - if (!serverScope) return; + if (!serverScope && !disposeServerRuntime) return; const scope = serverScope; + const disposeRuntime = disposeServerRuntime; serverScope = null; - await Effect.runPromise(Scope.close(scope, Exit.void)); + disposeServerRuntime = null; + if (scope) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } + if (disposeRuntime) { + await disposeRuntime(); + } } afterEach(async () => { @@ -1255,6 +1285,32 @@ describe("WebSocket Server", () => { expect(response.error?.message).toContain("exceeds current turn count"); }); + it("rejects project.create when the workspace root does not exist", async () => { + server = await createTestServer({ cwd: "/test" }); + const addr = server.address(); + const port = typeof addr === "object" && addr !== null ? addr.port : 0; + + const [ws] = await connectAndAwaitWelcome(port); + connections.push(ws); + + const missingWorkspaceRoot = path.join(makeTempDir("t3code-ws-project-missing-"), "missing"); + const response = await sendRequest(ws, ORCHESTRATION_WS_METHODS.dispatchCommand, { + type: "project.create", + commandId: "cmd-ws-project-create-missing", + projectId: "project-missing", + title: "Missing Project", + workspaceRoot: missingWorkspaceRoot, + defaultModelSelection: { + provider: "codex", + model: "gpt-5-codex", + }, + createdAt: new Date().toISOString(), + }); + + expect(response.result).toBeUndefined(); + expect(response.error?.message).toContain("Workspace root does not exist:"); + }); + it("keeps orchestration domain push behavior for provider runtime events", async () => { const runtimeEventPubSub = Effect.runSync(PubSub.unbounded()); const emitRuntimeEvent = (event: ProviderRuntimeEvent) => { @@ -1665,6 +1721,50 @@ describe("WebSocket Server", () => { ); }); + it("invalidates workspace entry search cache after projects.writeFile", async () => { + const workspace = makeTempDir("t3code-ws-write-file-invalidate-"); + fs.mkdirSync(path.join(workspace, "src"), { recursive: true }); + fs.writeFileSync(path.join(workspace, "src", "existing.ts"), "export {};\n", "utf8"); + + server = await createTestServer({ cwd: "/test" }); + const addr = server.address(); + const port = typeof addr === "object" && addr !== null ? addr.port : 0; + + const [ws] = await connectAndAwaitWelcome(port); + connections.push(ws); + + const beforeWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { + cwd: workspace, + query: "rpc", + limit: 10, + }); + expect(beforeWrite.error).toBeUndefined(); + expect(beforeWrite.result).toEqual({ + entries: [], + truncated: false, + }); + + const writeResponse = await sendRequest(ws, WS_METHODS.projectsWriteFile, { + cwd: workspace, + relativePath: "plans/effect-rpc.md", + contents: "# Plan\n", + }); + expect(writeResponse.error).toBeUndefined(); + + const afterWrite = await sendRequest(ws, WS_METHODS.projectsSearchEntries, { + cwd: workspace, + query: "rpc", + limit: 10, + }); + expect(afterWrite.error).toBeUndefined(); + expect(afterWrite.result).toEqual({ + entries: expect.arrayContaining([ + expect.objectContaining({ path: "plans/effect-rpc.md", kind: "file" }), + ]), + truncated: false, + }); + }); + it("rejects projects.writeFile paths outside the workspace root", async () => { const workspace = makeTempDir("t3code-ws-write-file-reject-"); @@ -1683,7 +1783,7 @@ describe("WebSocket Server", () => { expect(response.result).toBeUndefined(); expect(response.error?.message).toContain( - "Workspace file path must stay within the project root.", + "Workspace file path must be relative to the project root: ../escape.md", ); expect(fs.existsSync(path.join(workspace, "..", "escape.md"))).toBe(false); }); diff --git a/apps/server/src/wsServer.ts b/apps/server/src/wsServer.ts index 25f8158926..b9fd7e58df 100644 --- a/apps/server/src/wsServer.ts +++ b/apps/server/src/wsServer.ts @@ -50,7 +50,6 @@ import { GitManager } from "./git/Services/GitManager.ts"; import { TerminalManager } from "./terminal/Services/Manager.ts"; import { Keybindings } from "./keybindings"; import { ServerSettingsService } from "./serverSettings"; -import { searchWorkspaceEntries } from "./workspaceEntries"; import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; @@ -75,10 +74,13 @@ import { } from "./attachmentStore.ts"; import { parseBase64DataUrl } from "./imageMime.ts"; import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts"; -import { expandHomePath } from "./os-jank.ts"; import { makeServerPushBus } from "./wsServer/pushBus.ts"; import { makeServerReadiness } from "./wsServer/readiness.ts"; import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson"; +import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts"; +import { WorkspaceEntries } from "./workspace/Services/WorkspaceEntries.ts"; +import { WorkspaceFileSystem } from "./workspace/Services/WorkspaceFileSystem.ts"; +import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts"; /** * ServerShape - Service API for server lifecycle control. @@ -154,48 +156,6 @@ function websocketRawToString(raw: unknown): string | null { return null; } -function toPosixRelativePath(input: string): string { - return input.replaceAll("\\", "/"); -} - -function resolveWorkspaceWritePath(params: { - workspaceRoot: string; - relativePath: string; - path: Path.Path; -}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> { - const normalizedInputPath = params.relativePath.trim(); - if (params.path.isAbsolute(normalizedInputPath)) { - return Effect.fail( - new RouteRequestError({ - message: "Workspace file path must be relative to the project root.", - }), - ); - } - - const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath); - const relativeToRoot = toPosixRelativePath( - params.path.relative(params.workspaceRoot, absolutePath), - ); - if ( - relativeToRoot.length === 0 || - relativeToRoot === "." || - relativeToRoot.startsWith("../") || - relativeToRoot === ".." || - params.path.isAbsolute(relativeToRoot) - ) { - return Effect.fail( - new RouteRequestError({ - message: "Workspace file path must stay within the project root.", - }), - ); - } - - return Effect.succeed({ - absolutePath, - relativePath: relativeToRoot, - }); -} - function stripRequestTag(body: T) { return Struct.omit(body, ["_tag"]); } @@ -218,6 +178,10 @@ export type ServerRuntimeServices = | TerminalManager | Keybindings | ServerSettingsService + | ProjectFaviconResolver + | WorkspaceEntries + | WorkspaceFileSystem + | WorkspacePaths | Open | AnalyticsService; @@ -263,6 +227,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< const serverSettingsManager = yield* ServerSettingsService; const providerRegistry = yield* ProviderRegistry; const git = yield* GitCore; + const workspaceEntries = yield* WorkspaceEntries; + const workspaceFileSystem = yield* WorkspaceFileSystem; + const workspacePaths = yield* WorkspacePaths; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -312,35 +279,21 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< const normalizeDispatchCommand = Effect.fnUntraced(function* (input: { readonly command: ClientOrchestrationCommand; }) { - const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) { - const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim())); - const workspaceStat = yield* fileSystem - .stat(normalizedWorkspaceRoot) - .pipe(Effect.catch(() => Effect.succeed(null))); - if (!workspaceStat) { - return yield* new RouteRequestError({ - message: `Project directory does not exist: ${normalizedWorkspaceRoot}`, - }); - } - if (workspaceStat.type !== "Directory") { - return yield* new RouteRequestError({ - message: `Project path is not a directory: ${normalizedWorkspaceRoot}`, - }); - } - return normalizedWorkspaceRoot; - }); - if (input.command.type === "project.create") { return { ...input.command, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot), + workspaceRoot: yield* workspacePaths + .normalizeWorkspaceRoot(input.command.workspaceRoot) + .pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))), } satisfies OrchestrationCommand; } if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) { return { ...input.command, - workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot), + workspaceRoot: yield* workspacePaths + .normalizeWorkspaceRoot(input.command.workspaceRoot) + .pipe(Effect.mapError((cause) => new RouteRequestError({ message: cause.message }))), } satisfies OrchestrationCommand; } @@ -437,7 +390,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< void runPromise( Effect.gen(function* () { const url = new URL(req.url ?? "/", `http://localhost:${port}`); - if (tryHandleProjectFaviconRequest(url, res)) { + if (yield* tryHandleProjectFaviconRequest(url, res)) { return; } @@ -768,41 +721,26 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return< case WS_METHODS.projectsSearchEntries: { const body = stripRequestTag(request.body); - return yield* Effect.tryPromise({ - try: () => searchWorkspaceEntries(body), - catch: (cause) => - new RouteRequestError({ - message: `Failed to search workspace entries: ${String(cause)}`, - }), - }); + return yield* workspaceEntries.search(body).pipe( + Effect.mapError( + (cause) => + new RouteRequestError({ + message: `Failed to search workspace entries: ${cause.detail}`, + }), + ), + ); } case WS_METHODS.projectsWriteFile: { const body = stripRequestTag(request.body); - const target = yield* resolveWorkspaceWritePath({ - workspaceRoot: body.cwd, - relativePath: body.relativePath, - path, - }); - yield* fileSystem - .makeDirectory(path.dirname(target.absolutePath), { recursive: true }) - .pipe( - Effect.mapError( - (cause) => - new RouteRequestError({ - message: `Failed to prepare workspace path: ${String(cause)}`, - }), - ), - ); - yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe( + return yield* workspaceFileSystem.writeFile(body).pipe( Effect.mapError( (cause) => new RouteRequestError({ - message: `Failed to write workspace file: ${String(cause)}`, + message: `Failed to write workspace file: ${cause.message}`, }), ), ); - return { relativePath: target.relativePath }; } case WS_METHODS.shellOpenInEditor: { From aa5521dcfb709ddd3f3d079e70efb71916e74fe4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 31 Mar 2026 15:10:16 -0700 Subject: [PATCH 61/66] Map fatal Codex stderr to runtime errors (#1615) --- .../src/provider/Layers/CodexAdapter.test.ts | 36 +++++++++++++++++++ .../src/provider/Layers/CodexAdapter.ts | 35 +++++++++++++----- 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/apps/server/src/provider/Layers/CodexAdapter.test.ts b/apps/server/src/provider/Layers/CodexAdapter.test.ts index 7ddbdbfc98..b5eb873e85 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.test.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.test.ts @@ -508,6 +508,42 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => { }), ); + it.effect("maps fatal websocket stderr notifications to runtime.error", () => + Effect.gen(function* () { + const adapter = yield* CodexAdapter; + const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild); + + lifecycleManager.emit("event", { + id: asEventId("evt-process-stderr-websocket"), + kind: "notification", + provider: "codex", + threadId: asThreadId("thread-1"), + createdAt: new Date().toISOString(), + method: "process/stderr", + turnId: asTurnId("turn-1"), + message: + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + } satisfies ProviderEvent); + + const firstEvent = yield* Fiber.join(firstEventFiber); + + assert.equal(firstEvent._tag, "Some"); + if (firstEvent._tag !== "Some") { + return; + } + assert.equal(firstEvent.value.type, "runtime.error"); + if (firstEvent.value.type !== "runtime.error") { + return; + } + assert.equal(firstEvent.value.turnId, "turn-1"); + assert.equal(firstEvent.value.payload.class, "provider_error"); + assert.equal( + firstEvent.value.payload.message, + "2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses", + ); + }), + ); + it.effect("preserves request type when mapping serverRequest/resolved", () => Effect.gen(function* () { const adapter = yield* CodexAdapter; diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index b9ac4bfc4a..cee6bca6ed 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -112,6 +112,13 @@ function asNumber(value: unknown): number | undefined { return typeof value === "number" && Number.isFinite(value) ? value : undefined; } +const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"]; + +function isFatalCodexProcessStderrMessage(message: string): boolean { + const normalized = message.toLowerCase(); + return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet)); +} + function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined { const usage = asObject(value); const totalUsage = asObject(usage?.total_token_usage ?? usage?.total); @@ -1269,15 +1276,27 @@ function mapToRuntimeEvents( } if (event.method === "process/stderr") { + const message = event.message ?? "Codex process stderr"; + const isFatal = isFatalCodexProcessStderrMessage(message); return [ - { - type: "runtime.warning", - ...runtimeEventBase(event, canonicalThreadId), - payload: { - message: event.message ?? "Codex process stderr", - ...(event.payload !== undefined ? { detail: event.payload } : {}), - }, - }, + isFatal + ? { + type: "runtime.error", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + class: "provider_error" as const, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + } + : { + type: "runtime.warning", + ...runtimeEventBase(event, canonicalThreadId), + payload: { + message, + ...(event.payload !== undefined ? { detail: event.payload } : {}), + }, + }, ]; } From 19eb9e7227b2daad4e77fc2ae91814c1dae0875d Mon Sep 17 00:00:00 2001 From: EDM115 Date: Wed, 1 Apr 2026 03:02:09 +0200 Subject: [PATCH 62/66] fix(server): parse git branches correctly when column.ui is enabled (#1529) Co-authored-by: Julius Marminge --- apps/server/src/git/Layers/GitCore.test.ts | 60 +++++++++++++++++++++- apps/server/src/git/Layers/GitCore.ts | 7 +-- 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/apps/server/src/git/Layers/GitCore.test.ts b/apps/server/src/git/Layers/GitCore.test.ts index 135834f891..5c42e6e87f 100644 --- a/apps/server/src/git/Layers/GitCore.test.ts +++ b/apps/server/src/git/Layers/GitCore.test.ts @@ -369,6 +369,64 @@ it.layer(TestLayer)("git integration", (it) => { }), ); + it.effect("parses separate branch names when column.ui is always enabled", () => + Effect.gen(function* () { + const tmp = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(tmp); + const createdBranchNames = [ + "go-bin", + "copilot/rewrite-cli-in-go", + "copilot/rewrite-cli-in-rust", + ] as const; + for (const branchName of createdBranchNames) { + yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName }); + } + yield* git(tmp, ["config", "column.ui", "always"]); + + const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], { + ...process.env, + COLUMNS: "120", + }); + expect( + rawBranchOutput + .split("\n") + .some( + (line) => + createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2, + ), + ).toBe(true); + + const realGitCore = yield* GitCore; + const core = yield* makeIsolatedGitCore((input) => + realGitCore.execute( + input.args[0] === "branch" + ? { + ...input, + env: { ...input.env, COLUMNS: "120" }, + } + : input, + ), + ); + + const result = yield* core.listBranches({ cwd: tmp }); + const localBranchNames = result.branches + .filter((branch) => !branch.isRemote) + .map((branch) => branch.name); + + expect(localBranchNames).toHaveLength(4); + expect(localBranchNames).toEqual( + expect.arrayContaining([initialBranch, ...createdBranchNames]), + ); + expect( + localBranchNames.some( + (branchName) => + createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch)) + .length >= 2, + ), + ).toBe(false); + }), + ); + it.effect("isDefault is false when no remote exists", () => Effect.gen(function* () { const tmp = yield* makeTmpDir(); @@ -1898,7 +1956,7 @@ it.layer(TestLayer)("git integration", (it) => { let didFailRemoteBranches = false; let didFailRemoteNames = false; const core = yield* makeIsolatedGitCore((input) => { - if (input.args.join(" ") === "branch --no-color --remotes") { + if (input.args.join(" ") === "branch --no-color --no-column --remotes") { didFailRemoteBranches = true; return Effect.fail( new GitCommandError({ diff --git a/apps/server/src/git/Layers/GitCore.ts b/apps/server/src/git/Layers/GitCore.ts index 81d6cbb549..9ef11eecf9 100644 --- a/apps/server/src/git/Layers/GitCore.ts +++ b/apps/server/src/git/Layers/GitCore.ts @@ -1566,7 +1566,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const localBranchResult = yield* executeGit( "GitCore.listBranches.branchNoColor", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], { timeoutMs: 10_000, allowNonZeroExit: true, @@ -1581,7 +1581,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { return yield* createGitCommandError( "GitCore.listBranches", input.cwd, - ["branch", "--no-color"], + ["branch", "--no-color", "--no-column"], stderr || "git branch failed", ); } @@ -1589,7 +1589,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { const remoteBranchResultEffect = executeGit( "GitCore.listBranches.remoteBranches", input.cwd, - ["branch", "--no-color", "--remotes"], + ["branch", "--no-color", "--no-column", "--remotes"], { timeoutMs: 10_000, allowNonZeroExit: true, @@ -1957,6 +1957,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: { runGitStdout("GitCore.listLocalBranchNames", cwd, [ "branch", "--list", + "--no-column", "--format=%(refname:short)", ]).pipe( Effect.map((stdout) => From 0bc94bc24ec221e2ea7c370c9bfb2b06af9ae573 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Wed, 1 Apr 2026 07:10:14 +0530 Subject: [PATCH 63/66] fixing the input ui at certain endpoints causing the button to overflow. (#1574) --- apps/web/src/components/ChatView.browser.tsx | 316 +++++++++++++++++- apps/web/src/components/ChatView.tsx | 288 +++++++--------- .../chat/ComposerPrimaryActions.tsx | 217 ++++++++++++ .../components/chat/ProviderModelPicker.tsx | 5 +- .../components/composerFooterLayout.test.ts | 119 +++++++ .../src/components/composerFooterLayout.ts | 59 +++- 6 files changed, 831 insertions(+), 173 deletions(-) create mode 100644 apps/web/src/components/chat/ComposerPrimaryActions.tsx diff --git a/apps/web/src/components/ChatView.browser.tsx b/apps/web/src/components/ChatView.browser.tsx index 20816d6935..e6dcc4f637 100644 --- a/apps/web/src/components/ChatView.browser.tsx +++ b/apps/web/src/components/ChatView.browser.tsx @@ -11,6 +11,7 @@ import { type ProjectId, type ServerConfig, type ThreadId, + type TurnId, type WsWelcomePayload, WS_CHANNELS, WS_METHODS, @@ -79,6 +80,20 @@ const DEFAULT_VIEWPORT: ViewportSpec = { textTolerancePx: 44, attachmentTolerancePx: 56, }; +const WIDE_FOOTER_VIEWPORT: ViewportSpec = { + name: "wide-footer", + width: 1_400, + height: 1_100, + textTolerancePx: 44, + attachmentTolerancePx: 56, +}; +const COMPACT_FOOTER_VIEWPORT: ViewportSpec = { + name: "compact-footer", + width: 430, + height: 932, + textTolerancePx: 56, + attachmentTolerancePx: 56, +}; const TEXT_VIEWPORT_MATRIX = [ DEFAULT_VIEWPORT, { name: "tablet", width: 720, height: 1_024, textTolerancePx: 44, attachmentTolerancePx: 56 }, @@ -102,6 +117,7 @@ interface MountedChatView { cleanup: () => Promise; measureUserRow: (targetMessageId: MessageId) => Promise; setViewport: (viewport: ViewportSpec) => Promise; + setContainerSize: (viewport: Pick) => Promise; router: ReturnType; } @@ -513,6 +529,114 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel { }; } +function createSnapshotWithPendingUserInput(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-pending-input-target" as MessageId, + targetText: "question thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + activities: [ + { + id: EventId.makeUnsafe("activity-user-input-requested"), + tone: "info", + kind: "user-input.requested", + summary: "User input requested", + payload: { + requestId: "req-browser-user-input", + questions: [ + { + id: "scope", + header: "Scope", + question: "What should this change cover?", + options: [ + { + label: "Tight", + description: "Touch only the footer layout logic.", + }, + { + label: "Broad", + description: "Also adjust the related composer controls.", + }, + ], + }, + { + id: "risk", + header: "Risk", + question: "How aggressive should the imaginary plan be?", + options: [ + { + label: "Conservative", + description: "Favor reliability and low-risk changes.", + }, + { + label: "Balanced", + description: "Mix quick wins with one structural improvement.", + }, + ], + }, + ], + }, + turnId: null, + sequence: 1, + createdAt: isoAt(1_000), + }, + ], + updatedAt: isoAt(1_000), + }) + : thread, + ), + }; +} + +function createSnapshotWithPlanFollowUpPrompt(): OrchestrationReadModel { + const snapshot = createSnapshotForTargetUser({ + targetMessageId: "msg-user-plan-follow-up-target" as MessageId, + targetText: "plan follow-up thread", + }); + + return { + ...snapshot, + threads: snapshot.threads.map((thread) => + thread.id === THREAD_ID + ? Object.assign({}, thread, { + interactionMode: "plan", + latestTurn: { + turnId: "turn-plan-follow-up" as TurnId, + state: "completed", + requestedAt: isoAt(1_000), + startedAt: isoAt(1_001), + completedAt: isoAt(1_010), + assistantMessageId: null, + }, + proposedPlans: [ + { + id: "plan-follow-up-browser-test", + turnId: "turn-plan-follow-up" as TurnId, + planMarkdown: "# Follow-up plan\n\n- Keep the composer footer stable on resize.", + implementedAt: null, + implementationThreadId: null, + createdAt: isoAt(1_002), + updatedAt: isoAt(1_003), + }, + ], + session: { + ...thread.session, + status: "ready", + updatedAt: isoAt(1_010), + }, + updatedAt: isoAt(1_010), + }) + : thread, + ), + }; +} + function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown { const customResult = customWsRpcResolver?.(body); if (customResult !== undefined) { @@ -694,6 +818,13 @@ async function waitForComposerEditor(): Promise { ); } +async function waitForComposerMenuItem(itemId: string): Promise { + return waitForElement( + () => document.querySelector(`[data-composer-item-id="${itemId}"]`), + `Unable to find composer menu item "${itemId}".`, + ); +} + async function waitForSendButton(): Promise { return waitForElement( () => document.querySelector('button[aria-label="Send message"]'), @@ -701,6 +832,62 @@ async function waitForSendButton(): Promise { ); } +function findComposerProviderModelPicker(): HTMLButtonElement | null { + return document.querySelector('[data-chat-provider-model-picker="true"]'); +} + +function findButtonByText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find( + (button) => button.textContent?.trim() === text, + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonByText(text: string): Promise { + return waitForElement(() => findButtonByText(text), `Unable to find "${text}" button.`); +} + +function findButtonContainingText(text: string): HTMLButtonElement | null { + return (Array.from(document.querySelectorAll("button")).find((button) => + button.textContent?.includes(text), + ) ?? null) as HTMLButtonElement | null; +} + +async function waitForButtonContainingText(text: string): Promise { + return waitForElement( + () => findButtonContainingText(text), + `Unable to find button containing "${text}".`, + ); +} + +async function expectComposerActionsContained(): Promise { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const actions = await waitForElement( + () => document.querySelector('[data-chat-composer-actions="right"]'), + "Unable to find composer actions container.", + ); + + await vi.waitFor( + () => { + const footerRect = footer.getBoundingClientRect(); + const actionButtons = Array.from(actions.querySelectorAll("button")); + expect(actionButtons.length).toBeGreaterThanOrEqual(1); + + const buttonRects = actionButtons.map((button) => button.getBoundingClientRect()); + const firstTop = buttonRects[0]?.top ?? 0; + + for (const rect of buttonRects) { + expect(rect.right).toBeLessThanOrEqual(footerRect.right + 0.5); + expect(rect.bottom).toBeLessThanOrEqual(footerRect.bottom + 0.5); + expect(Math.abs(rect.top - firstTop)).toBeLessThanOrEqual(1.5); + } + }, + { timeout: 8_000, interval: 16 }, + ); +} + async function waitForInteractionModeButton( expectedLabel: "Chat" | "Plan", ): Promise { @@ -864,7 +1051,8 @@ async function mountChatView(options: { const host = document.createElement("div"); host.style.position = "fixed"; - host.style.inset = "0"; + host.style.top = "0"; + host.style.left = "0"; host.style.width = "100vw"; host.style.height = "100vh"; host.style.display = "grid"; @@ -897,6 +1085,11 @@ async function mountChatView(options: { await setViewport(viewport); await waitForProductionStyles(); }, + setContainerSize: async (viewport) => { + host.style.width = `${viewport.width}px`; + host.style.height = `${viewport.height}px`; + await waitForLayout(); + }, router, }; } @@ -2341,4 +2534,125 @@ describe("ChatView timeline estimator parity (full app)", () => { await mounted.cleanup(); } }); + + it("keeps pending-question footer actions inside the composer after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPendingUserInput(), + }); + + try { + const firstOption = await waitForButtonContainingText("Tight"); + firstOption.click(); + + await waitForButtonByText("Previous"); + await waitForButtonByText("Submit answers"); + + await mounted.setContainerSize(COMPACT_FOOTER_VIEWPORT); + await expectComposerActionsContained(); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps plan follow-up footer actions fused and aligned after a real resize", async () => { + const mounted = await mountChatView({ + viewport: WIDE_FOOTER_VIEWPORT, + snapshot: createSnapshotWithPlanFollowUpPrompt(), + }); + + try { + const footer = await waitForElement( + () => document.querySelector('[data-chat-composer-footer="true"]'), + "Unable to find composer footer.", + ); + const initialModelPicker = await waitForElement( + findComposerProviderModelPicker, + "Unable to find provider model picker.", + ); + const initialModelPickerOffset = + initialModelPicker.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + await waitForButtonByText("Implement"); + await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await mounted.setContainerSize({ + width: 440, + height: WIDE_FOOTER_VIEWPORT.height, + }); + await expectComposerActionsContained(); + + const implementButton = await waitForButtonByText("Implement"); + const implementActionsButton = await waitForElement( + () => + document.querySelector('button[aria-label="Implementation actions"]'), + "Unable to find implementation actions trigger.", + ); + + await vi.waitFor( + () => { + const implementRect = implementButton.getBoundingClientRect(); + const implementActionsRect = implementActionsButton.getBoundingClientRect(); + const compactModelPicker = findComposerProviderModelPicker(); + expect(compactModelPicker).toBeTruthy(); + + const compactModelPickerOffset = + compactModelPicker!.getBoundingClientRect().left - footer.getBoundingClientRect().left; + + expect(Math.abs(implementRect.right - implementActionsRect.left)).toBeLessThanOrEqual(1); + expect(Math.abs(implementRect.top - implementActionsRect.top)).toBeLessThanOrEqual(1); + expect(Math.abs(compactModelPickerOffset - initialModelPickerOffset)).toBeLessThanOrEqual( + 1, + ); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); + + it("keeps the slash-command menu visible above the composer", async () => { + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotForTargetUser({ + targetMessageId: "msg-user-command-menu-target" as MessageId, + targetText: "command menu thread", + }), + }); + + try { + await waitForComposerEditor(); + await page.getByTestId("composer-editor").fill("/"); + + const menuItem = await waitForComposerMenuItem("slash:model"); + const composerForm = await waitForElement( + () => document.querySelector('[data-chat-composer-form="true"]'), + "Unable to find composer form.", + ); + + await vi.waitFor( + () => { + const menuRect = menuItem.getBoundingClientRect(); + const composerRect = composerForm.getBoundingClientRect(); + const hitTarget = document.elementFromPoint( + menuRect.left + menuRect.width / 2, + menuRect.top + menuRect.height / 2, + ); + + expect(menuRect.width).toBeGreaterThan(0); + expect(menuRect.height).toBeGreaterThan(0); + expect(menuRect.bottom).toBeLessThanOrEqual(composerRect.bottom); + expect(hitTarget instanceof Element && menuItem.contains(hitTarget)).toBe(true); + }, + { timeout: 8_000, interval: 16 }, + ); + } finally { + await mounted.cleanup(); + } + }); }); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 7562f845e2..d4f304f837 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -106,7 +106,6 @@ import { } from "lucide-react"; import { Button } from "./ui/button"; import { Separator } from "./ui/separator"; -import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu"; import { cn, randomUUID } from "~/lib/utils"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { toastManager } from "./ui/toast"; @@ -148,7 +147,12 @@ import { type TerminalContextSelection, } from "../lib/terminalContext"; import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow"; -import { shouldUseCompactComposerFooter } from "./composerFooterLayout"; +import { + resolveComposerFooterContentWidth, + shouldForceCompactComposerFooterForFit, + shouldUseCompactComposerPrimaryActions, + shouldUseCompactComposerFooter, +} from "./composerFooterLayout"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; @@ -160,6 +164,7 @@ import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/Provider import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu"; import { ComposerPendingApprovalActions } from "./chat/ComposerPendingApprovalActions"; import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu"; +import { ComposerPrimaryActions } from "./chat/ComposerPrimaryActions"; import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel"; import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel"; import { ComposerPlanFollowUpBanner } from "./chat/ComposerPlanFollowUpBanner"; @@ -499,6 +504,7 @@ export default function ChatView({ threadId }: ChatViewProps) { const [expandedWorkGroups, setExpandedWorkGroups] = useState>({}); const [planSidebarOpen, setPlanSidebarOpen] = useState(false); const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); + const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); // Tracks whether the user explicitly dismissed the sidebar for the active turn. const planSidebarDismissedForTurnRef = useRef(null); // When set, the thread-change reset effect will open the sidebar instead of closing it. @@ -541,6 +547,9 @@ export default function ChatView({ threadId }: ChatViewProps) { const composerEditorRef = useRef(null); const composerFormRef = useRef(null); const composerFormHeightRef = useRef(0); + const composerFooterRef = useRef(null); + const composerFooterLeadingRef = useRef(null); + const composerFooterActionsRef = useRef(null); const composerImagesRef = useRef([]); const composerSelectLockRef = useRef(false); const composerMenuOpenRef = useRef(false); @@ -930,6 +939,28 @@ export default function ChatView({ threadId }: ChatViewProps) { pendingUserInputs.length > 0 || (showPlanFollowUpPrompt && activeProposedPlan !== null); const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null; + const composerFooterActionLayoutKey = useMemo(() => { + if (activePendingProgress) { + return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`; + } + if (phase === "running") { + return "running"; + } + if (showPlanFollowUpPrompt) { + return prompt.trim().length > 0 ? "plan:refine" : "plan:implement"; + } + return `idle:${composerSendState.hasSendableContent}:${isSendBusy}:${isConnecting}:${isPreparingWorktree}`; + }, [ + activePendingIsResponding, + activePendingProgress, + composerSendState.hasSendableContent, + isConnecting, + isPreparingWorktree, + isSendBusy, + phase, + prompt, + showPlanFollowUpPrompt, + ]); const lastSyncedPendingInputRef = useRef<{ requestId: string | null; questionId: string | null; @@ -2038,23 +2069,56 @@ export default function ChatView({ threadId }: ChatViewProps) { const composerForm = composerFormRef.current; if (!composerForm) return; const measureComposerFormWidth = () => composerForm.clientWidth; + const measureFooterCompactness = () => { + const composerFormWidth = measureComposerFormWidth(); + const heuristicFooterCompact = shouldUseCompactComposerFooter(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + const footer = composerFooterRef.current; + const footerStyle = footer ? window.getComputedStyle(footer) : null; + const footerContentWidth = resolveComposerFooterContentWidth({ + footerWidth: footer?.clientWidth ?? null, + paddingLeft: footerStyle ? Number.parseFloat(footerStyle.paddingLeft) : null, + paddingRight: footerStyle ? Number.parseFloat(footerStyle.paddingRight) : null, + }); + const fitInput = { + footerContentWidth, + leadingContentWidth: composerFooterLeadingRef.current?.scrollWidth ?? null, + actionsWidth: composerFooterActionsRef.current?.scrollWidth ?? null, + }; + const nextFooterCompact = + heuristicFooterCompact || shouldForceCompactComposerFooterForFit(fitInput); + const nextPrimaryActionsCompact = + nextFooterCompact && + shouldUseCompactComposerPrimaryActions(composerFormWidth, { + hasWideActions: composerFooterHasWideActions, + }); + + return { + primaryActionsCompact: nextPrimaryActionsCompact, + footerCompact: nextFooterCompact, + }; + }; composerFormHeightRef.current = composerForm.getBoundingClientRect().height; - setIsComposerFooterCompact( - shouldUseCompactComposerFooter(measureComposerFormWidth(), { - hasWideActions: composerFooterHasWideActions, - }), - ); + const initialCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact(initialCompactness.primaryActionsCompact); + setIsComposerFooterCompact(initialCompactness.footerCompact); if (typeof ResizeObserver === "undefined") return; const observer = new ResizeObserver((entries) => { const [entry] = entries; if (!entry) return; - const nextCompact = shouldUseCompactComposerFooter(measureComposerFormWidth(), { - hasWideActions: composerFooterHasWideActions, - }); - setIsComposerFooterCompact((previous) => (previous === nextCompact ? previous : nextCompact)); + const nextCompactness = measureFooterCompactness(); + setIsComposerPrimaryActionsCompact((previous) => + previous === nextCompactness.primaryActionsCompact + ? previous + : nextCompactness.primaryActionsCompact, + ); + setIsComposerFooterCompact((previous) => + previous === nextCompactness.footerCompact ? previous : nextCompactness.footerCompact, + ); const nextHeight = entry.contentRect.height; const previousHeight = composerFormHeightRef.current; @@ -2069,7 +2133,12 @@ export default function ChatView({ threadId }: ChatViewProps) { return () => { observer.disconnect(); }; - }, [activeThread?.id, composerFooterHasWideActions, scheduleStickToBottom]); + }, [ + activeThread?.id, + composerFooterActionLayoutKey, + composerFooterHasWideActions, + scheduleStickToBottom, + ]); useEffect(() => { if (!shouldAutoScrollRef.current) return; scheduleStickToBottom(); @@ -3788,7 +3857,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
) : (
@@ -4113,8 +4183,12 @@ export default function ChatView({ threadId }: ChatViewProps) { {/* Right side: send / stop button */}
{activeContextWindow ? ( @@ -4124,156 +4198,32 @@ export default function ChatView({ threadId }: ChatViewProps) { Preparing worktree... ) : null} - {activePendingProgress ? ( -
- {activePendingProgress.questionIndex > 0 ? ( - - ) : null} - -
- ) : phase === "running" ? ( - - ) : pendingUserInputs.length === 0 ? ( - showPlanFollowUpPrompt ? ( - prompt.trim().length > 0 ? ( - - ) : ( -
- - - - } - > - - - - void onImplementPlanInNewThread()} - > - Implement in a new thread - - - -
- ) - ) : ( - - ) - ) : null} + 0} + isSendBusy={isSendBusy} + isConnecting={isConnecting} + isPreparingWorktree={isPreparingWorktree} + hasSendableContent={composerSendState.hasSendableContent} + onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} + onInterrupt={() => void onInterrupt()} + onImplementPlanInNewThread={() => void onImplementPlanInNewThread()} + />
)} diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsx new file mode 100644 index 0000000000..09b343c900 --- /dev/null +++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx @@ -0,0 +1,217 @@ +import { memo } from "react"; +import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react"; +import { cn } from "~/lib/utils"; +import { Button } from "../ui/button"; +import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu"; + +interface PendingActionState { + questionIndex: number; + isLastQuestion: boolean; + canAdvance: boolean; + isResponding: boolean; + isComplete: boolean; +} + +interface ComposerPrimaryActionsProps { + compact: boolean; + pendingAction: PendingActionState | null; + isRunning: boolean; + showPlanFollowUpPrompt: boolean; + promptHasText: boolean; + isSendBusy: boolean; + isConnecting: boolean; + isPreparingWorktree: boolean; + hasSendableContent: boolean; + onPreviousPendingQuestion: () => void; + onInterrupt: () => void; + onImplementPlanInNewThread: () => void; +} + +const formatPendingPrimaryActionLabel = (input: { + compact: boolean; + isLastQuestion: boolean; + isResponding: boolean; +}) => { + if (input.isResponding) { + return "Submitting..."; + } + if (input.compact) { + return input.isLastQuestion ? "Submit" : "Next"; + } + return input.isLastQuestion ? "Submit answers" : "Next question"; +}; + +export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({ + compact, + pendingAction, + isRunning, + showPlanFollowUpPrompt, + promptHasText, + isSendBusy, + isConnecting, + isPreparingWorktree, + hasSendableContent, + onPreviousPendingQuestion, + onInterrupt, + onImplementPlanInNewThread, +}: ComposerPrimaryActionsProps) { + if (pendingAction) { + return ( +
+ {pendingAction.questionIndex > 0 ? ( + compact ? ( + + ) : ( + + ) + ) : null} + +
+ ); + } + + if (isRunning) { + return ( + + ); + } + + if (showPlanFollowUpPrompt) { + if (promptHasText) { + return ( + + ); + } + + return ( +
+ + + + } + > + + + + void onImplementPlanInNewThread()} + > + Implement in a new thread + + + +
+ ); + } + + return ( + + ); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 565a9d399d..01fa37516e 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -98,6 +98,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {