Merge remote-tracking branch 'origin/main' into t3code/fix-lightmode-sidebar
# Conflicts: # apps/web/src/components/SidebarV2.tsx
This commit is contained in:
commit
280440660b
46 files changed
+2393
-358
No files matched your search
@@ -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";
|
||||
|
||||
@@ -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 (
|
||||
<View className="items-center pb-2">
|
||||
<Animated.View
|
||||
className="absolute inset-x-0 bottom-full items-center pb-2"
|
||||
entering={FadeInDown.duration(180)}
|
||||
exiting={FadeOutDown.duration(140)}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
@@ -250,7 +261,7 @@ const ComposerConnectionStatusPill = memo(function ComposerConnectionStatusPill(
|
||||
{props.status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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<ThreadFeedE
|
||||
}, [threadId, feed]);
|
||||
}
|
||||
|
||||
// Pre-measurement estimate for the working pill's slot (the real height is
|
||||
// measured via onComposerLayout since the pill lives inside the composer
|
||||
// overlay). Matches the rendered pill: pt-2 + pb-2 (16) wrapping a bordered
|
||||
// px-3/py-2 row (~36), so ~52 — keep it in sync with WorkingDurationPill.
|
||||
const WORKING_INDICATOR_HEIGHT = 52;
|
||||
|
||||
const WorkingDurationPill = memo(function WorkingDurationPill(props: {
|
||||
readonly startedAt: string;
|
||||
}) {
|
||||
const [nowMs, setNowMs] = useState(() => 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 (
|
||||
<Animated.View
|
||||
className="shrink-0 px-4 pb-2 pt-2"
|
||||
entering={FadeInDown.duration(200)}
|
||||
exiting={FadeOut.duration(140)}
|
||||
>
|
||||
<View
|
||||
className={
|
||||
Platform.OS === "ios" && !NATIVE_LIQUID_GLASS_SUPPORTED
|
||||
? "self-start rounded-full border border-border bg-card px-3 py-2"
|
||||
: "self-start rounded-full border border-neutral-200/80 bg-neutral-50/90 px-3 py-2 dark:border-white/[0.08] dark:bg-white/[0.04]"
|
||||
}
|
||||
>
|
||||
<View className="flex-row items-center gap-2">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1.5 w-1.5 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
</Animated.View>
|
||||
);
|
||||
});
|
||||
|
||||
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. */}
|
||||
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
|
||||
<Animated.View
|
||||
className="w-full self-center"
|
||||
layout={LinearTransition.duration(220)}
|
||||
style={{ maxWidth: contentMaxWidth }}
|
||||
>
|
||||
{props.activeWorkStartedAt ? (
|
||||
<WorkingDurationPill startedAt={props.activeWorkStartedAt} />
|
||||
) : null}
|
||||
|
||||
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
|
||||
{props.activePendingApproval || props.activePendingUserInput ? (
|
||||
<Animated.View
|
||||
className="shrink-0 gap-3 px-4 pb-3"
|
||||
@@ -473,7 +414,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
) : null}
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</Animated.View>
|
||||
</View>
|
||||
|
||||
<ThreadComposer
|
||||
editorRef={composerEditorRef}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KeyboardAwareLegendList } from "@legendapp/list/keyboard";
|
||||
import { type LegendListRef } from "@legendapp/list/react-native";
|
||||
import type { EnvironmentId, MessageId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import { CHAT_LIST_ANCHOR_OFFSET, resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
|
||||
import { formatElapsed } from "@t3tools/shared/orchestrationTiming";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { HeaderHeightContext } from "@react-navigation/elements";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
@@ -128,6 +129,7 @@ export interface ThreadFeedProps {
|
||||
readonly contentPresentation: ThreadContentPresentation;
|
||||
readonly agentLabel: string;
|
||||
readonly latestTurn: ThreadFeedLatestTurn | null;
|
||||
readonly activeWorkStartedAt: string | null;
|
||||
readonly listRef: RefObject<LegendListRef | null>;
|
||||
readonly freeze: SharedValue<boolean>;
|
||||
readonly anchorMessageId: MessageId | null;
|
||||
@@ -816,6 +818,10 @@ function renderFeedEntry(
|
||||
const entry = info.item;
|
||||
const { markdownStyles, iconSubtleColor, userBubbleColor } = props;
|
||||
|
||||
if (entry.type === "working") {
|
||||
return <WorkingTimelineRow startedAt={entry.createdAt} />;
|
||||
}
|
||||
|
||||
if (entry.type === "turn-fold") {
|
||||
return (
|
||||
<Pressable
|
||||
@@ -993,6 +999,32 @@ function renderFeedEntry(
|
||||
);
|
||||
}
|
||||
|
||||
const WorkingTimelineRow = memo(function WorkingTimelineRow(props: { readonly startedAt: string }) {
|
||||
const [nowMs, setNowMs] = useState(() => 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 (
|
||||
<View className="mb-4 flex-row items-center gap-2 px-1.5 py-1">
|
||||
<View className="flex-row items-center gap-1">
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400 dark:bg-neutral-500" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/80 dark:bg-neutral-500/80" />
|
||||
<View className="h-1 w-1 rounded-full bg-neutral-400/60 dark:bg-neutral-500/60" />
|
||||
</View>
|
||||
<Text className="font-t3-medium text-xs tabular-nums text-neutral-600 dark:text-neutral-400">
|
||||
Working for {durationLabel}
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
});
|
||||
|
||||
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) {
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
{props.feed.length === 0 && props.contentPresentation.kind === "ready" ? (
|
||||
{props.feed.length === 0 &&
|
||||
props.activeWorkStartedAt === null &&
|
||||
props.contentPresentation.kind === "ready" ? (
|
||||
<View pointerEvents="none" style={StyleSheet.absoluteFill}>
|
||||
<ThreadFeedPlaceholder
|
||||
title="No conversation yet"
|
||||
|
||||
@@ -414,6 +414,20 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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,
|
||||
|
||||
@@ -98,6 +98,11 @@ type RawThreadFeedEntry =
|
||||
|
||||
export type ThreadFeedEntry =
|
||||
| Extract<RawThreadFeedEntry, { type: "message" }>
|
||||
| {
|
||||
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<TurnId>,
|
||||
expandedWorkGroupIds: ReadonlySet<string> = 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<string>();
|
||||
@@ -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<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" }>,
|
||||
entry: Exclude<ThreadFeedEntry, { readonly type: "turn-fold" | "work-toggle" | "working" }>,
|
||||
expandedWorkGroupIds: ReadonlySet<string>,
|
||||
): void {
|
||||
if (entry.type !== "activity-group") {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<ProviderSession, ProviderAdapterRequestError>;
|
||||
}) {
|
||||
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<void>();
|
||||
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";
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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 =
|
||||
|
||||
@@ -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: "[email protected]", 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: "[email protected]",
|
||||
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<string>;
|
||||
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),
|
||||
);
|
||||
});
|
||||
@@ -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<SettingSource>;
|
||||
|
||||
/** 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<SDKUserMessage> {
|
||||
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
|
||||
|
||||
@@ -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",
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -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<ServerProvider>();
|
||||
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<void>(), (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");
|
||||
|
||||
@@ -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<ServerProvider["models"][number]>,
|
||||
nextModels: ReadonlyArray<ServerProvider["models"][number]>,
|
||||
): ReadonlyArray<ServerProvider["models"][number]> => {
|
||||
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 = (
|
||||
|
||||
@@ -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<Agent> = [];
|
||||
if (agentsResult._tag === "Success" && agentsResult.value.code === 0) {
|
||||
agents = parseAgentListCliOutput(agentsResult.value.stdout);
|
||||
|
||||
@@ -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<string>();
|
||||
|
||||
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<string | null>(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 ? (
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<CommandPaletteView[]>([]);
|
||||
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,
|
||||
|
||||
@@ -70,4 +70,83 @@ describe("registerComposerInlineTokenPaste", () => {
|
||||
"<mention:.changeset/improve-deploy-error-logging.md> ",
|
||||
);
|
||||
});
|
||||
|
||||
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(`<mention:${path}>`),
|
||||
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(`<mention:${path}>`),
|
||||
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(
|
||||
"<mention:@scope/pkg/sub> ",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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 <ProjectFaviconFallback className={input.className} />;
|
||||
return <ProjectFaviconFallback className={input.className} icon={FallbackIcon} />;
|
||||
}
|
||||
|
||||
return <ProjectFaviconImage key={src} src={src} className={input.className} />;
|
||||
return (
|
||||
<ProjectFaviconImage
|
||||
key={src}
|
||||
src={src}
|
||||
className={input.className}
|
||||
fallbackIcon={FallbackIcon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function ProjectFaviconFallback({ className }: { readonly className?: string | undefined }) {
|
||||
return <FolderIcon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />;
|
||||
function ProjectFaviconFallback({
|
||||
className,
|
||||
icon: Icon,
|
||||
}: {
|
||||
readonly className?: string | undefined;
|
||||
readonly icon: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
return <Icon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />;
|
||||
}
|
||||
|
||||
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" ? <ProjectFaviconFallback className={className} /> : null}
|
||||
{status !== "loaded" ? (
|
||||
<ProjectFaviconFallback className={className} icon={FallbackIcon} />
|
||||
) : null}
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
|
||||
@@ -118,7 +118,7 @@ import { vcsEnvironment } from "../state/vcs";
|
||||
import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
|
||||
import {
|
||||
buildThreadRouteParams,
|
||||
resolveThreadRouteRef,
|
||||
resolveActiveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "../threadRoutes";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
@@ -3068,10 +3068,17 @@ export default function Sidebar() {
|
||||
const handleNewThread = useNewThreadHandler();
|
||||
const { archiveThread, deleteThread } = useThreadActions();
|
||||
const { isMobile, setOpenMobile } = useSidebar();
|
||||
const routeThreadRef = useParams({
|
||||
const routeTarget = useParams({
|
||||
strict: false,
|
||||
select: (params) => 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
|
||||
|
||||
@@ -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 ? (
|
||||
<div aria-hidden className="mb-1 mt-3 flex items-center gap-2 px-2.5">
|
||||
<span className="text-[10px] font-medium text-muted-foreground/65">Settled</span>
|
||||
<span className="h-px flex-1 bg-border/80" />
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
@@ -429,6 +420,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
environmentId={thread.environmentId}
|
||||
cwd={props.projectCwd ?? ""}
|
||||
className="size-3.5"
|
||||
fallbackIcon={MessageSquareIcon}
|
||||
/>
|
||||
</span>
|
||||
{title}
|
||||
@@ -1531,7 +1523,7 @@ export default function SidebarV2() {
|
||||
) : null}
|
||||
<SidebarGroup className="min-h-0 flex-1 overflow-y-auto px-2 py-1">
|
||||
<ul ref={attachListAutoAnimateRef} className="flex flex-col gap-px">
|
||||
{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 = (
|
||||
<SidebarV2Row
|
||||
showSettledGap={showSettledGap}
|
||||
key={threadKey}
|
||||
// Keyed per variant on purpose: when a thread settles, the
|
||||
// card fades out in place and the slim row fades in at its
|
||||
// settled position instead of one element FLIP-sliding
|
||||
// through every row in between (rows here are translucent,
|
||||
// so a crossing row reads as text painted over text).
|
||||
key={`${threadKey}:${isCard ? "card" : "slim"}`}
|
||||
thread={thread}
|
||||
variant={isCard ? "card" : "slim"}
|
||||
// Every settled row can un-settle: explicit settles clear
|
||||
@@ -1584,6 +1580,28 @@ export default function SidebarV2() {
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
/>
|
||||
);
|
||||
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 [
|
||||
<li
|
||||
key="settled-divider"
|
||||
aria-hidden
|
||||
data-thread-selection-safe
|
||||
className="list-none"
|
||||
>
|
||||
<div className="mb-1 mt-3 flex items-center gap-2 px-2.5">
|
||||
<span className="text-[10px] font-medium text-muted-foreground/50">
|
||||
Settled
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border/60" />
|
||||
</div>
|
||||
</li>,
|
||||
row,
|
||||
];
|
||||
})}
|
||||
{hiddenSettledCount > 0 ? (
|
||||
<li className="list-none">
|
||||
|
||||
@@ -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<ServerProvider["models"][number]>;
|
||||
@@ -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...")}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
@@ -2501,9 +2523,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
? `${environmentUnavailable.label}: ${connectionStatusText(
|
||||
environmentUnavailable.connection,
|
||||
)}`
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
: noProviderAvailable
|
||||
? "Enable a provider in Settings to send a message"
|
||||
: phase === "disconnected"
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, $use skills, or / for commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState || projectSelectionRequired}
|
||||
/>
|
||||
@@ -2521,7 +2545,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}
|
||||
@@ -2556,28 +2582,43 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
)}
|
||||
>
|
||||
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
activeInstanceId={selectedInstanceId}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
lockedContinuationGroupKey={lockedContinuationGroupKey}
|
||||
instanceEntries={providerInstanceEntries}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
terminalOpen={terminalOpen}
|
||||
open={isComposerModelPickerOpen}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName: composerProviderState.modelPickerIconClassName,
|
||||
}
|
||||
: {})}
|
||||
onOpenChange={(open) => {
|
||||
setIsComposerModelPickerOpen(open);
|
||||
}}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
onInstanceModelChange={onProviderModelSelect}
|
||||
/>
|
||||
{noProviderAvailable ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled
|
||||
data-chat-provider-unavailable="true"
|
||||
className="shrink-0 gap-2 px-2 text-muted-foreground/70 sm:px-3"
|
||||
>
|
||||
<CircleAlertIcon className="size-4" />
|
||||
No provider available
|
||||
</Button>
|
||||
) : (
|
||||
<ProviderModelPicker
|
||||
compact={isComposerFooterCompact}
|
||||
activeInstanceId={selectedInstanceId}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
lockedContinuationGroupKey={lockedContinuationGroupKey}
|
||||
instanceEntries={providerInstanceEntries}
|
||||
keybindings={keybindings}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
terminalOpen={terminalOpen}
|
||||
open={isComposerModelPickerOpen}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
activeProviderIconClassName:
|
||||
composerProviderState.modelPickerIconClassName,
|
||||
}
|
||||
: {})}
|
||||
onOpenChange={(open) => {
|
||||
setIsComposerModelPickerOpen(open);
|
||||
}}
|
||||
getModelDisabledReason={getModelDisabledReason}
|
||||
onInstanceModelChange={onProviderModelSelect}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isComposerFooterCompact ? (
|
||||
<CompactComposerControlsMenu
|
||||
@@ -2634,7 +2675,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
|
||||
isSendBusy={isSendBusy}
|
||||
isConnecting={isConnecting}
|
||||
isEnvironmentUnavailable={
|
||||
environmentUnavailable !== null || projectSelectionRequired
|
||||
environmentUnavailable !== null ||
|
||||
noProviderAvailable ||
|
||||
projectSelectionRequired
|
||||
}
|
||||
isPreparingWorktree={isPreparingWorktree}
|
||||
hasSendableContent={composerSendState.hasSendableContent}
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { resolveExternalWebLinkHost, showExternalLinkContextMenu } from "./externalLinkContextMenu";
|
||||
|
||||
function createHarness(selection: "open-in-preview" | "open-external" | "copy-link" | null) {
|
||||
const showContextMenu = vi.fn().mockResolvedValue(selection);
|
||||
const openInPreview = vi.fn().mockResolvedValue(undefined);
|
||||
const openExternal = vi.fn().mockResolvedValue(undefined);
|
||||
const copyLink = vi.fn().mockResolvedValue(undefined);
|
||||
const reportFailure = vi.fn();
|
||||
|
||||
return {
|
||||
showContextMenu,
|
||||
openInPreview,
|
||||
openExternal,
|
||||
copyLink,
|
||||
reportFailure,
|
||||
};
|
||||
}
|
||||
|
||||
describe("external chat link context menu", () => {
|
||||
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:[email protected]", 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);
|
||||
});
|
||||
});
|
||||
@@ -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<ExternalLinkContextMenuAction, ExternalLinkContextMenuFailureOperation>;
|
||||
|
||||
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<ExternalLinkContextMenuAction>[];
|
||||
|
||||
interface ShowExternalLinkContextMenuOptions {
|
||||
readonly href: string;
|
||||
readonly position: { readonly x: number; readonly y: number };
|
||||
readonly showContextMenu: (
|
||||
items: readonly ContextMenuItem<ExternalLinkContextMenuAction>[],
|
||||
position: { readonly x: number; readonly y: number },
|
||||
) => Promise<ExternalLinkContextMenuAction | null>;
|
||||
readonly openInPreview: (href: string) => Promise<void>;
|
||||
readonly openExternal: (href: string) => Promise<void>;
|
||||
readonly copyLink: (href: string) => Promise<unknown>;
|
||||
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<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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 });
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> | 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<string, unknown> | 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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -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.
|
||||
</DialogDescription>
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{wizardSteps.map((step, index) => (
|
||||
<button
|
||||
key={step}
|
||||
type="button"
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
|
||||
index === wizardStep
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: index < wizardStep
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
)}
|
||||
onClick={() => setWizardStep(index)}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
|
||||
index < wizardStep
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: index === wizardStep
|
||||
? "border-primary bg-background"
|
||||
: "border-muted-foreground/35 bg-background",
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
{index < wizardStep ? <CheckIcon className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span className="truncate text-xs font-semibold text-foreground">
|
||||
{step}
|
||||
{index < wizardStep && wizardStepSummaries[index]
|
||||
? `: ${wizardStepSummaries[index]}`
|
||||
: ""}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<AddProviderInstanceWizardSteps
|
||||
currentStep={wizardStep}
|
||||
summaries={wizardStepSummaries}
|
||||
instanceIdError={instanceIdError}
|
||||
onNavigation={applyWizardNavigation}
|
||||
/>
|
||||
</DialogHeader>
|
||||
|
||||
<div
|
||||
@@ -452,8 +423,8 @@ export function AddProviderInstanceDialog({ open, onOpenChange }: AddProviderIns
|
||||
>
|
||||
{wizardStep === 0 ? "Cancel" : "Back"}
|
||||
</Button>
|
||||
{wizardStep < wizardSteps.length - 1 ? (
|
||||
<Button size="sm" onClick={() => setWizardStep((step) => Math.min(2, step + 1))}>
|
||||
{wizardStep < ADD_PROVIDER_WIZARD_STEPS.length - 1 ? (
|
||||
<Button size="sm" onClick={() => navigateToStep(wizardStep + 1)}>
|
||||
Next
|
||||
</Button>
|
||||
) : (
|
||||
|
||||
@@ -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<typeof AddProviderInstanceWizardSteps>[0]["onNavigation"],
|
||||
): ReactElement<StepButtonProps>[] {
|
||||
const header = AddProviderInstanceWizardSteps({
|
||||
currentStep,
|
||||
summaries: ["Codex", "Codex Workspace", null],
|
||||
instanceIdError,
|
||||
onNavigation,
|
||||
});
|
||||
|
||||
return Children.toArray(header.props.children).filter(
|
||||
(child): child is ReactElement<StepButtonProps> => 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 });
|
||||
});
|
||||
});
|
||||
@@ -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 (
|
||||
<div className="grid grid-cols-3 gap-2">
|
||||
{ADD_PROVIDER_WIZARD_STEPS.map((step, index) => (
|
||||
<button
|
||||
key={step}
|
||||
type="button"
|
||||
className={cn(
|
||||
"grid min-w-0 grid-cols-[1rem_minmax(0,1fr)] gap-x-2 rounded-lg border px-3 py-2 text-left",
|
||||
index === currentStep
|
||||
? "border-primary bg-primary/10 ring-1 ring-primary/25"
|
||||
: index < currentStep
|
||||
? "border-border bg-background"
|
||||
: "border-border bg-muted/40",
|
||||
)}
|
||||
aria-current={index === currentStep ? "step" : undefined}
|
||||
onClick={() =>
|
||||
onNavigation(
|
||||
resolveWizardNavigation(currentStep, index, ADD_PROVIDER_WIZARD_STEPS.length, {
|
||||
instanceIdError,
|
||||
}),
|
||||
)
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={cn(
|
||||
"row-span-2 mt-0.5 grid size-4 place-items-center rounded-full border",
|
||||
index < currentStep
|
||||
? "border-primary bg-primary text-primary-foreground"
|
||||
: index === currentStep
|
||||
? "border-primary bg-background"
|
||||
: "border-muted-foreground/35 bg-background",
|
||||
)}
|
||||
aria-hidden
|
||||
>
|
||||
{index < currentStep ? <CheckIcon className="size-3" /> : null}
|
||||
</span>
|
||||
<span className="text-[10px] font-medium uppercase text-muted-foreground">
|
||||
Step {index + 1}
|
||||
</span>
|
||||
<span className="truncate text-xs font-semibold text-foreground">
|
||||
{step}
|
||||
{index < currentStep && summaries[index] ? `: ${summaries[index]}` : ""}
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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<ServerProvider>,
|
||||
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<ProviderInstanceEntry>,
|
||||
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<ServerProvider>,
|
||||
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<ServerProvider>,
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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/<uuid>`
|
||||
// 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}`;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user