diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 7a51700e0f..9795f04e8a 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -1,3 +1,9 @@ +for (const stream of [process.stdout, process.stderr]) { + stream.on("error", (err: NodeJS.ErrnoException) => { + if (err.code !== "EPIPE") throw err; + }); +} + import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient"; import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; import * as NodeServices from "@effect/platform-node/NodeServices"; diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx index e712664d30..c1a6f2c235 100644 --- a/apps/mobile/src/features/threads/ThreadComposer.tsx +++ b/apps/mobile/src/features/threads/ThreadComposer.tsx @@ -26,7 +26,13 @@ import { type ViewStyle, } from "react-native"; import ImageViewing from "react-native-image-viewing"; -import Animated, { FadeIn, FadeOut, LinearTransition } from "react-native-reanimated"; +import Animated, { + FadeIn, + FadeInDown, + FadeOut, + FadeOutDown, + LinearTransition, +} from "react-native-reanimated"; import { useThemeColor } from "../../lib/useThemeColor"; import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration"; import { scopedThreadKey } from "../../lib/scopedEntities"; @@ -232,7 +238,12 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill( const isReconnecting = props.status.kind !== "unavailable"; return ( - + - + ); }); diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 32527b0b71..5cb04290f6 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -14,21 +14,18 @@ import type { ServerConfig as T3ServerConfig, ThreadId, } from "@t3tools/contracts"; -import { formatElapsed } from "@t3tools/shared/orchestrationTiming"; import * as Haptics from "expo-haptics"; import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { Platform, View, type GestureResponderEvent } from "react-native"; import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller"; -import Animated, { FadeInDown, FadeOut, LinearTransition } from "react-native-reanimated"; +import Animated, { FadeInDown, FadeOut } from "react-native-reanimated"; import { useSafeAreaInsets } from "react-native-safe-area-context"; -import { AppText as Text } from "../../components/AppText"; import type { ComposerEditorHandle } from "../../components/ComposerEditor"; import type { StatusTone } from "../../components/StatusPill"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout"; import { scopedThreadKey } from "../../lib/scopedEntities"; -import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass"; import type { PendingApproval, PendingUserInput, @@ -172,54 +169,6 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray Date.now()); - - useEffect(() => { - const intervalId = setInterval(() => { - setNowMs(Date.now()); - }, 1_000); - return () => clearInterval(intervalId); - }, [props.startedAt]); - - const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s"; - - return ( - - - - - - - - - - Working for {durationLabel} - - - - - ); -}); - export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) { const insets = useSafeAreaInsets(); const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`; @@ -253,8 +202,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const selectedThreadFeed = props.selectedThreadFeed; const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME; const composerOverlapHeight = composerChrome + composerBottomInset; - const activeWorkIndicatorHeight = props.activeWorkStartedAt ? WORKING_INDICATOR_HEIGHT : 0; - const estimatedOverlayHeight = composerOverlapHeight + activeWorkIndicatorHeight; + const estimatedOverlayHeight = composerOverlapHeight; // The overlay's measured height includes the home-indicator inset (the // composer pads it), but contentInsetAdjustmentBehavior="automatic" makes // UIKit add the safe-area bottom to the content inset AGAIN — leaving a @@ -411,6 +359,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread contentPresentation={props.contentPresentation} agentLabel={agentLabel} latestTurn={props.selectedThread.latestTurn} + activeWorkStartedAt={props.activeWorkStartedAt} listRef={listRef} freeze={freeze} anchorMessageId={anchorMessageId} @@ -438,15 +387,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread list's bottom inset, so any padding above the pill/composer pushes the resting content floor up by the same amount. */} - - {props.activeWorkStartedAt ? ( - - ) : null} - + {props.activePendingApproval || props.activePendingUserInput ? ( ) : null} - + ; readonly freeze: SharedValue; readonly anchorMessageId: MessageId | null; @@ -816,6 +818,10 @@ function renderFeedEntry( const entry = info.item; const { markdownStyles, iconSubtleColor, userBubbleColor } = props; + if (entry.type === "working") { + return ; + } + if (entry.type === "turn-fold") { return ( Date.now()); + + useEffect(() => { + const intervalId = setInterval(() => { + setNowMs(Date.now()); + }, 1_000); + return () => clearInterval(intervalId); + }, [props.startedAt]); + + const durationLabel = formatElapsed(props.startedAt, new Date(nowMs).toISOString()) ?? "0s"; + + return ( + + + + + + + + Working for {durationLabel} + + + ); +}); + function UserMessageContent(props: { readonly text: string; readonly markdownStyles: MarkdownStyleSet; @@ -1415,8 +1447,15 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { props.latestTurn, expandedTurnIds, expandedWorkGroupIds, + props.activeWorkStartedAt, ), - [expandedTurnIds, expandedWorkGroupIds, props.feed, props.latestTurn], + [ + expandedTurnIds, + expandedWorkGroupIds, + props.activeWorkStartedAt, + props.feed, + props.latestTurn, + ], ); // The empty↔filled key below remounts the list, which resets its imperative @@ -1761,7 +1800,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) { }} /> - {props.feed.length === 0 && props.contentPresentation.kind === "ready" ? ( + {props.feed.length === 0 && + props.activeWorkStartedAt === null && + props.contentPresentation.kind === "ready" ? ( { }); }); + it("appends active work as a normal timeline row", () => { + const startedAt = "2026-04-01T00:00:01.000Z"; + const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt); + + expect(presented).toEqual([ + { + type: "working", + id: "working-indicator-row", + createdAt: startedAt, + }, + ]); + expect(deriveThreadFeedPresentation(presented, null, new Set())).toEqual([]); + }); + it("models work-log overflow as list rows", () => { const activity = ( id: string, diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 9f79a90550..6278247dc6 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -98,6 +98,11 @@ type RawThreadFeedEntry = export type ThreadFeedEntry = | Extract + | { + readonly type: "working"; + readonly id: string; + readonly createdAt: string; + } | { readonly type: "activity-group"; readonly id: string; @@ -1105,9 +1110,11 @@ export function deriveThreadFeedPresentation( latestTurn: ThreadFeedLatestTurn | null, expandedTurnIds: ReadonlySet, expandedWorkGroupIds: ReadonlySet = new Set(), + activeWorkStartedAt: string | null = null, ): ThreadFeedEntry[] { const sourceFeed = feed.filter( - (entry) => entry.type !== "turn-fold" && entry.type !== "work-toggle", + (entry) => + entry.type !== "turn-fold" && entry.type !== "work-toggle" && entry.type !== "working", ); const foldsByAnchorId = deriveThreadFeedTurnFolds(sourceFeed, latestTurn); const collapsedEntryIds = new Set(); @@ -1136,12 +1143,19 @@ export function deriveThreadFeedPresentation( appendPresentedFeedEntry(result, entry, expandedWorkGroupIds); } } + if (activeWorkStartedAt !== null) { + result.push({ + type: "working", + id: "working-indicator-row", + createdAt: activeWorkStartedAt, + }); + } return result; } function appendPresentedFeedEntry( result: ThreadFeedEntry[], - entry: Exclude, + entry: Exclude, expandedWorkGroupIds: ReadonlySet, ): void { if (entry.type !== "activity-group") { diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts index a9d7317999..926182a3ef 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.test.ts @@ -2464,6 +2464,74 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => { ); }); +it.layer(makeProjectionPipelinePrefixedTestLayer("t3-pending-turn-terminal-test-"))( + "OrchestrationProjectionPipeline pending turn cleanup", + (it) => { + it.effect("clears pending turn starts when startup reaches a terminal session state", () => + Effect.gen(function* () { + const projectionPipeline = yield* OrchestrationProjectionPipeline; + const eventStore = yield* OrchestrationEventStore; + const sql = yield* SqlClient.SqlClient; + + for (const [index, status] of (["error", "interrupted", "stopped"] as const).entries()) { + const threadId = ThreadId.make(`thread-terminal-${status}`); + const requestedAt = `2026-02-26T14:00:0${index}.000Z`; + yield* eventStore.append({ + type: "thread.turn-start-requested", + eventId: EventId.make(`evt-terminal-pending-${status}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: requestedAt, + commandId: CommandId.make(`cmd-terminal-pending-${status}`), + causationEventId: null, + correlationId: CorrelationId.make(`cmd-terminal-pending-${status}`), + metadata: {}, + payload: { + threadId, + messageId: MessageId.make(`message-terminal-${status}`), + runtimeMode: "approval-required", + createdAt: requestedAt, + }, + }); + yield* eventStore.append({ + type: "thread.session-set", + eventId: EventId.make(`evt-terminal-session-${status}`), + aggregateKind: "thread", + aggregateId: threadId, + occurredAt: requestedAt, + commandId: CommandId.make(`cmd-terminal-session-${status}`), + causationEventId: null, + correlationId: CorrelationId.make(`cmd-terminal-session-${status}`), + metadata: {}, + payload: { + threadId, + session: { + threadId, + status, + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: status === "error" ? "startup failed" : null, + updatedAt: requestedAt, + }, + }, + }); + } + + yield* projectionPipeline.bootstrap; + + const pendingRows = yield* sql<{ readonly threadId: string }>` + SELECT thread_id AS "threadId" + FROM projection_turns + WHERE turn_id IS NULL + AND state = 'pending' + `; + assert.deepEqual(pendingRows, []); + }), + ); + }, +); + it.effect("restores pending turn-start metadata across projection pipeline restart", () => Effect.gen(function* () { const { dbPath } = yield* ServerConfig; diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index 3ceae0ea43..cfb88a06cd 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -1059,6 +1059,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.session-set": { const turnId = event.payload.session.activeTurnId; if (turnId === null || event.payload.session.status !== "running") { + if ( + event.payload.session.status === "error" || + event.payload.session.status === "stopped" || + event.payload.session.status === "interrupted" + ) { + yield* projectionTurnRepository.deletePendingTurnStartByThreadId({ + threadId: event.payload.threadId, + }); + } // Leaving the "running" session status is the turn-end signal: // settle still-running turns so their duration reflects the whole // turn rather than the last assistant message. diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index ce464565dc..c49646b7a4 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -22,6 +22,7 @@ import { TurnId, } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; +import * as Deferred from "effect/Deferred"; import * as Exit from "effect/Exit"; import * as Layer from "effect/Layer"; import * as ManagedRuntime from "effect/ManagedRuntime"; @@ -145,6 +146,9 @@ describe("ProviderCommandReactor", () => { readonly threadModelSelection?: ModelSelection; readonly sessionModelSwitch?: "unsupported" | "in-session"; readonly requiresNewThreadForModelChange?: boolean; + readonly startSessionEffect?: ( + session: ProviderSession, + ) => Effect.Effect; }) { const now = "2026-01-01T00:00:00.000Z"; const baseDir = @@ -159,6 +163,7 @@ describe("ProviderCommandReactor", () => { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex", }; + const startSessionEffect = input?.startSessionEffect; const startSession = vi.fn((_: unknown, input: unknown) => { const sessionIndex = nextSessionIndex++; const resumeCursor = @@ -212,8 +217,13 @@ describe("ProviderCommandReactor", () => { createdAt: now, updatedAt: now, }; - runtimeSessions.push(session); - return Effect.succeed(session); + return (startSessionEffect?.(session) ?? Effect.succeed(session)).pipe( + Effect.tap((startedSession) => + Effect.sync(() => { + runtimeSessions.push(startedSession); + }), + ), + ); }); const sendTurn = vi.fn((_: unknown) => Effect.succeed({ @@ -463,9 +473,120 @@ describe("ProviderCommandReactor", () => { const readModel = await harness.readModel(); const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); expect(thread?.session?.threadId).toBe("thread-1"); + expect(thread?.session?.status).toBe("starting"); expect(thread?.session?.runtimeMode).toBe("approval-required"); }); + effectIt.effect("projects starting before a slow provider session finishes", () => + Effect.gen(function* () { + const releaseStart = yield* Deferred.make(); + const harness = yield* Effect.promise(() => + createHarness({ + startSessionEffect: (session) => Deferred.await(releaseStart).pipe(Effect.as(session)), + }), + ); + const now = "2026-01-01T00:00:00.000Z"; + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-slow-provider"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-slow-provider"), + role: "user", + text: "start slowly", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }); + + yield* Effect.promise(() => waitFor(() => harness.startSession.mock.calls.length === 1)); + const duringStartup = yield* Effect.promise(() => harness.readModel()); + expect( + duringStartup.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session + ?.status, + ).toBe("starting"); + expect(harness.sendTurn).not.toHaveBeenCalled(); + + yield* Deferred.succeed(releaseStart, undefined); + yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1)); + }), + ); + + effectIt.effect("settles a failed provider startup and allows a clean retry", () => + Effect.gen(function* () { + let failStartup = true; + const harness = yield* Effect.promise(() => + createHarness({ + startSessionEffect: (session) => + failStartup + ? Effect.fail( + new ProviderAdapterRequestError({ + provider: "codex", + method: "thread.start", + detail: "deterministic startup failure", + }), + ) + : Effect.succeed(session), + }), + ); + const now = "2026-01-01T00:00:00.000Z"; + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-provider-failure"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-provider-failure"), + role: "user", + text: "fail once", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + }); + + yield* Effect.promise(() => + waitFor(async () => { + const readModel = await harness.readModel(); + return ( + readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"))?.session + ?.status === "error" + ); + }), + ); + let readModel = yield* Effect.promise(() => harness.readModel()); + let thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + expect(thread?.session?.lastError).toContain("deterministic startup failure"); + expect(harness.sendTurn).not.toHaveBeenCalled(); + + failStartup = false; + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-provider-retry"), + threadId: ThreadId.make("thread-1"), + message: { + messageId: asMessageId("user-message-provider-retry"), + role: "user", + text: "retry", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }); + + yield* Effect.promise(() => waitFor(() => harness.sendTurn.mock.calls.length === 1)); + readModel = yield* Effect.promise(() => harness.readModel()); + thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1")); + expect(thread?.session?.status).toBe("starting"); + expect(thread?.session?.lastError).toBeNull(); + }), + ); + it("generates a thread title on the first turn", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 9c7a7c94bb..b6bff8c766 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -288,15 +288,20 @@ const make = Effect.gen(function* () { readonly createdAt: string; }) { const thread = yield* resolveThread(input.threadId); - const session = thread?.session; - if (!session) { + if (!thread) { return; } + const session = thread.session; yield* setThreadSession({ threadId: input.threadId, session: { - ...session, - status: session.status === "stopped" ? "stopped" : "ready", + ...(session ?? { + threadId: input.threadId, + providerName: null, + providerInstanceId: thread.modelSelection.instanceId, + runtimeMode: thread.runtimeMode, + }), + status: session?.status === "stopped" ? "stopped" : "error", activeTurnId: null, lastError: input.detail, updatedAt: input.createdAt, @@ -354,6 +359,7 @@ const make = Effect.gen(function* () { createdAt: string, options?: { readonly modelSelection?: ModelSelection; + readonly pendingTurnStart?: boolean; }, ) { const thread = yield* resolveThread(threadId); @@ -428,6 +434,22 @@ const make = Effect.gen(function* () { }); } const preferredProvider: ProviderDriverKind = desiredDriverKind; + if (options?.pendingTurnStart === true && thread.session?.status !== "running") { + yield* setThreadSession({ + threadId, + session: { + threadId, + status: "starting", + providerName: activeSession?.provider ?? preferredProvider, + providerInstanceId: activeSession?.providerInstanceId ?? desiredInstanceId, + runtimeMode: desiredRuntimeMode, + activeTurnId: null, + lastError: null, + updatedAt: createdAt, + }, + createdAt, + }); + } if (thread.session !== null) { yield* rejectStartedThreadModelChangeIfRequired({ threadId, @@ -498,7 +520,10 @@ const make = Effect.gen(function* () { threadId, session: { threadId, - status: mapProviderSessionStatusToOrchestrationStatus(session.status), + status: + options?.pendingTurnStart === true && session.status === "ready" + ? "starting" + : mapProviderSessionStatusToOrchestrationStatus(session.status), providerName: session.provider, providerInstanceId: session.providerInstanceId, runtimeMode: desiredRuntimeMode, @@ -597,11 +622,10 @@ const make = Effect.gen(function* () { new Error(`Thread '${input.threadId}' was not found in read model.`), ); } - yield* ensureSessionForThread( - input.threadId, - input.createdAt, - input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}, - ); + yield* ensureSessionForThread(input.threadId, input.createdAt, { + ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), + pendingTurnStart: true, + }); if (input.modelSelection !== undefined) { threadModelSelections.set(input.threadId, input.modelSelection); } diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts index 20611e1ee7..74ece50cd3 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.test.ts @@ -30,6 +30,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime"; import * as PubSub from "effect/PubSub"; import * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import { it as effectIt } from "@effect/vitest"; import { afterEach, describe, expect, it } from "vite-plus/test"; import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts"; @@ -493,6 +494,185 @@ describe("ProviderRuntimeIngestion", () => { expect(thread.session?.lastError).toBeNull(); }); + effectIt.effect( + "keeps a reconnecting pending turn starting while ready clears stale active state", + () => + Effect.gen(function* () { + const harness = yield* Effect.promise(() => createHarness()); + const threadId = asThreadId("thread-1"); + const staleTurnId = asTurnId("turn-stale-before-reconnect"); + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-pending-reconnect"), + threadId, + message: { + messageId: MessageId.make("message-pending-reconnect"), + role: "user", + text: "resume after reconnect", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }); + yield* harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-starting-pending-reconnect"), + threadId, + session: { + threadId, + status: "starting", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: staleTurnId, + lastError: null, + updatedAt: "2026-01-01T00:00:01.000Z", + }, + createdAt: "2026-01-01T00:00:01.000Z", + }); + + harness.emit({ + type: "session.state.changed", + eventId: asEventId("evt-session-ready-pending-reconnect"), + provider: ProviderDriverKind.make("codex"), + threadId, + createdAt: "2026-01-01T00:00:02.000Z", + payload: { state: "ready" }, + }); + + let thread = yield* Effect.promise(() => + waitForThread( + harness.readModel, + (entry) => entry.session?.status === "starting" && entry.session.activeTurnId === null, + ), + ); + expect(thread.session?.status).toBe("starting"); + expect(thread.session?.activeTurnId).toBeNull(); + + harness.emit({ + type: "session.started", + eventId: asEventId("evt-session-started-pending-reconnect"), + provider: ProviderDriverKind.make("codex"), + threadId, + createdAt: "2026-01-01T00:00:03.000Z", + }); + yield* Effect.promise(() => harness.drain()); + thread = (yield* Effect.promise(() => harness.readModel())).threads.find( + (entry) => entry.id === threadId, + )!; + expect(thread.session?.status).toBe("starting"); + expect(thread.session?.activeTurnId).toBeNull(); + + harness.emit({ + type: "turn.started", + eventId: asEventId("evt-turn-started-pending-reconnect"), + provider: ProviderDriverKind.make("codex"), + threadId, + turnId: asTurnId("turn-after-reconnect"), + createdAt: "2026-01-01T00:00:04.000Z", + }); + thread = yield* Effect.promise(() => + waitForThread( + harness.readModel, + (entry) => + entry.session?.status === "running" && + entry.session.activeTurnId === asTurnId("turn-after-reconnect"), + ), + ); + expect(thread.session?.status).toBe("running"); + + harness.emit({ + type: "session.started", + eventId: asEventId("evt-session-started-duplicate-midturn"), + provider: ProviderDriverKind.make("codex"), + threadId, + createdAt: "2026-01-01T00:00:05.000Z", + }); + yield* Effect.promise(() => harness.drain()); + thread = (yield* Effect.promise(() => harness.readModel())).threads.find( + (entry) => entry.id === threadId, + )!; + expect(thread.session?.status).toBe("running"); + expect(thread.session?.activeTurnId).toBe(asTurnId("turn-after-reconnect")); + }), + ); + + effectIt.effect("keeps an aborted pending start stopped across duplicate exit events", () => + Effect.gen(function* () { + const harness = yield* Effect.promise(() => createHarness()); + const threadId = asThreadId("thread-1"); + const stoppedAt = "2026-01-01T00:00:02.000Z"; + + yield* harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-turn-start-before-stop"), + threadId, + message: { + messageId: MessageId.make("message-before-stop"), + role: "user", + text: "stop this startup", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: "2026-01-01T00:00:01.000Z", + }); + yield* harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-starting-before-stop"), + threadId, + session: { + threadId, + status: "starting", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: "2026-01-01T00:00:01.000Z", + }, + createdAt: "2026-01-01T00:00:01.000Z", + }); + yield* harness.engine.dispatch({ + type: "thread.session.set", + commandId: CommandId.make("cmd-session-stop-pending-start"), + threadId, + session: { + threadId, + status: "stopped", + providerName: "codex", + runtimeMode: "approval-required", + activeTurnId: null, + lastError: null, + updatedAt: stoppedAt, + }, + createdAt: stoppedAt, + }); + + harness.emit({ + type: "session.exited", + eventId: asEventId("evt-session-exited-after-stop"), + provider: ProviderDriverKind.make("codex"), + threadId, + createdAt: "2026-01-01T00:00:03.000Z", + }); + harness.emit({ + type: "session.exited", + eventId: asEventId("evt-duplicate-session-exited-after-stop"), + provider: ProviderDriverKind.make("codex"), + threadId, + createdAt: "2026-01-01T00:00:04.000Z", + }); + + yield* Effect.promise(() => harness.drain()); + const thread = (yield* Effect.promise(() => harness.readModel())).threads.find( + (entry) => entry.id === threadId, + ); + expect(thread?.session?.status).toBe("stopped"); + expect(thread?.session?.activeTurnId).toBeNull(); + }), + ); + it("does not clear active turn when session/thread started arrives mid-turn", async () => { const harness = await createHarness(); const now = "2026-01-01T00:00:00.000Z"; diff --git a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts index 09566feb2b..a8a51b3026 100644 --- a/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts +++ b/apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts @@ -1308,6 +1308,11 @@ const make = Effect.gen(function* () { const now = event.createdAt; const eventTurnId = toTurnId(event.turnId); const activeTurnId = thread.session?.activeTurnId ?? null; + const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({ + threadId: thread.id, + }); + const hasPendingTurnStart = + Option.isSome(pendingTurnStart) && thread.session?.status === "starting"; const conflictsWithActiveTurn = activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId); @@ -1322,11 +1327,7 @@ const make = Effect.gen(function* () { const conflictingTurnStartIsPendingTurnStart = event.type === "turn.started" && conflictsWithActiveTurn ? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) && - Option.isSome( - yield* projectionTurnRepository.getPendingTurnStartByThreadId({ - threadId: thread.id, - }), - ) + Option.isSome(pendingTurnStart) : false; const shouldApplyThreadLifecycle = (() => { @@ -1370,8 +1371,10 @@ const make = Effect.gen(function* () { ) { const status = (() => { switch (event.type) { - case "session.state.changed": - return orchestrationSessionStatusFromRuntimeState(event.payload.state); + case "session.state.changed": { + const runtimeStatus = orchestrationSessionStatusFromRuntimeState(event.payload.state); + return hasPendingTurnStart && runtimeStatus === "ready" ? "starting" : runtimeStatus; + } case "turn.started": return "running"; case "session.exited": @@ -1383,8 +1386,8 @@ const make = Effect.gen(function* () { 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"; + // active or pending turn; preserve that lifecycle state. + return activeTurnId !== null ? "running" : hasPendingTurnStart ? "starting" : "ready"; } })(); const nextActiveTurnId = @@ -1392,7 +1395,10 @@ const make = Effect.gen(function* () { ? (eventTurnId ?? null) : event.type === "turn.completed" || event.type === "session.exited" ? null - : event.type === "session.state.changed" && !sessionStatusAllowsActiveTurn(status) + : event.type === "session.state.changed" && + !sessionStatusAllowsActiveTurn( + orchestrationSessionStatusFromRuntimeState(event.payload.state), + ) ? null : activeTurnId; const lastError = diff --git a/apps/server/src/provider/Layers/ClaudeCapabilitiesProbe.test.ts b/apps/server/src/provider/Layers/ClaudeCapabilitiesProbe.test.ts new file mode 100644 index 0000000000..ab6e599299 --- /dev/null +++ b/apps/server/src/provider/Layers/ClaudeCapabilitiesProbe.test.ts @@ -0,0 +1,138 @@ +import { ClaudeSettings } from "@t3tools/contracts"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import * as Schema from "effect/Schema"; + +import { + buildClaudeCapabilitiesProbeQueryOptions, + CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES, + probeClaudeCapabilities, +} from "./ClaudeProvider.ts"; + +const decodeClaudeSettings = Schema.decodeSync(ClaudeSettings); + +it("isolates Claude capability probes without dropping workspace setting sources", () => { + const abortController = new AbortController(); + const options = buildClaudeCapabilitiesProbeQueryOptions({ + executablePath: "/usr/bin/claude", + abortController, + environment: { + HOME: "/home/user", + ENABLE_CLAUDEAI_MCP_SERVERS: "true", + }, + cwd: "/workspace/project", + }); + + assert.deepEqual(options.mcpServers, {}); + assert.equal(options.strictMcpConfig, true); + assert.equal(options.cwd, "/workspace/project"); + assert.deepEqual(options.settingSources, [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES]); + assert.deepEqual(options.allowedTools, []); + assert.equal(options.persistSession, false); + assert.equal(options.pathToClaudeCodeExecutable, "/usr/bin/claude"); + assert.equal(options.abortController, abortController); + assert.equal(options.env?.HOME, "/home/user"); + assert.equal(options.env?.ENABLE_CLAUDEAI_MCP_SERVERS, "false"); +}); + +it.layer(NodeServices.layer)("Claude capability probe SDK boundary", (it) => { + it.effect("serializes strict no-MCP options and still resolves account capabilities", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-probe-sdk-" }); + const executablePath = path.join(tempDir, "fake-claude.mjs"); + const invocationPath = path.join(tempDir, "invocation.json"); + const workspaceCwd = path.join(tempDir, "workspace"); + yield* fs.makeDirectory(workspaceCwd, { recursive: true }); + + yield* fs.writeFileString( + executablePath, + [ + "#!/usr/bin/env node", + 'import { existsSync, readFileSync, writeFileSync } from "node:fs";', + 'import { createInterface } from "node:readline";', + "const args = process.argv.slice(2);", + 'const mcpConfigIndex = args.indexOf("--mcp-config");', + "const rawMcpConfig = mcpConfigIndex >= 0 ? args[mcpConfigIndex + 1] : undefined;", + "let mcpConfig;", + "if (rawMcpConfig) {", + ' const contents = existsSync(rawMcpConfig) ? readFileSync(rawMcpConfig, "utf8") : rawMcpConfig;', + " try { mcpConfig = JSON.parse(contents); } catch { mcpConfig = contents; }", + "}", + "writeFileSync(process.env.T3_PROBE_INVOCATION_PATH, JSON.stringify({", + " args,", + " cwd: process.cwd(),", + " connectorEnv: process.env.ENABLE_CLAUDEAI_MCP_SERVERS,", + " mcpConfig,", + "}));", + "const lines = createInterface({ input: process.stdin });", + 'lines.on("line", (line) => {', + " const message = JSON.parse(line);", + ' if (message.type !== "control_request" || message.request?.subtype !== "initialize") return;', + " process.stdout.write(JSON.stringify({", + ' type: "control_response",', + " response: {", + ' subtype: "success",', + " request_id: message.request_id,", + " response: {", + ' commands: [{ name: "review", description: "Review changes", argumentHint: "[path]" }],', + " agents: [],", + ' output_style: "default",', + ' available_output_styles: ["default"],', + " models: [],", + ' account: { email: "dev@example.com", subscriptionType: "pro", tokenSource: "oauth" },', + " },", + " },", + ' }) + "\\n");', + "});", + "setInterval(() => {}, 1_000);", + "", + ].join("\n"), + ); + yield* fs.chmod(executablePath, 0o755); + + const capabilities = yield* probeClaudeCapabilities( + decodeClaudeSettings({ binaryPath: executablePath }), + { + ...process.env, + T3_PROBE_INVOCATION_PATH: invocationPath, + ENABLE_CLAUDEAI_MCP_SERVERS: "true", + }, + workspaceCwd, + ); + + assert.deepEqual(capabilities, { + email: "dev@example.com", + subscriptionType: "pro", + tokenSource: "oauth", + apiProvider: undefined, + slashCommands: [ + { + name: "review", + description: "Review changes", + input: { hint: "[path]" }, + }, + ], + }); + + // @effect-diagnostics-next-line preferSchemaOverJson:off + const invocation = JSON.parse(yield* fs.readFileString(invocationPath)) as { + readonly args: ReadonlyArray; + readonly cwd: string; + readonly connectorEnv: string; + readonly mcpConfig: unknown; + }; + assert.equal(invocation.cwd, yield* fs.realPath(workspaceCwd)); + assert.equal(invocation.connectorEnv, "false"); + assert.equal(invocation.args.includes("--strict-mcp-config"), true); + assert.equal(invocation.args.includes("--mcp-config"), false); + assert.equal(invocation.mcpConfig, undefined); + + assert.equal(invocation.args.includes("--setting-sources=user,project,local"), true); + }).pipe(Effect.scoped), + ); +}); diff --git a/apps/server/src/provider/Layers/ClaudeProvider.ts b/apps/server/src/provider/Layers/ClaudeProvider.ts index 9df672f54b..4920f96465 100644 --- a/apps/server/src/provider/Layers/ClaudeProvider.ts +++ b/apps/server/src/provider/Layers/ClaudeProvider.ts @@ -21,8 +21,10 @@ import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { compareSemverVersions } from "@t3tools/shared/semver"; import { query as claudeQuery, + type Options as ClaudeQueryOptions, type SlashCommand as ClaudeSlashCommand, type SDKUserMessage, + type SettingSource, } from "@anthropic-ai/claude-agent-sdk"; import { @@ -508,6 +510,44 @@ function apiProviderAuthMetadata( // `undefined` and left the provider unverified and unselectable in the picker. const CAPABILITIES_PROBE_TIMEOUT_MS = 25_000; +/** + * Keep workspace-scoped command discovery intact while isolating the periodic + * health check from configured MCP servers. + */ +export const CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES = [ + "user", + "project", + "local", +] as const satisfies ReadonlyArray; + +/** Build the exact SDK options used by the periodic Claude capability probe. */ +export function buildClaudeCapabilitiesProbeQueryOptions(input: { + readonly executablePath: string; + readonly abortController: AbortController; + readonly environment: NodeJS.ProcessEnv; + readonly cwd: string | undefined; +}): ClaudeQueryOptions { + return { + persistSession: false, + pathToClaudeCodeExecutable: input.executablePath, + abortController: input.abortController, + settingSources: [...CLAUDE_CAPABILITIES_PROBE_SETTING_SOURCES], + allowedTools: [], + // Ignore MCP definitions from every filesystem setting source above. The + // SDK combines this empty explicit map with --strict-mcp-config. + mcpServers: {}, + strictMcpConfig: true, + env: { + ...input.environment, + // Connected claude.ai MCP servers are discovered outside filesystem + // config; disable them independently for this health check. + ENABLE_CLAUDEAI_MCP_SERVERS: "false", + }, + ...(input.cwd ? { cwd: input.cwd } : {}), + stderr: () => {}, + }; +} + function nonEmptyProbeString(value: string): string | undefined { const candidate = value.trim(); return candidate ? candidate : undefined; @@ -631,16 +671,12 @@ const probeClaudeCapabilities = ( prompt: (async function* (): AsyncGenerator { await waitForAbortSignal(abort.signal); })(), - options: { - persistSession: false, - pathToClaudeCodeExecutable: executablePath, + options: buildClaudeCapabilitiesProbeQueryOptions({ + executablePath, abortController: abort, - settingSources: ["user", "project", "local"], - allowedTools: [], - env: claudeEnvironment, - ...(cwd ? { cwd } : {}), - stderr: () => {}, - }, + environment: claudeEnvironment, + cwd, + }), }); const init = await q.initializationResult(); const account = init.account as diff --git a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts index 05160517bf..41454b48b3 100644 --- a/apps/server/src/provider/Layers/OpenCodeProvider.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeProvider.test.ts @@ -97,10 +97,13 @@ const OpenCodeRuntimeTestDouble: OpenCodeRuntimeShape = { : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory), loadInventoryFromCli: () => runtimeMock.state.inventoryError - ? Effect.succeed({ - providerList: { all: [], default: {}, connected: [] as string[] }, - agents: [], - } as OpenCodeInventory) + ? Effect.fail( + new OpenCodeRuntimeError({ + operation: "loadInventoryFromCli", + detail: runtimeMock.state.inventoryError.message, + cause: runtimeMock.state.inventoryError, + }), + ) : Effect.succeed(runtimeMock.state.inventory as OpenCodeInventory), }; @@ -212,14 +215,18 @@ it.layer(testLayer)("checkOpenCodeProviderStatus", (it) => { }), ); - it.effect("degrades gracefully on CLI failure for local installs", () => + it.effect("reports local model inventory failures without treating them as empty", () => Effect.gen(function* () { runtimeMock.state.inventoryError = new Error("opencode models failed"); const snapshot = yield* checkOpenCodeProviderStatus(makeOpenCodeSettings(), process.cwd()); - NodeAssert.equal(snapshot.status, "warning"); + NodeAssert.equal(snapshot.status, "error"); NodeAssert.equal(snapshot.installed, true); NodeAssert.equal(snapshot.models.length, 0); + NodeAssert.equal( + snapshot.message, + "Failed to execute OpenCode CLI health check: opencode models failed", + ); }), ); }); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.test.ts b/apps/server/src/provider/Layers/ProviderRegistry.test.ts index 159d853121..5efbb6f1c1 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.test.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.test.ts @@ -563,6 +563,176 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te ]); }); + it("drops stale OpenCode models missing from a successful refresh", () => { + const previousProvider = { + instanceId: ProviderInstanceId.make("opencode"), + driver: ProviderDriverKind.make("opencode"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-07-17T00:00:00.000Z", + version: "1.0.0", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + { + slug: "removed-plugin/model", + name: "Removed Plugin Model", + subProvider: "Removed Plugin", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshedProvider = { + ...previousProvider, + checkedAt: "2026-07-17T00:01:00.000Z", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + ], + } satisfies ServerProvider; + + assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [ + ...refreshedProvider.models, + ]); + }); + + it("retains stale OpenCode models when a refresh fails", () => { + const previousProvider = { + instanceId: ProviderInstanceId.make("opencode"), + driver: ProviderDriverKind.make("opencode"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-07-17T00:00:00.000Z", + version: "1.0.0", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const refreshedProvider = { + ...previousProvider, + status: "error", + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:01:00.000Z", + models: [], + message: "Failed to refresh OpenCode models.", + } satisfies ServerProvider; + + assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, refreshedProvider).models, [ + ...previousProvider.models, + ]); + }); + + it("classifies pending, logout, uninstall, and reconnect OpenCode inventories", () => { + const previousProvider = { + instanceId: ProviderInstanceId.make("opencode"), + driver: ProviderDriverKind.make("opencode"), + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-07-17T00:00:00.000Z", + version: "1.0.0", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + { + slug: "removed-plugin/model", + name: "Removed Plugin Model", + subProvider: "Removed Plugin", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const pendingProvider = { + ...previousProvider, + status: "warning", + installed: false, + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:01:00.000Z", + version: null, + models: [], + message: "OpenCode provider status has not been checked in this session yet.", + } satisfies ServerProvider; + const loggedOutProvider = { + ...previousProvider, + status: "warning", + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:02:00.000Z", + models: [], + message: "OpenCode is available, but it did not report any connected upstream providers.", + } satisfies ServerProvider; + const missingProvider = { + ...previousProvider, + status: "error", + installed: false, + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:03:00.000Z", + version: null, + models: [], + message: "OpenCode CLI (`opencode`) is not installed or not on PATH.", + } satisfies ServerProvider; + const authoritativeProvider = { + ...previousProvider, + checkedAt: "2026-07-17T00:04:00.000Z", + models: [previousProvider.models[0]!], + } satisfies ServerProvider; + const failedProvider = { + ...authoritativeProvider, + status: "error", + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:05:00.000Z", + models: [], + message: "Failed to refresh OpenCode models.", + } satisfies ServerProvider; + + assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, pendingProvider).models, [ + ...previousProvider.models, + ]); + assert.deepStrictEqual( + mergeProviderSnapshot(previousProvider, loggedOutProvider).models, + [], + ); + assert.deepStrictEqual(mergeProviderSnapshot(previousProvider, missingProvider).models, []); + + const afterRemoval = mergeProviderSnapshot(previousProvider, authoritativeProvider); + const afterFailure = mergeProviderSnapshot(afterRemoval, failedProvider); + + assert.deepStrictEqual(afterFailure.models, [authoritativeProvider.models[0]!]); + }); + it("fills missing capabilities from the previous provider snapshot", () => { const previousProvider = { instanceId: ProviderInstanceId.make("cursor"), @@ -866,6 +1036,144 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsModule.layerTest(), Te }), ); + it.effect( + "persists authoritative OpenCode removals without resurrecting them on a failed live refresh", + () => + Effect.gen(function* () { + const openCodeDriver = ProviderDriverKind.make("opencode"); + const openCodeInstanceId = ProviderInstanceId.make("opencode"); + const initialProvider = { + instanceId: openCodeInstanceId, + driver: openCodeDriver, + status: "ready", + enabled: true, + installed: true, + auth: { status: "authenticated" }, + checkedAt: "2026-07-17T00:00:00.000Z", + version: "1.0.0", + models: [ + { + slug: "github/gpt-5", + name: "GPT-5", + subProvider: "GitHub", + isCustom: false, + capabilities: null, + }, + { + slug: "removed-plugin/model", + name: "Removed Plugin Model", + subProvider: "Removed Plugin", + isCustom: false, + capabilities: null, + }, + ], + slashCommands: [], + skills: [], + } as const satisfies ServerProvider; + const authoritativeProvider = { + ...initialProvider, + checkedAt: "2026-07-17T00:01:00.000Z", + models: [initialProvider.models[0]!], + } satisfies ServerProvider; + const failedProvider = { + ...authoritativeProvider, + status: "error", + auth: { status: "unknown" }, + checkedAt: "2026-07-17T00:02:00.000Z", + models: [], + message: "Failed to refresh OpenCode models.", + } satisfies ServerProvider; + const changes = yield* PubSub.unbounded(); + const instance = { + instanceId: openCodeInstanceId, + driverKind: openCodeDriver, + continuationIdentity: { + driverKind: openCodeDriver, + continuationKey: "opencode:instance:opencode", + }, + displayName: undefined, + enabled: true, + snapshot: { + maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({ + provider: openCodeDriver, + packageName: null, + }), + getSnapshot: Effect.succeed(initialProvider), + refresh: Effect.succeed(authoritativeProvider), + streamChanges: Stream.fromPubSub(changes), + }, + adapter: {} as ProviderInstance["adapter"], + textGeneration: {} as ProviderInstance["textGeneration"], + } satisfies ProviderInstance; + const instanceRegistryLayer = Layer.succeed( + ProviderInstanceRegistry.ProviderInstanceRegistry, + { + getInstance: (instanceId) => + Effect.succeed(instanceId === openCodeInstanceId ? instance : undefined), + listInstances: Effect.succeed([instance]), + listUnavailable: Effect.succeed([]), + streamChanges: Stream.empty, + subscribeChanges: Effect.flatMap(PubSub.unbounded(), (pubsub) => + PubSub.subscribe(pubsub), + ), + }, + ); + const scope = yield* Scope.make(); + yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void)); + const runtimeServices = yield* Layer.build( + ProviderRegistryLive.pipe( + Layer.provideMerge(instanceRegistryLayer), + Layer.provideMerge( + ServerConfig.layerTest(process.cwd(), { + prefix: "t3-provider-registry-opencode-authoritative-persist-", + }), + ), + Layer.provideMerge(NodeServices.layer), + ), + ).pipe(Scope.provide(scope)); + + yield* Effect.gen(function* () { + const registry = yield* ProviderRegistry.ProviderRegistry; + const config = yield* ServerConfig.ServerConfig; + const filePath = yield* resolveProviderStatusCachePath({ + cacheDir: config.providerStatusCacheDir, + instanceId: openCodeInstanceId, + }); + + yield* PubSub.publish(changes, authoritativeProvider); + + let cachedProvider = yield* readProviderStatusCache(filePath); + for ( + let attempt = 0; + attempt < 50 && cachedProvider?.checkedAt !== authoritativeProvider.checkedAt; + attempt += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + cachedProvider = yield* readProviderStatusCache(filePath); + } + + assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); + + yield* PubSub.publish(changes, failedProvider); + for ( + let attempt = 0; + attempt < 50 && cachedProvider?.checkedAt !== failedProvider.checkedAt; + attempt += 1 + ) { + yield* TestClock.adjust("10 millis"); + yield* Effect.yieldNow; + cachedProvider = yield* readProviderStatusCache(filePath); + } + + assert.deepStrictEqual(cachedProvider?.models, [authoritativeProvider.models[0]!]); + assert.deepStrictEqual((yield* registry.getProviders)[0]?.models, [ + authoritativeProvider.models[0]!, + ]); + }).pipe(Effect.provide(runtimeServices)); + }), + ); + it.effect("returns the cached provider list when a manual refresh fails", () => Effect.gen(function* () { const codexDriver = ProviderDriverKind.make("codex"); diff --git a/apps/server/src/provider/Layers/ProviderRegistry.ts b/apps/server/src/provider/Layers/ProviderRegistry.ts index 2df63e5383..760c8e1c59 100644 --- a/apps/server/src/provider/Layers/ProviderRegistry.ts +++ b/apps/server/src/provider/Layers/ProviderRegistry.ts @@ -78,11 +78,31 @@ const makeManualProviderMaintenanceCapabilities = (provider: ProviderDriverKind) const hasModelCapabilities = (model: ServerProvider["models"][number]): boolean => (model.capabilities?.optionDescriptors?.length ?? 0) > 0; +const shouldRetainMissingProviderModels = (provider: ServerProvider): boolean => { + if (provider.driver !== ProviderDriverKind.make("opencode")) { + return true; + } + + // OpenCode's initial snapshot is deliberately non-authoritative while its + // first probe is still running. A probe error from an installed CLI/server + // is likewise partial: it could not establish the current inventory. + // Conversely, disabled and missing-CLI snapshots are authoritative removals, + // as are successful ready/warning inventories (including an empty one after + // logout or plugin removal). + const isPendingInitialProbe = + provider.enabled && !provider.installed && provider.status === "warning"; + const didInstalledProviderProbeFail = provider.installed && provider.status === "error"; + return isPendingInitialProbe || didInstalledProviderProbeFail; +}; + const mergeProviderModels = ( + provider: ServerProvider, previousModels: ReadonlyArray, nextModels: ReadonlyArray, ): ReadonlyArray => { - if (nextModels.length === 0 && previousModels.length > 0) { + const shouldRetainMissingModels = shouldRetainMissingProviderModels(provider); + + if (shouldRetainMissingModels && nextModels.length === 0 && previousModels.length > 0) { return previousModels; } @@ -98,7 +118,9 @@ const mergeProviderModels = ( }; }); const nextSlugs = new Set(nextModels.map((model) => model.slug)); - return [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))]; + return shouldRetainMissingModels + ? [...mergedModels, ...previousModels.filter((model) => !nextSlugs.has(model.slug))] + : mergedModels; }; export const mergeProviderSnapshot = ( @@ -109,7 +131,7 @@ export const mergeProviderSnapshot = ( ? nextProvider : { ...nextProvider, - models: mergeProviderModels(previousProvider.models, nextProvider.models), + models: mergeProviderModels(nextProvider, previousProvider.models, nextProvider.models), }; export const mergeProviderSnapshots = ( diff --git a/apps/server/src/provider/opencodeRuntime.ts b/apps/server/src/provider/opencodeRuntime.ts index b853662b03..63fcea22d1 100644 --- a/apps/server/src/provider/opencodeRuntime.ts +++ b/apps/server/src/provider/opencodeRuntime.ts @@ -690,22 +690,36 @@ const makeOpenCodeRuntime = Effect.gen(function* () { agentsResult = a2; } - // Degrade gracefully on failure — return empty inventory (warning status, not error) - let connected: string[] = []; - let allProviders: ProviderListResponse["all"] = []; - if (modelsResult._tag === "Success" && modelsResult.value.code === 0) { - const parsed = parseModelsCliOutput(modelsResult.value.stdout); - connected = [...parsed.connected]; - allProviders = [...parsed.providers.values()].map((p) => ({ - id: p.id, - name: p.name, + if (modelsResult._tag === "Failure") { + const cause = Cause.squash(modelsResult.cause); + return yield* ensureRuntimeError( + "loadInventoryFromCli", + `Failed to load OpenCode models: ${openCodeRuntimeErrorDetail(cause)}`, + cause, + ); + } + if (modelsResult.value.code !== 0) { + return yield* new OpenCodeRuntimeError({ + operation: "loadInventoryFromCli", + detail: `OpenCode models command exited with code ${modelsResult.value.code}.`, + }); + } + + const parsed = parseModelsCliOutput(modelsResult.value.stdout); + const connected = [...parsed.connected]; + const allProviders: ProviderListResponse["all"] = [...parsed.providers.values()].map( + (provider) => ({ + id: provider.id, + name: provider.name, source: "config" as const, env: [], options: {}, - models: p.models, - })); - } + models: provider.models, + }), + ); + // Agent metadata enriches model capabilities but is not required for an + // authoritative model inventory, so it may still degrade to an empty list. let agents: ReadonlyArray = []; if (agentsResult._tag === "Success" && agentsResult.value.code === 0) { agents = parseAgentListCliOutput(agentsResult.value.stdout); diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsx index c85340c715..fac3bf7d24 100644 --- a/apps/web/src/components/ChatMarkdown.tsx +++ b/apps/web/src/components/ChatMarkdown.tsx @@ -42,6 +42,10 @@ import remarkGfm from "remark-gfm"; import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText"; import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip"; import { PierreEntryIcon } from "./chat/PierreEntryIcon"; +import { + resolveExternalWebLinkHost, + showExternalLinkContextMenu, +} from "./chat/externalLinkContextMenu"; import { hasSpecificPierreIconForFileName, syntheticFileNameForLanguageId } from "../pierre-icons"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { Button } from "./ui/button"; @@ -76,6 +80,7 @@ import { usePreparedConnection } from "../state/session"; import { previewEnvironment } from "../state/preview"; import { useAtomCommand } from "../state/use-atom-command"; import { useAtomQueryRunner } from "../state/use-atom-query-runner"; +import { writeTextToClipboard } from "../hooks/useCopyToClipboard"; import { isPreviewSupportedInRuntime } from "../previewStateStore"; import { isBrowserPreviewFile, @@ -831,17 +836,6 @@ const MARKDOWN_LINK_FAVICON_CLASS_NAME = "block size-full shrink-0 select-none"; /** Hosts whose favicon request already failed this session — skip straight to the globe. */ const failedFaviconHosts = new Set(); -function resolveExternalLinkHost(href: string | undefined): string | null { - if (!href) return null; - try { - const url = new URL(href); - if (url.protocol !== "http:" && url.protocol !== "https:") return null; - return url.hostname || null; - } catch { - return null; - } -} - const MarkdownLinkFavicon = memo(function MarkdownLinkFavicon({ host }: { host: string }) { const [failedHost, setFailedHost] = useState(null); return ( @@ -1393,7 +1387,7 @@ function ChatMarkdown({ const normalizedHref = href ? normalizeMarkdownLinkHrefKey(href) : ""; const fileLinkMeta = normalizedHref ? markdownFileLinkMetaByHref.get(normalizedHref) : null; if (!fileLinkMeta) { - const faviconHost = resolveExternalLinkHost(href); + const faviconHost = resolveExternalWebLinkHost(href); const isSameDocumentLink = href?.startsWith("#") ?? false; const onClick = props.onClick; const canOpenInPreview = Boolean(threadRef) && isPreviewSupportedInRuntime(); @@ -1410,37 +1404,30 @@ function ChatMarkdown({ } }} onContextMenu={(event) => { - if (!canOpenInPreview || !href) return; + if (!canOpenInPreview || !href || !faviconHost) return; event.preventDefault(); event.stopPropagation(); const api = readLocalApi(); if (!api) return; - void (async () => { - let operation = "show-link-context-menu"; - try { - const clicked = await api.contextMenu.show( - [ - { id: "open-in-browser", label: "Open in integrated browser" }, - { id: "open-external", label: "Open in system browser" }, - ] as const, - { x: event.clientX, y: event.clientY }, - ); - if (clicked === "open-in-browser") { - operation = "open-link-in-preview"; - const result = await openExternalLinkInPreview(href); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { - reportMarkdownActionFailure({ operation, target: href }, result.cause); - } - return; + void showExternalLinkContextMenu({ + href, + position: { x: event.clientX, y: event.clientY }, + showContextMenu: (items, position) => api.contextMenu.show(items, position), + openInPreview: async (target) => { + const result = await openExternalLinkInPreview(target); + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + reportMarkdownActionFailure( + { operation: "open-link-in-preview", target }, + result.cause, + ); } - if (clicked === "open-external") { - operation = "open-link-external"; - await api.shell.openExternal(href); - } - } catch (cause) { + }, + openExternal: (target) => api.shell.openExternal(target), + copyLink: (target) => writeTextToClipboard(target, "link"), + reportFailure: (operation, cause) => { reportMarkdownActionFailure({ operation, target: href }, cause); - } - })(); + }, + }); }} > {faviconHost ? ( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 1b8447c1fd..722ffbfaf6 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -152,6 +152,7 @@ import { } from "~/projectScripts"; import { newDraftId, newMessageId, newThreadId } from "~/lib/utils"; import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels"; +import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances"; import { useEnvironmentSettings } from "../hooks/useSettings"; import { resolveAppModelSelectionForInstance } from "../modelSelection"; import { getTerminalFocusOwner } from "../lib/terminalFocus"; @@ -1361,10 +1362,7 @@ function ChatViewContent(props: ChatViewProps) { ? buildLocalDraftThread( threadId, draftThread, - fallbackDraftProject?.defaultModelSelection ?? { - instanceId: ProviderInstanceId.make("codex"), - model: DEFAULT_MODEL, - }, + fallbackDraftProject?.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION, ) : undefined, [draftThread, fallbackDraftProject?.defaultModelSelection, threadId], @@ -1856,7 +1854,7 @@ function ChatViewContent(props: ChatViewProps) { const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS; const unlockedSelectedProvider = resolveSelectableProvider( providerStatuses, - selectedProviderByThreadId ?? threadProvider ?? ProviderDriverKind.make("codex"), + selectedProviderByThreadId ?? threadProvider, ); const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; const phase = derivePhase(activeThread?.session ?? null); @@ -4038,7 +4036,7 @@ function ChatViewContent(props: ChatViewProps) { return; } const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx) return; + if (!sendCtx?.providerAvailable) return; const { images: composerImages, terminalContexts: composerTerminalContexts, @@ -4614,7 +4612,7 @@ function ChatViewContent(props: ChatViewProps) { } const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx) { + if (!sendCtx?.providerAvailable) { return; } const { @@ -4773,7 +4771,7 @@ function ChatViewContent(props: ChatViewProps) { } const sendCtx = composerRef.current?.getSendContext(); - if (!sendCtx) { + if (!sendCtx?.providerAvailable) { return; } const { diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 8dccf98445..9d824e0f72 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -7,12 +7,10 @@ import { squashAtomCommandFailure, } from "@t3tools/client-runtime/state/runtime"; import { - DEFAULT_MODEL, type DesktopWslState, type EnvironmentId, type FilesystemBrowseResult, type ProjectId, - ProviderInstanceId, type SourceControlDiscoveryResult, type SourceControlProviderKind, type SourceControlRepositoryInfo, @@ -111,7 +109,8 @@ import { CommandPaletteResults } from "./CommandPaletteResults"; import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons"; import { ProjectFavicon } from "./ProjectFavicon"; import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators"; -import { primaryServerKeybindingsAtom } from "../state/server"; +import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server"; +import { resolveDefaultProviderModelSelection } from "../providerInstances"; import { resolveShortcutCommand } from "../keybindings"; import { Command, @@ -476,6 +475,7 @@ function OpenCommandPaletteDialog(props: { const projects = useProjects(); const threads = useThreadShells(); const keybindings = useAtomValue(primaryServerKeybindingsAtom); + const providers = useAtomValue(primaryServerProvidersAtom); const [viewStack, setViewStack] = useState([]); const currentView = viewStack.at(-1) ?? null; const [browseGeneration, setBrowseGeneration] = useState(0); @@ -1149,6 +1149,10 @@ function OpenCommandPaletteDialog(props: { } const projectId = newProjectId(); + const targetEnvironmentProviders = + environments.find((environment) => environment.environmentId === input.environmentId) + ?.serverConfig?.providers ?? + (input.environmentId === primaryEnvironmentId ? providers : []); const createResult = await createProject({ environmentId: input.environmentId, input: { @@ -1156,10 +1160,10 @@ function OpenCommandPaletteDialog(props: { title: inferProjectTitleFromPath(cwd), workspaceRoot: cwd, createWorkspaceRootIfMissing: true, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: DEFAULT_MODEL, - }, + defaultModelSelection: resolveDefaultProviderModelSelection( + targetEnvironmentProviders, + null, + ), }, }); if (createResult._tag === "Failure") { @@ -1195,8 +1199,11 @@ function OpenCommandPaletteDialog(props: { [ handleNewThread, createProject, + environments, navigate, + primaryEnvironmentId, projects, + providers, setOpen, clientSettings.sidebarThreadSortOrder, threads, diff --git a/apps/web/src/components/ComposerPromptEditor.test.ts b/apps/web/src/components/ComposerPromptEditor.test.ts index 45a2db4731..0aab8fb0c2 100644 --- a/apps/web/src/components/ComposerPromptEditor.test.ts +++ b/apps/web/src/components/ComposerPromptEditor.test.ts @@ -70,4 +70,83 @@ describe("registerComposerInlineTokenPaste", () => { " ", ); }); + + it.each([ + "yarn expo install @expo/ui", + "npm install @jane/foo.js", + "import '@scope/pkg/sub/path'", + ])("leaves scoped package command %s to the plain-text paste fallback", (command) => { + vi.stubGlobal("ClipboardEvent", TestClipboardEvent); + const editor = createEditor(); + const plainTextFallback = vi.fn((event: ClipboardEvent) => { + const selection = $getSelection(); + if (!$isRangeSelection(selection)) return false; + selection.insertText(event.clipboardData?.getData("text/plain") ?? ""); + return true; + }); + + editor.update( + () => { + const paragraph = $createParagraphNode(); + $getRoot().append(paragraph); + paragraph.selectEnd(); + }, + { discrete: true }, + ); + registerComposerInlineTokenPaste(editor, { + createMentionNode: (path) => $createTextNode(``), + getExpandedAbsoluteOffsetForPoint: () => 0, + }); + editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR); + + const event = new TestClipboardEvent(command); + let handled = false; + editor.update( + () => { + handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent); + }, + { discrete: true }, + ); + + expect(handled).toBe(true); + expect(plainTextFallback).toHaveBeenCalledOnce(); + expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(command); + }); + + it("pastes a canonical scoped folder link as a mention", () => { + vi.stubGlobal("ClipboardEvent", TestClipboardEvent); + const editor = createEditor(); + const mention = "[sub](@scope/pkg/sub)"; + const plainTextFallback = vi.fn(() => true); + + editor.update( + () => { + const paragraph = $createParagraphNode(); + $getRoot().append(paragraph); + paragraph.selectEnd(); + }, + { discrete: true }, + ); + registerComposerInlineTokenPaste(editor, { + createMentionNode: (path) => $createTextNode(``), + getExpandedAbsoluteOffsetForPoint: () => 0, + }); + editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR); + + const event = new TestClipboardEvent(mention); + let handled = false; + editor.update( + () => { + handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent); + }, + { discrete: true }, + ); + + expect(handled).toBe(true); + expect(plainTextFallback).not.toHaveBeenCalled(); + expect(event.defaultPrevented).toBe(true); + expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe( + " ", + ); + }); }); diff --git a/apps/web/src/components/ProjectFavicon.tsx b/apps/web/src/components/ProjectFavicon.tsx index f7603a36e9..bc3e8ee832 100644 --- a/apps/web/src/components/ProjectFavicon.tsx +++ b/apps/web/src/components/ProjectFavicon.tsx @@ -1,6 +1,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { isProjectFaviconFallbackUrl } from "@t3tools/shared/projectFavicon"; import { FolderIcon } from "lucide-react"; +import type { ComponentType } from "react"; import { useState } from "react"; import { useAssetUrl } from "../assets/assetUrls"; @@ -10,29 +11,46 @@ export function ProjectFavicon(input: { environmentId: EnvironmentId; cwd: string; className?: string | undefined; + fallbackIcon?: ComponentType<{ className?: string }>; }) { const src = useAssetUrl(input.environmentId, { _tag: "project-favicon", cwd: input.cwd, }); + const FallbackIcon = input.fallbackIcon ?? FolderIcon; if (!src || isProjectFaviconFallbackUrl(src)) { - return ; + return ; } - return ; + return ( + + ); } -function ProjectFaviconFallback({ className }: { readonly className?: string | undefined }) { - return ; +function ProjectFaviconFallback({ + className, + icon: Icon, +}: { + readonly className?: string | undefined; + readonly icon: ComponentType<{ className?: string }>; +}) { + return ; } function ProjectFaviconImage({ src, className, + fallbackIcon: FallbackIcon, }: { readonly src: string; readonly className?: string | undefined; + readonly fallbackIcon: ComponentType<{ className?: string }>; }) { const [status, setStatus] = useState<"loading" | "loaded" | "error">(() => loadedProjectFaviconSrcs.has(src) ? "loaded" : "loading", @@ -40,7 +58,9 @@ function ProjectFaviconImage({ return ( <> - {status !== "loaded" ? : null} + {status !== "loaded" ? ( + + ) : null} resolveThreadRouteRef(params), + select: (params) => resolveThreadRouteTarget(params), }); + const routeDraftThread = useComposerDraftStore((store) => + routeTarget?.kind === "draft" ? store.getDraftSession(routeTarget.draftId) : null, + ); + const routeThreadRef = useMemo( + () => resolveActiveThreadRouteRef(routeTarget, routeDraftThread), + [routeDraftThread, routeTarget], + ); const routeThreadKey = routeThreadRef ? scopedThreadKey(routeThreadRef) : null; const routeTerminalOpen = useTerminalUiStateStore((state) => routeThreadRef diff --git a/apps/web/src/components/SidebarV2.tsx b/apps/web/src/components/SidebarV2.tsx index 760d60fbdf..2dc6a75795 100644 --- a/apps/web/src/components/SidebarV2.tsx +++ b/apps/web/src/components/SidebarV2.tsx @@ -14,6 +14,7 @@ import { CircleDashedIcon, CloudIcon, FolderPlusIcon, + MessageSquareIcon, PlusIcon, SearchIcon, SquarePenIcon, @@ -128,10 +129,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { // False on environments whose server predates thread.settle/unsettle: // the lifecycle affordances hide entirely rather than fail on click. settlementSupported: boolean; - // Marks where active work transitions into history: a quiet labeled - // rule above the first settled row, so the tail reads as a named zone - // rather than an unexplained gap. - showSettledGap?: boolean; isActive: boolean; jumpLabel: string | null; currentEnvironmentId: string | null; @@ -400,12 +397,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: { data-thread-item className="list-none [content-visibility:auto] [contain-intrinsic-size:auto_34px]" > - {props.showSettledGap ? ( -
- Settled - -
- ) : null}
{title} @@ -1531,7 +1523,7 @@ export default function SidebarV2() { ) : null}
    - {orderedThreads.map((thread, threadIndex) => { + {orderedThreads.flatMap((thread, threadIndex) => { const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); const isSettledRow = settledThreadKeys.has(threadKey); // Settled is the ONLY thing that collapses a row: every @@ -1546,10 +1538,14 @@ export default function SidebarV2() { scopedThreadKey(scopeThreadRef(previousThread.environmentId, previousThread.id)), ); const showSettledGap = !isCard && previousWasCard; - return ( + const row = ( ); + if (!showSettledGap) return [row]; + // The divider is its own keyed list item (not part of the first + // settled row): it keeps one stable DOM node at the boundary, + // so settling a thread slides it instead of teleporting it + // along with whichever row happens to be first in the tail — + // and row heights stay independent of neighbor classification. + return [ +
  • +
    + + Settled + + +
    +
  • , + row, + ]; })} {hiddenSettledCount > 0 ? (
  • diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 94e4af3bba..591a07ac4c 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -114,7 +114,9 @@ import { getProviderDisplayName, getProviderInteractionModeToggle } from "../../ import { applyProviderInstanceSettings, deriveProviderInstanceEntries, + NO_PROVIDER_MODEL_SELECTION, resolveProviderDriverKindForInstanceSelection, + resolveSelectableProviderInstanceEntry, sortProviderInstanceEntries, type ProviderInstanceEntry, } from "../../providerInstances"; @@ -433,6 +435,7 @@ export interface ChatComposerHandle { selectedPromptEffort: string | null; selectedModelOptionsForDispatch: unknown; selectedModelSelection: ModelSelection; + providerAvailable: boolean; selectedProvider: ProviderDriverKind; selectedModel: string; selectedProviderModels: ReadonlyArray; @@ -696,8 +699,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) providerInstanceEntries, providerStatuses, explicitSelectedInstanceId, - ) ?? ProviderDriverKind.make("codex"); - const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; + ) ?? + providerInstanceEntries[0]?.driverKind ?? + ProviderDriverKind.make("unconfigured"); + const requestedDriverKind: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider; const lockedContinuationGroupKey = useMemo((): string | null => { if (!lockedProvider || !activeThread) return null; const lockedInstanceId = @@ -734,7 +739,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) for (const candidate of candidates) { if (!candidate) continue; const match = providerInstanceEntries.find( - (entry) => entry.instanceId === candidate && entry.enabled, + (entry) => entry.instanceId === candidate && entry.enabled && entry.isAvailable, ); if (match) { // When locked to a specific driver kind, ignore persisted instance @@ -749,36 +754,44 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) return match.instanceId; } } - if (explicitSelectedInstanceId) { - return ProviderInstanceId.make(explicitSelectedInstanceId); - } - const byKind = providerInstanceEntries.find( + const compatibleEntries = providerInstanceEntries.filter( (entry) => - entry.enabled && - entry.driverKind === selectedProvider && + (!lockedProvider || entry.driverKind === lockedProvider) && (!lockedContinuationGroupKey || entry.continuationGroupKey === lockedContinuationGroupKey), ); - if (byKind) return byKind.instanceId; - const anyEnabled = providerInstanceEntries.find((entry) => entry.enabled); + const requestedDriverEntries = compatibleEntries.filter( + (entry) => entry.driverKind === requestedDriverKind, + ); return ( - anyEnabled?.instanceId ?? - providerInstanceEntries[0]?.instanceId ?? - activeThreadModelSelection?.instanceId ?? - activeProjectDefaultModelSelection?.instanceId ?? - ProviderInstanceId.make("codex") + resolveSelectableProviderInstanceEntry(requestedDriverEntries, undefined)?.instanceId ?? + resolveSelectableProviderInstanceEntry(compatibleEntries, undefined)?.instanceId ?? + NO_PROVIDER_MODEL_SELECTION.instanceId ); }, [ activeProjectDefaultModelSelection?.instanceId, activeThread?.session?.providerInstanceId, activeThreadModelSelection?.instanceId, composerDraft.activeProvider, - explicitSelectedInstanceId, lockedContinuationGroupKey, lockedProvider, providerInstanceEntries, - selectedProvider, + requestedDriverKind, ]); + // Resolve the active instance's snapshot by `instanceId` so a custom + // instance gets its own slash commands, skills, and model list — not + // the first snapshot for the same driver kind. + const selectedProviderEntry = useMemo( + () => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId), + [providerInstanceEntries, selectedInstanceId], + ); + const noProviderAvailable = selectedProviderEntry === undefined; + // The driver kind follows the instance that will actually run the turn, + // which can differ from the persisted selection when that selection is + // disabled. + const selectedProvider: ProviderDriverKind = + selectedProviderEntry?.driverKind ?? requestedDriverKind; + const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({ threadRef: composerDraftTarget, providers: providerStatuses, @@ -788,14 +801,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) projectModelSelection: activeProjectDefaultModelSelection, settings, }); - - // Resolve the active instance's snapshot by `instanceId` so a custom - // instance gets its own slash commands, skills, and model list — not - // the first snapshot for the same driver kind. - const selectedProviderEntry = useMemo( - () => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId), - [providerInstanceEntries, selectedInstanceId], - ); const selectedProviderStatus = useMemo( () => selectedProviderEntry?.snapshot ?? null, [selectedProviderEntry], @@ -1158,6 +1163,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) phase === "running" || isSendBusy || isConnecting || + noProviderAvailable || projectSelectionRequired || environmentUnavailable !== null || !composerSendState.hasSendableContent; @@ -1698,7 +1704,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const shouldBlurMobileComposerOnSubmit = useCallback(() => { if (!isMobileViewport) return false; - if (isSendBusy || isConnecting || environmentUnavailable !== null || phase === "running") { + if ( + isSendBusy || + isConnecting || + noProviderAvailable || + environmentUnavailable !== null || + phase === "running" + ) { return false; } if (activePendingProgress) { @@ -1713,18 +1725,23 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isConnecting, isMobileViewport, isSendBusy, + noProviderAvailable, phase, showPlanFollowUpPrompt, ]); const submitComposer = useCallback( (event?: { preventDefault: () => void }) => { + if (noProviderAvailable) { + event?.preventDefault(); + return; + } onSend(event); if (shouldBlurMobileComposerOnSubmit()) { blurMobileComposerAfterSend(); } }, - [blurMobileComposerAfterSend, onSend, shouldBlurMobileComposerOnSubmit], + [blurMobileComposerAfterSend, noProviderAvailable, onSend, shouldBlurMobileComposerOnSubmit], ); const expandMobileComposer = useCallback(() => { if (composerBlurFrameRef.current !== null) { @@ -2083,6 +2100,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedPromptEffort, selectedModelOptionsForDispatch, selectedModelSelection, + providerAvailable: !noProviderAvailable, selectedProvider, selectedModel, selectedProviderModels, @@ -2110,6 +2128,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) selectedModel, selectedModelOptionsForDispatch, selectedModelSelection, + noProviderAvailable, selectedPromptEffort, selectedProvider, selectedProviderModels, @@ -2260,7 +2279,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isSendBusy={isSendBusy} isConnecting={isConnecting} isEnvironmentUnavailable={ - environmentUnavailable !== null || projectSelectionRequired + environmentUnavailable !== null || + noProviderAvailable || + projectSelectionRequired } isPreparingWorktree={false} hasSendableContent={false} @@ -2292,7 +2313,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {activePendingProgress ? activePendingProgress.customAnswer || "Type your own answer, or leave this blank to use the selected option" - : prompt.trim() || "Ask anything..."} + : prompt.trim() || + (noProviderAvailable ? "Enable a provider in Settings" : "Ask anything...")} + ) : ( + { + setIsComposerModelPickerOpen(open); + }} + getModelDisabledReason={getModelDisabledReason} + onInstanceModelChange={onProviderModelSelect} + /> + )} {isComposerFooterCompact ? ( { + it("offers both open actions and Copy Link", async () => { + const harness = createHarness(null); + + await showExternalLinkContextMenu({ + href: "https://example.com/docs?topic=menus#copy", + position: { x: 12, y: 24 }, + ...harness, + }); + + expect(harness.showContextMenu).toHaveBeenCalledWith( + [ + { id: "open-in-preview", label: "Open in integrated browser" }, + { id: "open-external", label: "Open in system browser" }, + { id: "copy-link", label: "Copy Link" }, + ], + { x: 12, y: 24 }, + ); + expect(harness.openInPreview).not.toHaveBeenCalled(); + expect(harness.openExternal).not.toHaveBeenCalled(); + expect(harness.copyLink).not.toHaveBeenCalled(); + }); + + it("copies the exact destination without opening it", async () => { + const harness = createHarness("copy-link"); + const href = "https://example.com/docs?topic=menus#copy"; + + await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness }); + + expect(harness.copyLink).toHaveBeenCalledWith(href); + expect(harness.openInPreview).not.toHaveBeenCalled(); + expect(harness.openExternal).not.toHaveBeenCalled(); + }); + + it.each([ + ["open-in-preview" as const, "openInPreview" as const], + ["open-external" as const, "openExternal" as const], + ])("preserves the %s action", async (selection, expectedCallback) => { + const harness = createHarness(selection); + const href = "https://example.com/docs"; + + await showExternalLinkContextMenu({ href, position: { x: 1, y: 2 }, ...harness }); + + expect(harness[expectedCallback]).toHaveBeenCalledWith(href); + expect(harness.copyLink).not.toHaveBeenCalled(); + }); + + it("reports the selected action when it fails", async () => { + const harness = createHarness("copy-link"); + const cause = new Error("clipboard denied"); + harness.copyLink.mockRejectedValue(cause); + + await showExternalLinkContextMenu({ + href: "https://example.com/docs", + position: { x: 1, y: 2 }, + ...harness, + }); + + expect(harness.reportFailure).toHaveBeenCalledWith("copy-link", cause); + }); + + it("reports the menu operation when the native menu cannot be shown", async () => { + const harness = createHarness(null); + const cause = new Error("menu unavailable"); + harness.showContextMenu.mockRejectedValue(cause); + + await showExternalLinkContextMenu({ + href: "https://example.com/docs", + position: { x: 1, y: 2 }, + ...harness, + }); + + expect(harness.reportFailure).toHaveBeenCalledWith("show-link-context-menu", cause); + expect(harness.openInPreview).not.toHaveBeenCalled(); + expect(harness.openExternal).not.toHaveBeenCalled(); + expect(harness.copyLink).not.toHaveBeenCalled(); + }); + + it.each([ + ["open-in-preview" as const, "openInPreview" as const, "open-link-in-preview"], + ["open-external" as const, "openExternal" as const, "open-link-external"], + ])("reports a failed %s action", async (selection, callback, operation) => { + const harness = createHarness(selection); + const cause = new Error("open failed"); + harness[callback].mockRejectedValue(cause); + + await showExternalLinkContextMenu({ + href: "https://example.com/docs", + position: { x: 1, y: 2 }, + ...harness, + }); + + expect(harness.reportFailure).toHaveBeenCalledWith(operation, cause); + }); + + it.each([ + ["https://example.com", "example.com"], + ["http://localhost:3000/path", "localhost"], + ["#details", null], + ["mailto:hello@example.com", null], + ["file:///tmp/example.txt", null], + ["javascript:void(0)", null], + ["not a URL", null], + [undefined, null], + ])("resolves the external web-link host for %s as %s", (href, expected) => { + expect(resolveExternalWebLinkHost(href)).toBe(expected); + }); +}); diff --git a/apps/web/src/components/chat/externalLinkContextMenu.ts b/apps/web/src/components/chat/externalLinkContextMenu.ts new file mode 100644 index 0000000000..398ca40da5 --- /dev/null +++ b/apps/web/src/components/chat/externalLinkContextMenu.ts @@ -0,0 +1,78 @@ +import type { ContextMenuItem } from "@t3tools/contracts"; + +export type ExternalLinkContextMenuAction = "open-in-preview" | "open-external" | "copy-link"; + +export type ExternalLinkContextMenuFailureOperation = + | "show-link-context-menu" + | "open-link-in-preview" + | "open-link-external" + | "copy-link"; + +const FAILURE_OPERATION_BY_ACTION = { + "open-in-preview": "open-link-in-preview", + "open-external": "open-link-external", + "copy-link": "copy-link", +} as const satisfies Record; + +const EXTERNAL_LINK_CONTEXT_MENU_ITEMS = [ + { id: "open-in-preview", label: "Open in integrated browser" }, + { id: "open-external", label: "Open in system browser" }, + { id: "copy-link", label: "Copy Link" }, +] as const satisfies readonly ContextMenuItem[]; + +interface ShowExternalLinkContextMenuOptions { + readonly href: string; + readonly position: { readonly x: number; readonly y: number }; + readonly showContextMenu: ( + items: readonly ContextMenuItem[], + position: { readonly x: number; readonly y: number }, + ) => Promise; + readonly openInPreview: (href: string) => Promise; + readonly openExternal: (href: string) => Promise; + readonly copyLink: (href: string) => Promise; + readonly reportFailure: ( + operation: ExternalLinkContextMenuFailureOperation, + cause: unknown, + ) => void; +} + +export function resolveExternalWebLinkHost(href: string | undefined): string | null { + if (!href) return null; + try { + const url = new URL(href); + if (url.protocol !== "http:" && url.protocol !== "https:") return null; + return url.hostname || null; + } catch { + return null; + } +} + +export async function showExternalLinkContextMenu({ + href, + position, + showContextMenu, + openInPreview, + openExternal, + copyLink, + reportFailure, +}: ShowExternalLinkContextMenuOptions): Promise { + let action: ExternalLinkContextMenuAction | null; + try { + action = await showContextMenu(EXTERNAL_LINK_CONTEXT_MENU_ITEMS, position); + } catch (cause) { + reportFailure("show-link-context-menu", cause); + return; + } + + try { + if (action === "open-in-preview") { + await openInPreview(href); + } else if (action === "open-external") { + await openExternal(href); + } else if (action === "copy-link") { + await copyLink(href); + } + } catch (cause) { + if (action) reportFailure(FAILURE_OPERATION_BY_ACTION[action], cause); + } +} diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts new file mode 100644 index 0000000000..fdffa9a190 --- /dev/null +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.logic.ts @@ -0,0 +1,36 @@ +export type WizardNavigation = + | { readonly kind: "navigate"; readonly step: number } + | { readonly kind: "blocked"; readonly step: number; readonly error: string }; + +const IDENTITY_STEP = 1; + +export const ADD_PROVIDER_WIZARD_STEPS = ["Driver", "Identity", "Config"] as const; + +/** + * Resolve navigation within the add-provider wizard. + * + * Moving forward past Identity requires a valid instance id, whether the user + * advances one step at a time or skips directly to Config from a step header. + * A blocked skip lands on Identity so its existing inline validation is + * visible. Backward navigation is always preserved. + */ +export function resolveWizardNavigation( + currentStep: number, + requestedStep: number, + stepCount: number, + validation: { readonly instanceIdError: string | null }, +): WizardNavigation { + const lastStep = Math.max(0, stepCount - 1); + const targetStep = Math.max(0, Math.min(lastStep, requestedStep)); + const movesForwardPastIdentity = currentStep <= IDENTITY_STEP && targetStep > IDENTITY_STEP; + + if (movesForwardPastIdentity && validation.instanceIdError !== null) { + return { + kind: "blocked", + step: Math.min(IDENTITY_STEP, lastStep), + error: validation.instanceIdError, + }; + } + + return { kind: "navigate", step: targetStep }; +} diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts b/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts new file mode 100644 index 0000000000..594d2e4537 --- /dev/null +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { resolveWizardNavigation } from "./AddProviderInstanceDialog.logic"; + +describe("resolveWizardNavigation", () => { + const invalidId = { instanceIdError: "Instance ID is required." }; + const validId = { instanceIdError: null }; + + it("allows moving from Driver to Identity before the instance id is valid", () => { + expect(resolveWizardNavigation(0, 1, 3, invalidId)).toEqual({ kind: "navigate", step: 1 }); + }); + + it("blocks Next from Identity to Config while the instance id is invalid", () => { + expect(resolveWizardNavigation(1, 2, 3, invalidId)).toEqual({ + kind: "blocked", + step: 1, + error: "Instance ID is required.", + }); + }); + + it("stops a direct Driver-to-Config skip at Identity and surfaces its error", () => { + expect(resolveWizardNavigation(0, 2, 3, invalidId)).toEqual({ + kind: "blocked", + step: 1, + error: "Instance ID is required.", + }); + }); + + it("allows advancing and skipping forward once the instance id is valid", () => { + expect(resolveWizardNavigation(1, 2, 3, validId)).toEqual({ kind: "navigate", step: 2 }); + expect(resolveWizardNavigation(0, 2, 3, validId)).toEqual({ kind: "navigate", step: 2 }); + }); + + it("always preserves backward Driver and Identity navigation", () => { + expect(resolveWizardNavigation(2, 1, 3, invalidId)).toEqual({ kind: "navigate", step: 1 }); + expect(resolveWizardNavigation(2, 0, 3, invalidId)).toEqual({ kind: "navigate", step: 0 }); + expect(resolveWizardNavigation(1, 0, 3, invalidId)).toEqual({ kind: "navigate", step: 0 }); + }); + + it("clamps requested steps to the wizard bounds", () => { + expect(resolveWizardNavigation(2, 8, 3, validId)).toEqual({ kind: "navigate", step: 2 }); + expect(resolveWizardNavigation(0, -1, 3, invalidId)).toEqual({ kind: "navigate", step: 0 }); + }); +}); diff --git a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx index 77c1813f11..ed808e30b0 100644 --- a/apps/web/src/components/settings/AddProviderInstanceDialog.tsx +++ b/apps/web/src/components/settings/AddProviderInstanceDialog.tsx @@ -1,8 +1,7 @@ "use client"; -import { CheckIcon } from "lucide-react"; import { Radio as RadioPrimitive } from "@base-ui/react/radio"; -import { useCallback, useMemo, useState } from "react"; +import { useMemo, useState } from "react"; import { ProviderInstanceId, ProviderDriverKind, @@ -29,6 +28,12 @@ import { toastManager } from "../ui/toast"; import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta"; import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm"; import { AnimatedHeight } from "../AnimatedHeight"; +import { + ADD_PROVIDER_WIZARD_STEPS, + resolveWizardNavigation, + type WizardNavigation, +} from "./AddProviderInstanceDialog.logic"; +import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps"; const PROVIDER_ACCENT_SWATCHES = [ "#2563eb", @@ -143,26 +148,37 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns const instanceIdError = validateInstanceId(instanceId, existingIds); const showInstanceIdError = hasAttemptedSubmit && instanceIdError !== null; const previewLabel = label.trim() || `${driverOption.label} Workspace`; - const wizardSteps = ["Driver", "Identity", "Config"] as const; const wizardStepSummaries = [driverOption.label, previewLabel, null] as const; const configDraft = configByDriver[driver] ?? EMPTY_CONFIG_DRAFT; - const setConfigDraft = useCallback( - (config: Record | undefined) => { - setConfigByDriver((existing) => { - const next = { ...existing }; - if (config === undefined || Object.keys(config).length === 0) { - delete next[driver]; - } else { - next[driver] = config; - } - return next; - }); - }, - [driver], - ); + const setConfigDraft = (config: Record | undefined) => { + setConfigByDriver((existing) => { + const next = { ...existing }; + if (config === undefined || Object.keys(config).length === 0) { + delete next[driver]; + } else { + next[driver] = config; + } + return next; + }); + }; - const handleSave = useCallback(() => { + const applyWizardNavigation = (navigation: WizardNavigation) => { + if (navigation.kind === "blocked") { + setHasAttemptedSubmit(true); + } + setWizardStep(navigation.step); + }; + + const navigateToStep = (requestedStep: number) => { + applyWizardNavigation( + resolveWizardNavigation(wizardStep, requestedStep, ADD_PROVIDER_WIZARD_STEPS.length, { + instanceIdError, + }), + ); + }; + + const handleSave = () => { setHasAttemptedSubmit(true); if (instanceIdError !== null) return; @@ -201,18 +217,7 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns description: error instanceof Error ? error.message : "Update failed.", }); } - }, [ - driver, - driverOption, - configByDriver, - instanceId, - instanceIdError, - label, - accentColor, - onOpenChange, - settings.providerInstances, - updateSettings, - ]); + }; return ( @@ -224,46 +229,12 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns Configure an additional provider instance — for example, a second Codex install pointed at a different workspace. -
    - {wizardSteps.map((step, index) => ( - - ))} -
    +
    {wizardStep === 0 ? "Cancel" : "Back"} - {wizardStep < wizardSteps.length - 1 ? ( - ) : ( diff --git a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx new file mode 100644 index 0000000000..964779f4ec --- /dev/null +++ b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.test.tsx @@ -0,0 +1,61 @@ +import { Children, isValidElement, type ReactElement } from "react"; +import { describe, expect, it, vi } from "vite-plus/test"; + +import { ADD_PROVIDER_WIZARD_STEPS } from "./AddProviderInstanceDialog.logic"; +import { AddProviderInstanceWizardSteps } from "./AddProviderInstanceWizardSteps"; + +interface StepButtonProps { + readonly "aria-current"?: string; + readonly onClick: () => void; +} + +function renderStepButtons( + currentStep: number, + instanceIdError: string | null, + onNavigation: Parameters[0]["onNavigation"], +): ReactElement[] { + const header = AddProviderInstanceWizardSteps({ + currentStep, + summaries: ["Codex", "Codex Workspace", null], + instanceIdError, + onNavigation, + }); + + return Children.toArray(header.props.children).filter( + (child): child is ReactElement => isValidElement(child), + ); +} + +describe("AddProviderInstanceWizardSteps", () => { + it("gates the actual Config header click through Identity validation", () => { + const onNavigation = vi.fn(); + const buttons = renderStepButtons(0, "Instance ID is required.", onNavigation); + + expect(buttons).toHaveLength(ADD_PROVIDER_WIZARD_STEPS.length); + buttons[2]!.props.onClick(); + + expect(onNavigation).toHaveBeenCalledOnce(); + expect(onNavigation).toHaveBeenCalledWith({ + kind: "blocked", + step: 1, + error: "Instance ID is required.", + }); + }); + + it("marks the wizard step separately from the clicked button focus", () => { + const buttons = renderStepButtons(1, "Instance ID is required.", vi.fn()); + + expect(buttons[0]!.props["aria-current"]).toBeUndefined(); + expect(buttons[1]!.props["aria-current"]).toBe("step"); + expect(buttons[2]!.props["aria-current"]).toBeUndefined(); + }); + + it("preserves the actual backward header click", () => { + const onNavigation = vi.fn(); + const buttons = renderStepButtons(2, "Instance ID is required.", onNavigation); + + buttons[0]!.props.onClick(); + + expect(onNavigation).toHaveBeenCalledWith({ kind: "navigate", step: 0 }); + }); +}); diff --git a/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx new file mode 100644 index 0000000000..4747557471 --- /dev/null +++ b/apps/web/src/components/settings/AddProviderInstanceWizardSteps.tsx @@ -0,0 +1,70 @@ +import { CheckIcon } from "lucide-react"; + +import { cn } from "../../lib/utils"; +import { + ADD_PROVIDER_WIZARD_STEPS, + resolveWizardNavigation, + type WizardNavigation, +} from "./AddProviderInstanceDialog.logic"; + +interface AddProviderInstanceWizardStepsProps { + readonly currentStep: number; + readonly summaries: readonly (string | null)[]; + readonly instanceIdError: string | null; + readonly onNavigation: (navigation: WizardNavigation) => void; +} + +export function AddProviderInstanceWizardSteps({ + currentStep, + summaries, + instanceIdError, + onNavigation, +}: AddProviderInstanceWizardStepsProps) { + return ( +
    + {ADD_PROVIDER_WIZARD_STEPS.map((step, index) => ( + + ))} +
    + ); +} diff --git a/apps/web/src/composer-editor-mentions.test.ts b/apps/web/src/composer-editor-mentions.test.ts index d79170769d..70c9740037 100644 --- a/apps/web/src/composer-editor-mentions.test.ts +++ b/apps/web/src/composer-editor-mentions.test.ts @@ -22,9 +22,9 @@ describe("splitPromptIntoComposerSegments", () => { }); it("keeps newlines around mention tokens", () => { - expect(splitPromptIntoComposerSegments("one\n@src/index.ts \ntwo")).toEqual([ + expect(splitPromptIntoComposerSegments("one\n@AGENTS.md \ntwo")).toEqual([ { type: "text", text: "one\n" }, - { type: "mention", path: "src/index.ts", source: "@src/index.ts" }, + { type: "mention", path: "AGENTS.md", source: "@AGENTS.md" }, { type: "text", text: " \ntwo" }, ]); }); @@ -71,6 +71,31 @@ describe("splitPromptIntoComposerSegments", () => { ).toEqual([{ type: "text", text: "Read [the docs](https://example.com/docs) first" }]); }); + it.each(["@expo/ui", "@jane/foo.js", "@scope/pkg/sub/path"])( + "does not turn scoped package reference %s into file mention segments", + (reference) => { + const prompt = `Install ${reference} next`; + expect(splitPromptIntoComposerSegments(prompt)).toEqual([{ type: "text", text: prompt }]); + }, + ); + + it("keeps IME-composed text containing a scoped package reference as text", () => { + const prompt = "入力 @expo/ui を追加"; + expect(splitPromptIntoComposerSegments(prompt)).toEqual([{ type: "text", text: prompt }]); + }); + + it("turns canonical scoped folder links into file mention segments", () => { + expect(splitPromptIntoComposerSegments("Inspect [sub](@scope/pkg/sub) next")).toEqual([ + { type: "text", text: "Inspect " }, + { + type: "mention", + path: "@scope/pkg/sub", + source: "[sub](@scope/pkg/sub)", + }, + { type: "text", text: " next" }, + ]); + }); + it("decodes reserved path characters from generated links", () => { expect( splitPromptIntoComposerSegments( diff --git a/apps/web/src/composer-logic.test.ts b/apps/web/src/composer-logic.test.ts index 99ac6bba71..b8ef744361 100644 --- a/apps/web/src/composer-logic.test.ts +++ b/apps/web/src/composer-logic.test.ts @@ -246,12 +246,21 @@ describe("collapseExpandedComposerCursor", () => { ); }); - it("keeps replacement cursors aligned when another mention already exists earlier", () => { + it("keeps package-like text expanded when another mention already exists earlier", () => { const text = "open @AGENTS.md then @src/index.ts "; const expandedCursor = text.length; const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor); - expect(collapsedCursor).toBe("open ".length + 1 + " then ".length + 2); + expect(collapsedCursor).toBe("open ".length + 1 + " then @src/index.ts ".length); + expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor); + }); + + it("collapses only genuine mentions when package-like text exists earlier", () => { + const text = "install @scope/pkg then @README.md "; + const expandedCursor = text.length; + const collapsedCursor = collapseExpandedComposerCursor(text, expandedCursor); + + expect(collapsedCursor).toBe("install @scope/pkg then ".length + 1 + " ".length); expect(expandCollapsedComposerCursor(text, collapsedCursor)).toBe(expandedCursor); }); diff --git a/apps/web/src/providerInstances.test.ts b/apps/web/src/providerInstances.test.ts index a5b03f5632..2d0d7bb021 100644 --- a/apps/web/src/providerInstances.test.ts +++ b/apps/web/src/providerInstances.test.ts @@ -3,8 +3,10 @@ import { describe, expect, it } from "vite-plus/test"; import { applyProviderInstanceSettings, deriveProviderInstanceEntries, + getDefaultProviderInstanceModel, isProviderInstancePickerReady, isProviderInstancePickerVisible, + resolveDefaultProviderModelSelection, resolveSelectableProviderInstance, resolveProviderDriverKindForInstanceSelection, } from "./providerInstances"; @@ -15,6 +17,8 @@ function provider(input: { enabled?: boolean; availability?: ServerProvider["availability"]; displayName?: string; + status?: ServerProvider["status"]; + models?: ServerProvider["models"]; }): ServerProvider { return { instanceId: ProviderInstanceId.make(input.instanceId), @@ -23,16 +27,24 @@ function provider(input: { enabled: input.enabled ?? true, installed: true, version: null, - status: "ready", + status: input.status ?? "ready", ...(input.availability ? { availability: input.availability } : {}), auth: { status: "authenticated" }, checkedAt: "2026-01-01T00:00:00.000Z", - models: [], + models: input.models ?? [], slashCommands: [], skills: [], }; } +const model = (slug: string, isCustom = false, isDefault = false) => ({ + slug, + name: slug, + isCustom, + ...(isDefault ? { isDefault: true } : {}), + capabilities: {}, +}); + describe("isProviderInstancePickerReady", () => { it("rejects a disabled instance even while its last probe status is ready", () => { const [entry] = deriveProviderInstanceEntries([ @@ -146,6 +158,67 @@ describe("resolveSelectableProviderInstance", () => { expect(resolveSelectableProviderInstance(providers, disabled)).toBe(fallback); }); + it("prefers a ready instance over an enabled one whose driver cannot start", () => { + const notInstalled = ProviderInstanceId.make("codex"); + const ready = ProviderInstanceId.make("claudeAgent"); + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: notInstalled, + status: "error", + }), + provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: ready }), + ]; + + expect(resolveSelectableProviderInstance(providers, undefined)).toBe(ready); + }); + + it("prefers an unprobed (warning) instance over one whose probe errored", () => { + const notInstalled = ProviderInstanceId.make("codex"); + const unprobed = ProviderInstanceId.make("claudeAgent"); + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: notInstalled, + status: "error", + }), + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: unprobed, + status: "warning", + }), + ]; + + expect(resolveSelectableProviderInstance(providers, undefined)).toBe(unprobed); + }); + + it("keeps a requested instance even when its probe errored", () => { + const requested = ProviderInstanceId.make("codex"); + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: requested, + status: "error", + }), + provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: "claudeAgent" }), + ]; + + expect(resolveSelectableProviderInstance(providers, requested)).toBe(requested); + }); + + it("does not invent an errored instance as a new-user default", () => { + const notInstalled = ProviderInstanceId.make("codex"); + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: notInstalled, + status: "error", + }), + ]; + + expect(resolveSelectableProviderInstance(providers, undefined)).toBeUndefined(); + }); + it("does not return disabled, unavailable, or unknown instances when none are sendable", () => { const disabled = ProviderInstanceId.make("codex"); const unavailable = ProviderInstanceId.make("claudeAgent"); @@ -206,3 +279,184 @@ describe("resolveProviderDriverKindForInstanceSelection", () => { ).toBeUndefined(); }); }); + +describe("getDefaultProviderInstanceModel", () => { + it("uses the instance's own models, not the default instance of the kind", () => { + const providers = [ + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claude_openrouter", + models: [model("openai/gpt-5.5", true), model("claude-opus-4-8")], + }), + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claudeAgent", + models: [model("claude-sonnet-5")], + }), + ]; + + expect( + getDefaultProviderInstanceModel(providers, ProviderInstanceId.make("claude_openrouter")), + ).toBe("claude-opus-4-8"); + }); + + it("falls back to the driver default when the instance reports no models", () => { + const providers = [ + provider({ provider: ProviderDriverKind.make("claudeAgent"), instanceId: "claudeAgent" }), + ]; + + const resolved = getDefaultProviderInstanceModel( + providers, + ProviderInstanceId.make("claudeAgent"), + ); + expect(typeof resolved).toBe("string"); + expect(resolved?.length).toBeGreaterThan(0); + }); + + it("honors the instance's declared default before model-list order", () => { + const providers = [ + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claudeAgent", + models: [model("claude-sonnet-5"), model("claude-opus-4-8", false, true)], + }), + ]; + + expect(getDefaultProviderInstanceModel(providers, ProviderInstanceId.make("claudeAgent"))).toBe( + "claude-opus-4-8", + ); + }); + + it("returns undefined for an unknown instance", () => { + expect( + getDefaultProviderInstanceModel([], ProviderInstanceId.make("removed_instance")), + ).toBeUndefined(); + }); +}); + +describe("resolveDefaultProviderModelSelection", () => { + it.each([ + ["codex", "codex", "gpt-5.6"], + ["claudeAgent", "claudeAgent", "claude-fable-5"], + ["cursor", "cursor", "composer-2"], + ])("uses the only available %s instance", (driver, instanceId, modelSlug) => { + const providers = [ + provider({ + provider: ProviderDriverKind.make(driver), + instanceId, + models: [model(modelSlug, false, true)], + }), + ]; + + expect(resolveDefaultProviderModelSelection(providers, null)).toEqual({ + instanceId, + model: modelSlug, + }); + }); + + it("preserves a valid stored selection including its options", () => { + const providers = [ + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claudeAgent", + models: [model("claude-opus-4-8")], + }), + ]; + const stored = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "custom-model", + options: [{ id: "effort", value: "high" }], + }; + + expect(resolveDefaultProviderModelSelection(providers, stored)).toBe(stored); + }); + + it("replaces a stale stored instance with the first ready instance and its model", () => { + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: "codex", + status: "warning", + models: [model("gpt-5.6")], + }), + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claudeAgent", + models: [model("claude-opus-4-8", false, true)], + }), + ]; + + expect( + resolveDefaultProviderModelSelection(providers, { + instanceId: ProviderInstanceId.make("removed-provider"), + model: "stale-model", + }), + ).toEqual({ instanceId: "claudeAgent", model: "claude-opus-4-8" }); + }); + + it.each([{ enabled: false }, { availability: "unavailable" as const }])( + "replaces an unavailable stored instance deterministically", + (requestedState) => { + const providers = [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: "codex", + models: [model("gpt-5.6")], + ...requestedState, + }), + provider({ + provider: ProviderDriverKind.make("claudeAgent"), + instanceId: "claudeAgent", + models: [model("claude-opus-4-8", false, true)], + }), + ]; + + expect( + resolveDefaultProviderModelSelection(providers, { + instanceId: ProviderInstanceId.make("codex"), + model: "gpt-5.6", + }), + ).toEqual({ instanceId: "claudeAgent", model: "claude-opus-4-8" }); + }, + ); + + it("returns no selection for empty, disabled, unavailable, or error-only profiles", () => { + expect(resolveDefaultProviderModelSelection([], null)).toBeNull(); + expect( + resolveDefaultProviderModelSelection( + [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: "codex", + enabled: false, + }), + ], + null, + ), + ).toBeNull(); + expect( + resolveDefaultProviderModelSelection( + [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: "codex", + availability: "unavailable", + }), + ], + null, + ), + ).toBeNull(); + expect( + resolveDefaultProviderModelSelection( + [ + provider({ + provider: ProviderDriverKind.make("codex"), + instanceId: "codex", + status: "error", + }), + ], + null, + ), + ).toBeNull(); + }); +}); diff --git a/apps/web/src/providerInstances.ts b/apps/web/src/providerInstances.ts index c9ac87ac39..337e68d44d 100644 --- a/apps/web/src/providerInstances.ts +++ b/apps/web/src/providerInstances.ts @@ -13,10 +13,12 @@ * @module providerInstances */ import { + DEFAULT_MODEL_BY_PROVIDER, defaultInstanceIdForDriver, PROVIDER_DISPLAY_NAMES, + type ModelSelection, type ProviderDriverKind, - type ProviderInstanceId, + ProviderInstanceId, type ServerProvider, type ServerProviderModel, type ServerSettings, @@ -25,6 +27,16 @@ import { import { formatProviderDriverKindLabel } from "./providerModels"; +/** + * Local-only placeholder used while a draft has no provider it can safely + * target. It must never be persisted or dispatched; the composer disables + * send until a live provider replaces it. + */ +export const NO_PROVIDER_MODEL_SELECTION: ModelSelection = { + instanceId: ProviderInstanceId.make("t3code_no_provider"), + model: "", +}; + /** * UI-facing projection of one configured provider instance. Carries the * snapshot verbatim for callers that need server-side fields we don't @@ -253,27 +265,82 @@ export function getProviderInstanceModels( return getProviderInstanceEntry(providers, instanceId)?.models ?? []; } +/** + * Default model slug for a specific instance: its declared built-in default, + * then its first built-in model, then any model it reports, then the driver-level default. Custom + * instances can serve a different model list than the default instance of + * the same driver kind, so the lookup must be instance-scoped rather than + * kind-scoped. + */ +export function getDefaultProviderInstanceModel( + providers: ReadonlyArray, + instanceId: ProviderInstanceId, +): string | undefined { + const entry = getProviderInstanceEntry(providers, instanceId); + if (!entry) return undefined; + return ( + entry.models.find((model) => model.isDefault && !model.isCustom)?.slug ?? + entry.models.find((model) => !model.isCustom)?.slug ?? + entry.models[0]?.slug ?? + DEFAULT_MODEL_BY_PROVIDER[entry.driverKind] + ); +} + +const isSelectableProviderInstanceEntry = (entry: ProviderInstanceEntry): boolean => + entry.enabled && entry.isAvailable; + +/** + * Resolve an exact stored instance when it remains enabled and available. + * Otherwise choose a deterministic fallback that can plausibly start now: + * ready first, then a non-error probe result. An errored provider is retained + * only when it was explicitly requested; it is never invented as a new-user + * default. + */ +export function resolveSelectableProviderInstanceEntry( + entries: ReadonlyArray, + instanceId: ProviderInstanceId | undefined, +): ProviderInstanceEntry | undefined { + if (instanceId !== undefined) { + const requested = entries.find((entry) => entry.instanceId === instanceId); + if (requested && isSelectableProviderInstanceEntry(requested)) { + return requested; + } + } + return ( + entries.find(isProviderInstancePickerReady) ?? + entries.find((entry) => isSelectableProviderInstanceEntry(entry) && entry.status !== "error") + ); +} + /** * Resolve the routing key for a selection that may reference an instance * id that no longer exists (e.g. a persisted thread selection after the - * user deleted the custom instance). Returns the first enabled instance - * as a fallback so downstream code can still send a turn. + * user deleted the custom instance). Returns a ready or non-error fallback, + * or `undefined` when no provider can safely become a new selection. */ export function resolveSelectableProviderInstance( providers: ReadonlyArray, instanceId: ProviderInstanceId | undefined, ): ProviderInstanceId | undefined { - if (instanceId === undefined) { - return deriveProviderInstanceEntries(providers).find( - (entry) => entry.enabled && entry.isAvailable, - )?.instanceId; - } const entries = deriveProviderInstanceEntries(providers); - const requested = entries.find((entry) => entry.instanceId === instanceId); - if (requested && requested.enabled && requested.isAvailable) { - return instanceId; - } - return entries.find((entry) => entry.enabled && entry.isAvailable)?.instanceId; + return resolveSelectableProviderInstanceEntry(entries, instanceId)?.instanceId; +} + +/** + * Resolve the model selection persisted for a project or new thread. A valid + * stored selection is preserved byte-for-byte. Falling back to another + * instance also resets the model to that instance's own default, avoiding + * cross-provider instance/model pairs. + */ +export function resolveDefaultProviderModelSelection( + providers: ReadonlyArray, + selection: ModelSelection | null | undefined, +): ModelSelection | null { + const instanceId = resolveSelectableProviderInstance(providers, selection?.instanceId); + if (instanceId === undefined) return null; + if (selection?.instanceId === instanceId) return selection; + const model = getDefaultProviderInstanceModel(providers, instanceId); + return model ? { instanceId, model } : null; } /** diff --git a/apps/web/src/threadRoutes.test.ts b/apps/web/src/threadRoutes.test.ts index d15a233a30..644cdccb5c 100644 --- a/apps/web/src/threadRoutes.test.ts +++ b/apps/web/src/threadRoutes.test.ts @@ -6,6 +6,7 @@ import { DraftId } from "./composerDraftStore"; import { buildDraftThreadRouteParams, buildThreadRouteParams, + resolveActiveThreadRouteRef, resolveThreadRouteRef, resolveThreadRouteTarget, } from "./threadRoutes"; @@ -64,4 +65,31 @@ describe("threadRoutes", () => { draftId: "draft-1", }); }); + + it("resolves the backing thread while a draft route is being promoted", () => { + const target = resolveThreadRouteTarget({ draftId: "draft-1" }); + + expect( + resolveActiveThreadRouteRef(target, { + environmentId: "env-1" as never, + threadId: ThreadId.make("draft-thread"), + promotedTo: scopeThreadRef("env-2" as never, ThreadId.make("server-thread")), + }), + ).toEqual({ + environmentId: "env-2", + threadId: "server-thread", + }); + }); + + it("does not treat a draft's reserved thread ref as an active sidebar thread", () => { + const target = resolveThreadRouteTarget({ draftId: "draft-1" }); + + expect( + resolveActiveThreadRouteRef(target, { + environmentId: "env-1" as never, + threadId: ThreadId.make("draft-thread"), + promotedTo: null, + }), + ).toBeNull(); + }); }); diff --git a/apps/web/src/threadRoutes.ts b/apps/web/src/threadRoutes.ts index 19a7d5ca60..a4d853c0a7 100644 --- a/apps/web/src/threadRoutes.ts +++ b/apps/web/src/threadRoutes.ts @@ -12,6 +12,12 @@ export type ThreadRouteTarget = draftId: DraftId; }; +type DraftThreadRouteState = { + environmentId: EnvironmentId; + threadId: ThreadId; + promotedTo?: ScopedThreadRef | null; +}; + export function buildThreadRouteParams(ref: ScopedThreadRef): { environmentId: EnvironmentId; threadId: ThreadId; @@ -57,3 +63,20 @@ export function resolveThreadRouteTarget( draftId: params.draftId as DraftId, }; } + +/** + * Resolves the thread represented by either a canonical thread route or a + * draft route whose promotion to a server thread has been recorded. + */ +export function resolveActiveThreadRouteRef( + target: ThreadRouteTarget | null, + draftThread: DraftThreadRouteState | null, +): ScopedThreadRef | null { + if (target?.kind === "server") { + return target.threadRef; + } + if (target?.kind !== "draft" || !draftThread?.promotedTo) { + return null; + } + return draftThread.promotedTo; +} diff --git a/packages/client-runtime/src/operations/projects.test.ts b/packages/client-runtime/src/operations/projects.test.ts index f3bc72603a..11b4974246 100644 --- a/packages/client-runtime/src/operations/projects.test.ts +++ b/packages/client-runtime/src/operations/projects.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; import { - DEFAULT_MODEL, EnvironmentId, ProjectId, CommandId, @@ -138,10 +137,7 @@ describe("add project shared logic", () => { title: "repo", workspaceRoot: "/work/repo", createWorkspaceRootIfMissing: true, - defaultModelSelection: { - instanceId: "codex", - model: DEFAULT_MODEL, - }, + defaultModelSelection: null, }); }); }); diff --git a/packages/client-runtime/src/operations/projects.ts b/packages/client-runtime/src/operations/projects.ts index ec58418a94..6ae6e18baa 100644 --- a/packages/client-runtime/src/operations/projects.ts +++ b/packages/client-runtime/src/operations/projects.ts @@ -7,7 +7,6 @@ import type { SourceControlProviderKind, SourceControlRepositoryInfo, } from "@t3tools/contracts"; -import { DEFAULT_MODEL, ProviderInstanceId } from "@t3tools/contracts"; import * as Arr from "effect/Array"; import * as Option from "effect/Option"; import * as Order from "effect/Order"; @@ -215,10 +214,7 @@ export function buildProjectCreateCommand(input: { title: inferProjectTitleFromPath(input.workspaceRoot), workspaceRoot: input.workspaceRoot, createWorkspaceRootIfMissing: true, - defaultModelSelection: { - instanceId: ProviderInstanceId.make("codex"), - model: DEFAULT_MODEL, - }, + defaultModelSelection: null, createdAt: input.createdAt, }; } diff --git a/packages/client-runtime/src/state/threadSettled.test.ts b/packages/client-runtime/src/state/threadSettled.test.ts index 50f3c2d391..59f9f1d6f5 100644 --- a/packages/client-runtime/src/state/threadSettled.test.ts +++ b/packages/client-runtime/src/state/threadSettled.test.ts @@ -178,6 +178,51 @@ describe("effectiveSettled", () => { ).toBe(false); }); + it("keeps a new turn active from queued through starting and running", () => { + const requestedAt = "2026-04-09T12:00:00.000Z"; + const transitionNow = "2026-04-09T12:00:30.000Z"; + const base = makeShell({ + settledOverride: null, + activityAt: STALE, + }); + const queued: OrchestrationThreadShell = { + ...base, + latestUserMessageAt: requestedAt, + latestTurn: null, + session: null, + }; + const starting: OrchestrationThreadShell = { + ...queued, + session: { + threadId: queued.id, + status: "starting", + providerName: "Codex", + runtimeMode: "full-access", + activeTurnId: null, + lastError: null, + updatedAt: requestedAt, + }, + }; + const running: OrchestrationThreadShell = { + ...starting, + session: { + ...starting.session!, + status: "running", + activeTurnId: TurnId.make("turn-new"), + }, + }; + + for (const shell of [queued, starting, running]) { + expect( + effectiveSettled(shell, { + now: transitionNow, + autoSettleAfterDays: 3, + changeRequestState: "merged", + }), + ).toBe(false); + } + }); + it("uses a strict inactivity boundary and honors a null threshold", () => { const boundary = makeShell({ activityAt: "2026-04-07T00:00:00.000Z", diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index f99d0b6654..5a7c14f172 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -81,4 +81,52 @@ describe("collectComposerInlineTokens", () => { it("ignores normal web links", () => { expect(collectComposerInlineTokens("Read [docs](https://example.com) first")).toEqual([]); }); + + it.each(["@expo/ui", "@jane/foo.js", "@scope/pkg/sub/path"])( + "keeps scoped package reference %s as plain text", + (reference) => { + expect(collectComposerInlineTokens(`Install ${reference} next`)).toEqual([]); + }, + ); + + it("keeps scoped package references plain across incomplete input and IME whitespace", () => { + expect(collectComposerInlineTokens("Install @expo/ui")).toEqual([]); + expect(collectComposerInlineTokens("入力 @expo/ui を追加")).toEqual([]); + }); + + it("keeps bare non-scoped file paths as mentions", () => { + expect(collectComposerInlineTokens("Inspect @README.md next")).toEqual([ + { + type: "mention", + value: "README.md", + source: "@README.md", + start: 8, + end: 18, + }, + ]); + }); + + it("keeps canonical file links for scoped paths as mentions", () => { + expect(collectComposerInlineTokens("Inspect [sub](@scope/pkg/sub) next")).toEqual([ + { + type: "mention", + value: "@scope/pkg/sub", + source: "[sub](@scope/pkg/sub)", + start: 8, + end: 29, + }, + ]); + }); + + it("allows ambiguous scoped paths through explicit quoted mentions", () => { + expect(collectComposerInlineTokens('Inspect @"expo/ui" next')).toEqual([ + { + type: "mention", + value: "expo/ui", + source: '@"expo/ui"', + start: 8, + end: 18, + }, + ]); + }); }); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index aa5e67d6fc..dda548059d 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -23,6 +23,9 @@ const MENTION_TOKEN_REGEX = /(^|\s)@(?:"((?:\\.|[^"\\])*)"|([^\s@"]+))(?=\s)/g; const FILE_LINK_TOKEN_REGEX = /(^|\s)\[((?:\\.|[^\]\\])*)\]\(([^)\s]+)\)(?=\s)/g; const URI_SCHEME_REGEX = /^[A-Za-z][A-Za-z0-9+.-]*:/; const WINDOWS_DRIVE_PATH_REGEX = /^[A-Za-z]:[\\/]/; +// Autocomplete emits canonical file links, so ambiguous bare @scope/package text stays a package. +const SCOPED_PACKAGE_REFERENCE_REGEX = + /^[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*(?:\/[^\s@"]+)*$/; function collectMentionTokens(text: string): ComposerInlineToken[] { const matches: ComposerInlineToken[] = []; @@ -60,7 +63,7 @@ function collectMentionTokens(text: string): ComposerInlineToken[] { const prefix = match[1] ?? ""; const quotedPath = match[2]; const path = quotedPath !== undefined ? quotedPath.replace(/\\(.)/g, "$1") : (match[3] ?? ""); - if (!path) { + if (!path || (quotedPath === undefined && SCOPED_PACKAGE_REFERENCE_REGEX.test(path))) { continue; } const start = (match.index ?? 0) + prefix.length; diff --git a/packages/shared/src/git.test.ts b/packages/shared/src/git.test.ts index 80578e262f..96539f0aae 100644 --- a/packages/shared/src/git.test.ts +++ b/packages/shared/src/git.test.ts @@ -71,6 +71,29 @@ describe("isTemporaryWorktreeBranch", () => { expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/DEADBEEF`)).toBe(true); }); + it("normalizes a UUID-shaped random callback to the canonical 8-hex form", () => { + expect(buildTemporaryWorktreeBranchName(() => "f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12")).toBe( + `${WORKTREE_BRANCH_PREFIX}/f4ae4e0e`, + ); + }); + + it("matches legacy UUID-shaped temporary worktree refs from older mobile builds", () => { + expect( + isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/f4ae4e0e-f971-4d48-b4f2-9cf0aa54ab12`), + ).toBe(true); + }); + + it("rejects UUID-shaped refs that are not RFC 4122 v4", () => { + // version nibble is not 4 + expect( + isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/f4ae4e0e-f971-1d48-b4f2-9cf0aa54ab12`), + ).toBe(false); + // variant nibble is not [89ab] + expect( + isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/f4ae4e0e-f971-4d48-c4f2-9cf0aa54ab12`), + ).toBe(false); + }); + it("rejects non-temporary refName names", () => { expect(isTemporaryWorktreeBranch(`${WORKTREE_BRANCH_PREFIX}/feature/demo`)).toBe(false); expect(isTemporaryWorktreeBranch("main")).toBe(false); diff --git a/packages/shared/src/git.ts b/packages/shared/src/git.ts index ae50b14883..71fe2e806c 100644 --- a/packages/shared/src/git.ts +++ b/packages/shared/src/git.ts @@ -11,7 +11,13 @@ import * as Result from "effect/Result"; import { detectSourceControlProviderFromRemoteUrl } from "./sourceControl.ts"; export const WORKTREE_BRANCH_PREFIX = "t3code"; -const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`); +// Canonical form is `t3code/<8 hex>`. Older mobile builds generated `t3code/` +// via Crypto.randomUUID() (always RFC 4122 v4), so the matcher also accepts exactly +// that shape — version nibble `4`, variant nibble `[89ab]` — to keep those threads +// eligible for branch regeneration without loosening beyond what was ever generated. +const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp( + `^${WORKTREE_BRANCH_PREFIX}\\/(?:[0-9a-f]{8}|[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})$`, +); /** * Sanitize an arbitrary string into a valid, lowercase git refName fragment. @@ -89,7 +95,12 @@ export function deriveLocalBranchNameFromRemoteRef(branchName: string): string { export function buildTemporaryWorktreeBranchName( randomHex: (byteLength: number) => string, ): string { - const token = randomHex(4).toLowerCase(); + // Normalize to exactly 8 lowercase hex chars so a UUID-shaped callback + // still produces the canonical temporary branch form. + const token = randomHex(4) + .toLowerCase() + .replace(/[^0-9a-f]/g, "") + .slice(0, 8); return `${WORKTREE_BRANCH_PREFIX}/${token}`; }