Merge latest origin/main into orchestrator v2
Resolve the orchestrator-v2 integration conflicts while preserving the latest MCP liveness, source-control writer, editor discovery, and V2 client behavior. Co-authored-by: codex <[email protected]>
This commit is contained in:
commit
fe1c7a7549
123 files changed
+3994
-927
No files matched your search
@@ -864,6 +864,7 @@ jobs:
|
||||
echo "Deploying hosted web app for $channel_name channel."
|
||||
deployment_url="$(
|
||||
vp dlx [email protected] deploy \
|
||||
--archive=tgz \
|
||||
--prod \
|
||||
--skip-domain \
|
||||
--yes \
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
|
||||
@@ -22,9 +22,17 @@ import * as BrowserSession from "./BrowserSession.ts";
|
||||
import * as PreviewManager from "./Manager.ts";
|
||||
|
||||
describe("fitPictureInPictureContentSize", () => {
|
||||
it("fits landscape and portrait viewports without letterboxing the window", () => {
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([480, 270]);
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 9 / 16)).toEqual([240, 427]);
|
||||
it("preserves the PiP content area across aspect-ratio changes", () => {
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 16 / 9)).toEqual([523, 294]);
|
||||
expect(PreviewManager.fitPictureInPictureContentSize([480, 320], 9 / 16)).toEqual([294, 523]);
|
||||
});
|
||||
|
||||
it("does not collapse toward the minimum size when orientation changes repeatedly", () => {
|
||||
const portrait = PreviewManager.fitPictureInPictureContentSize([523, 294], 9 / 16);
|
||||
const landscape = PreviewManager.fitPictureInPictureContentSize(portrait, 16 / 9);
|
||||
|
||||
expect(portrait).toEqual([294, 523]);
|
||||
expect(landscape).toEqual([523, 294]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1065,7 +1073,7 @@ describe("PreviewManager", () => {
|
||||
skipTransformProcessType: true,
|
||||
});
|
||||
expect(pictureInPictureWindow.setAspectRatio.mock.calls).toEqual([[0], [1280 / 720]]);
|
||||
expect(pictureInPictureWindow.setContentSize).toHaveBeenCalledWith(480, 270, false);
|
||||
expect(pictureInPictureWindow.setContentSize).toHaveBeenCalledWith(523, 294, false);
|
||||
expect(pictureInPictureWindow.setAspectRatio.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
pictureInPictureWindow.setContentSize.mock.invocationCallOrder[0] ?? 0,
|
||||
);
|
||||
|
||||
@@ -104,6 +104,7 @@ const PICTURE_IN_PICTURE_INITIAL_WIDTH = 480;
|
||||
const PICTURE_IN_PICTURE_INITIAL_HEIGHT = 320;
|
||||
const PICTURE_IN_PICTURE_MIN_WIDTH = 240;
|
||||
const PICTURE_IN_PICTURE_MIN_HEIGHT = 160;
|
||||
const PICTURE_IN_PICTURE_ASPECT_RATIO_EPSILON = 0.002;
|
||||
const DIAGNOSTIC_BUFFER_LIMIT = 200;
|
||||
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
|
||||
const AGENT_CURSOR_MOVE_MS = 160;
|
||||
@@ -164,8 +165,8 @@ export const fitPictureInPictureContentSize = (
|
||||
): readonly [width: number, height: number] => {
|
||||
const currentWidth = Math.max(1, current[0] ?? PICTURE_IN_PICTURE_INITIAL_WIDTH);
|
||||
const currentHeight = Math.max(1, current[1] ?? PICTURE_IN_PICTURE_INITIAL_HEIGHT);
|
||||
let width =
|
||||
currentWidth / currentHeight > aspectRatio ? currentHeight * aspectRatio : currentWidth;
|
||||
const currentArea = currentWidth * currentHeight;
|
||||
let width = Math.sqrt(currentArea * aspectRatio);
|
||||
let height = width / aspectRatio;
|
||||
const minimumScale = Math.max(
|
||||
1,
|
||||
@@ -2074,7 +2075,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
|
||||
tabId,
|
||||
);
|
||||
const aspectRatio = frame.width / frame.height;
|
||||
if (previousAspectRatio !== aspectRatio) {
|
||||
if (
|
||||
previousAspectRatio === undefined ||
|
||||
Math.abs(previousAspectRatio - aspectRatio) > PICTURE_IN_PICTURE_ASPECT_RATIO_EPSILON
|
||||
) {
|
||||
yield* attempt(
|
||||
{
|
||||
operation: "pictureInPicture.setAspectRatio",
|
||||
|
||||
@@ -30,6 +30,7 @@ const clientSettings: ClientSettings = {
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
sidebarThreadPreviewCount: 6,
|
||||
sidebarV2Enabled: false,
|
||||
sidebarV2ConfiguredByUser: false,
|
||||
timestampFormat: "24-hour",
|
||||
wordWrap: true,
|
||||
};
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import type { EnvironmentId, SidebarThreadSortOrder } from "@t3tools/contracts";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useCallback, useMemo, useRef } from "react";
|
||||
import { Platform, Pressable, Text as RNText, TextInput, View } from "react-native";
|
||||
@@ -12,7 +10,7 @@ import { ControlPillMenu } from "../../components/ControlPill";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { T3Wordmark } from "../../components/T3Wordmark";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useHardwareKeyboardCommand } from "../keyboard/hardwareKeyboardCommands";
|
||||
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
|
||||
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
|
||||
@@ -59,21 +57,14 @@ function checkedMenuState(checked: boolean) {
|
||||
return checked ? ("on" as const) : undefined;
|
||||
}
|
||||
|
||||
/** Thread List v2 lays the list out in fixed creation order, so the
|
||||
sort/group filter controls would be silently ignored — hide them and
|
||||
key the "customized" icon state off the environment filter alone. */
|
||||
function useThreadListV2FilterGate() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
return (
|
||||
AsyncResult.isSuccess(preferencesResult) && preferencesResult.value.threadListV2Enabled === true
|
||||
);
|
||||
}
|
||||
|
||||
function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
const insets = useSafeAreaInsets();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
@@ -291,7 +282,10 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
function IosHomeHeader(props: HomeHeaderProps) {
|
||||
const searchBarRef = useRef<SearchBarCommands>(null);
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const threadListV2Enabled = useThreadListV2FilterGate();
|
||||
// Thread List v2 lays the list out in fixed creation order, so the
|
||||
// sort/group filter controls would be silently ignored — hide them and
|
||||
// key the "customized" icon state off the environment filter alone.
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const hasCustomListOptions = threadListV2Enabled
|
||||
? props.selectedEnvironmentId !== null || props.selectedProjectKey !== null
|
||||
: hasCustomHomeListOptions(props);
|
||||
|
||||
@@ -27,6 +27,7 @@ import type { SavedRemoteConnection } from "../../lib/connection";
|
||||
import { scopedProjectKey } from "../../lib/scopedEntities";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import {
|
||||
@@ -181,9 +182,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
ReadonlyMap<string, HomeGroupDisplayState>
|
||||
>(() => new Map());
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
|
||||
const listRef = useRef<LegendListRef | null>(null);
|
||||
|
||||
@@ -8,11 +8,20 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import * as Effect from "effect/Effect";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from "react";
|
||||
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
|
||||
import {
|
||||
ActivityIndicator,
|
||||
Alert,
|
||||
Linking,
|
||||
Platform,
|
||||
Pressable,
|
||||
ScrollView,
|
||||
View,
|
||||
} from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import {
|
||||
type AtomCommandResult,
|
||||
isAtomCommandInterrupted,
|
||||
reportAtomCommandResult,
|
||||
settleAsyncResult,
|
||||
@@ -37,6 +46,7 @@ import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
|
||||
import { runtime } from "../../lib/runtime";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
|
||||
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
|
||||
import { SettingsRow } from "./components/SettingsRow";
|
||||
import { SettingsSection } from "./components/SettingsSection";
|
||||
@@ -546,11 +556,8 @@ function GeneralSettingsSection() {
|
||||
* the counterpart of web's Settings → Beta backed by mobile preferences.
|
||||
*/
|
||||
function BetaSettingsSection() {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
|
||||
const threadListV2Enabled = AsyncResult.isSuccess(preferencesResult)
|
||||
? preferencesResult.value.threadListV2Enabled === true
|
||||
: false;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
|
||||
return (
|
||||
<View className="gap-3">
|
||||
@@ -570,8 +577,12 @@ function BetaSettingsSection() {
|
||||
);
|
||||
}
|
||||
|
||||
type UpdateCheckState = "idle" | "checking" | "downloading" | "restarting" | "current";
|
||||
|
||||
function AppSettingsSection() {
|
||||
const icon = useThemeColor("--color-icon");
|
||||
const [updateState, setUpdateState] = useState<UpdateCheckState>("idle");
|
||||
const updateInFlight = useRef(false);
|
||||
|
||||
const version = Constants.expoConfig?.version ?? "0.0.0";
|
||||
// Fall back to "production" to match resolveAppVariant in app.config.ts, so a
|
||||
@@ -590,30 +601,140 @@ function AppSettingsSection() {
|
||||
: null
|
||||
: null;
|
||||
|
||||
const busy =
|
||||
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
|
||||
|
||||
// "Up to date" is a transient acknowledgement, not a state worth persisting —
|
||||
// drop back to the bundle label so the row keeps answering "what am I running?".
|
||||
useEffect(() => {
|
||||
if (updateState !== "current") return;
|
||||
const timer = setTimeout(() => setUpdateState("idle"), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [updateState]);
|
||||
|
||||
const checkForUpdate = useCallback(async () => {
|
||||
// `disabled={busy}` only takes effect on the next render, so two taps in the
|
||||
// same frame would both get through. The ref closes that window.
|
||||
if (updateInFlight.current) return;
|
||||
updateInFlight.current = true;
|
||||
try {
|
||||
await runUpdateCheck(setUpdateState);
|
||||
} finally {
|
||||
updateInFlight.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const statusLabel =
|
||||
updateState === "checking"
|
||||
? "Checking…"
|
||||
: updateState === "downloading"
|
||||
? "Downloading…"
|
||||
: updateState === "restarting"
|
||||
? "Restarting…"
|
||||
: updateState === "current"
|
||||
? "Up to date"
|
||||
: bundleLabel;
|
||||
|
||||
const versionRow = (
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
size={22}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{statusLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{statusLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
{Updates.isEnabled ? (
|
||||
<View className="w-[22px] items-center">
|
||||
{busy ? (
|
||||
<ActivityIndicator color={icon} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={18}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="semibold"
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="App">
|
||||
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
|
||||
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
|
||||
<View className="flex-row items-center gap-4 p-4">
|
||||
<SymbolView
|
||||
name="info.circle"
|
||||
size={22}
|
||||
tintColor={icon}
|
||||
type="monochrome"
|
||||
weight="regular"
|
||||
/>
|
||||
<Text className="flex-1 text-lg text-foreground">Version</Text>
|
||||
<View className="items-end">
|
||||
<Text className="text-lg text-foreground-muted">{versionLabel}</Text>
|
||||
{bundleLabel ? (
|
||||
<Text className="text-xs text-foreground-muted/70">{bundleLabel}</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
{Updates.isEnabled ? (
|
||||
<Pressable
|
||||
accessibilityLabel="Check for updates"
|
||||
accessibilityRole="button"
|
||||
disabled={busy}
|
||||
onPress={() => void checkForUpdate()}
|
||||
>
|
||||
{versionRow}
|
||||
</Pressable>
|
||||
) : (
|
||||
versionRow
|
||||
)}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
async function runUpdateCheck(setUpdateState: (state: UpdateCheckState) => void): Promise<void> {
|
||||
setUpdateState("checking");
|
||||
const check = await settlePromise(() => Updates.checkForUpdateAsync());
|
||||
if (check._tag === "Failure") {
|
||||
reportUpdateFailure(check, "Could not check for updates.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// A rollback directive (`eas update:rollback`) arrives as isAvailable: false
|
||||
// with isRollBackToEmbedded: true — there is nothing newer to install, but the
|
||||
// running OTA still has to be dropped for the embedded bundle.
|
||||
if (!check.value.isAvailable && !check.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("downloading");
|
||||
const fetched = await settlePromise(() => Updates.fetchUpdateAsync());
|
||||
if (fetched._tag === "Failure") {
|
||||
reportUpdateFailure(fetched, "Could not download the update.");
|
||||
setUpdateState("idle");
|
||||
return;
|
||||
}
|
||||
// isNew is always false for a rollback, so it can't be the sole gate here either.
|
||||
if (!fetched.value.isNew && !fetched.value.isRollBackToEmbedded) {
|
||||
setUpdateState("current");
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState("restarting");
|
||||
// reloadAsync never resolves on success — the JS context is torn down — so
|
||||
// reaching the failure branch below is the only way this returns.
|
||||
const reloaded = await settlePromise(() => Updates.reloadAsync());
|
||||
if (reloaded._tag === "Failure") {
|
||||
reportUpdateFailure(reloaded, "Downloaded, but could not restart the app.");
|
||||
setUpdateState("idle");
|
||||
}
|
||||
}
|
||||
|
||||
function reportUpdateFailure(result: AtomCommandResult<unknown, unknown>, fallback: string): void {
|
||||
reportAtomCommandResult(result, { label: "app update check" });
|
||||
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
|
||||
const error = squashAtomCommandFailure(result);
|
||||
Alert.alert("Update failed", error instanceof Error ? error.message : fallback);
|
||||
}
|
||||
|
||||
function capitalize(value: string): string {
|
||||
return value.length > 0 ? value.charAt(0).toUpperCase() + value.slice(1) : value;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import type {
|
||||
import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
@@ -25,7 +24,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { usePendingNewTasks, type PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
@@ -196,10 +195,7 @@ function ThreadNavigationSidebarPane(
|
||||
const sidebarScrollGesture = useMemo(() => Gesture.Native(), []);
|
||||
const { archiveThread, confirmDeleteThread, settleThread, unsettleThread } =
|
||||
useThreadListActions();
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const threadListV2Enabled =
|
||||
AsyncResult.isSuccess(preferencesResult) &&
|
||||
preferencesResult.value.threadListV2Enabled === true;
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
|
||||
const environments = useMemo(
|
||||
|
||||
@@ -5,6 +5,7 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
import { makeThreadShellFixture } from "../../test-fixtures";
|
||||
import {
|
||||
buildThreadListV2Items,
|
||||
resolveThreadListV2Enabled,
|
||||
resolveThreadListV2Status,
|
||||
sortThreadsForListV2,
|
||||
} from "./threadListV2";
|
||||
@@ -22,6 +23,47 @@ function makeThread(
|
||||
|
||||
const NOW = "2026-06-02T00:00:00.000Z";
|
||||
|
||||
describe("resolveThreadListV2Enabled", () => {
|
||||
it.each(["development", "preview"])("defaults on for the %s variant", (appVariant) => {
|
||||
expect(
|
||||
resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true, appVariant }),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["production", undefined])("defaults off for the %s variant", (appVariant) => {
|
||||
expect(
|
||||
resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true, appVariant }),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("prefers an explicit device choice over the variant default", () => {
|
||||
expect(
|
||||
resolveThreadListV2Enabled({
|
||||
preference: false,
|
||||
preferencesLoaded: true,
|
||||
appVariant: "preview",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
resolveThreadListV2Enabled({
|
||||
preference: true,
|
||||
preferencesLoaded: true,
|
||||
appVariant: "production",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("holds v1 while preferences are still loading so the list does not remount", () => {
|
||||
expect(
|
||||
resolveThreadListV2Enabled({
|
||||
preference: undefined,
|
||||
preferencesLoaded: false,
|
||||
appVariant: "development",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadListV2Status", () => {
|
||||
it("prioritizes approval over a running runtime", () => {
|
||||
const thread = makeThread({
|
||||
|
||||
@@ -18,6 +18,37 @@ export type ThreadListV2Status = "approval" | "input" | "working" | "failed" | "
|
||||
export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
|
||||
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
|
||||
|
||||
/**
|
||||
* Whether Thread List v2 is on by default for an app variant. The `development`
|
||||
* and `preview` variants are mobile's nightly equivalents and opt in;
|
||||
* `production` stays on v1. Counterpart of web's `resolveSidebarV2Default`.
|
||||
*/
|
||||
export function resolveThreadListV2Default(appVariant: unknown): boolean {
|
||||
return appVariant === "development" || appVariant === "preview";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved Thread List v2 state: the device-local preference if the user has
|
||||
* set one, otherwise the default for this app variant. Preferences persist as
|
||||
* sparse patches, so `undefined` genuinely means "never chosen".
|
||||
*
|
||||
* `preferencesLoaded` guards the startup window: preferences load
|
||||
* asynchronously, and treating "still loading" as "never chosen" would mount
|
||||
* v2 on a development build and then flip to v1 once a stored opt-out arrives,
|
||||
* remounting the whole list. While loading, hold v1 — the state both variants
|
||||
* already start from.
|
||||
*/
|
||||
export function resolveThreadListV2Enabled(input: {
|
||||
readonly preference: boolean | undefined;
|
||||
readonly preferencesLoaded: boolean;
|
||||
readonly appVariant: unknown;
|
||||
}): boolean {
|
||||
if (!input.preferencesLoaded) {
|
||||
return false;
|
||||
}
|
||||
return input.preference ?? resolveThreadListV2Default(input.appVariant);
|
||||
}
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "runtime">,
|
||||
): ThreadListV2Status {
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { AsyncResult } from "effect/unstable/reactivity";
|
||||
import Constants from "expo-constants";
|
||||
|
||||
import { mobilePreferencesAtom } from "../../state/preferences";
|
||||
import { resolveThreadListV2Enabled } from "./threadListV2";
|
||||
|
||||
/**
|
||||
* Resolved Thread List v2 state: the device-local preference if the user has
|
||||
* set one, otherwise the default for this app variant (on for development and
|
||||
* preview, off for production). Every consumer must read through this rather
|
||||
* than the raw preference, which is undefined until explicitly chosen.
|
||||
*
|
||||
* Kept out of `state/preferences.ts` so that module stays importable from node
|
||||
* test environments, which have no `__DEV__` for expo-constants.
|
||||
*/
|
||||
export function useThreadListV2Enabled(): boolean {
|
||||
const preferencesResult = useAtomValue(mobilePreferencesAtom);
|
||||
const loaded = AsyncResult.isSuccess(preferencesResult);
|
||||
return resolveThreadListV2Enabled({
|
||||
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
|
||||
preferencesLoaded: loaded,
|
||||
appVariant: Constants.expoConfig?.extra?.appVariant,
|
||||
});
|
||||
}
|
||||
@@ -26,7 +26,8 @@ export interface Preferences {
|
||||
/**
|
||||
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
|
||||
* client-settings sync, so the flat v2 thread list is opted into per
|
||||
* device.
|
||||
* device. Undefined means the user has never chosen, in which case the app
|
||||
* variant decides — see `resolveThreadListV2Enabled`.
|
||||
*/
|
||||
readonly threadListV2Enabled?: boolean;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -16,11 +16,16 @@ import { expect } from "vite-plus/test";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
ModelSelection,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitCommandError, TextGenerationError } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
GitCommandError,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
TextGenerationError,
|
||||
} from "@t3tools/contracts";
|
||||
import * as GitHubCli from "../sourceControl/GitHubCli.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
@@ -29,6 +34,7 @@ import * as GitHubSourceControlProvider from "../sourceControl/GitHubSourceContr
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
|
||||
@@ -65,38 +71,7 @@ function fakeGhOutput(stdout: string): VcsProcess.VcsProcessOutput {
|
||||
};
|
||||
}
|
||||
|
||||
interface FakeGitTextGeneration {
|
||||
generateCommitMessage: (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch?: boolean;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
headBranch: string;
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string; body: string }, TextGenerationError>;
|
||||
generateBranchName: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ branch: string }, TextGenerationError>;
|
||||
generateThreadTitle: (input: {
|
||||
cwd: string;
|
||||
message: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) => Effect.Effect<{ title: string }, TextGenerationError>;
|
||||
}
|
||||
type FakeGitTextGeneration = TextGeneration.TextGeneration["Service"];
|
||||
|
||||
type FakePullRequest = NonNullable<FakeGhScenario["pullRequest"]>;
|
||||
|
||||
@@ -640,6 +615,7 @@ function preparePullRequestThread(
|
||||
function makeManager(input?: {
|
||||
ghScenario?: FakeGhScenario;
|
||||
textGeneration?: Partial<FakeGitTextGeneration>;
|
||||
serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||
setupScriptRunner?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"];
|
||||
}) {
|
||||
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
|
||||
@@ -648,7 +624,7 @@ function makeManager(input?: {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest();
|
||||
const serverSettingsLayer = ServerSettings.ServerSettingsService.layerTest(input?.serverSettings);
|
||||
|
||||
const vcsDriverLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
@@ -672,6 +648,9 @@ function makeManager(input?: {
|
||||
|
||||
const managerLayer = Layer.mergeAll(
|
||||
Layer.succeed(TextGeneration.TextGeneration, textGeneration),
|
||||
Layer.mock(ProviderRegistry.ProviderRegistry)({
|
||||
getProviders: Effect.succeed([]),
|
||||
}),
|
||||
Layer.succeed(
|
||||
ProjectSetupScriptRunner.ProjectSetupScriptRunner,
|
||||
input?.setupScriptRunner ?? {
|
||||
@@ -1568,8 +1547,22 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Use a direct tone.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Implement stacked git actions", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
@@ -1579,6 +1572,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
expect(generatedPolicy).toMatchObject({ commitInstructions: "Use a direct tone." });
|
||||
expect(result.toast).toMatchObject({
|
||||
description: "Implement stacked git actions",
|
||||
cta: {
|
||||
@@ -1598,6 +1592,118 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves custom style when instructions are empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Preserve custom style", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "custom",
|
||||
inferRepositoryConventions: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back when the dedicated source control writer is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\nworld\n");
|
||||
const missingInstanceId = ProviderInstanceId.make("missing_writer");
|
||||
let generatedModelSelection:
|
||||
| TextGeneration.CommitMessageGenerationInput["modelSelection"]
|
||||
| undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
providerInstances: {
|
||||
[missingInstanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: missingInstanceId,
|
||||
model: "missing-model",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedModelSelection = input.modelSelection;
|
||||
return Effect.succeed({ subject: "Use the available writer", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedModelSelection).toEqual(DEFAULT_SERVER_SETTINGS.textGenerationModelSelection);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves repository conventions style when recent history is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* runGit(repoDir, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(repoDir, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(repoDir, ["config", "user.name", "Test User"]);
|
||||
NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "hello\n");
|
||||
yield* runGit(repoDir, ["add", "README.md"]);
|
||||
let generatedPolicy: TextGeneration.CommitMessageGenerationInput["policy"] = undefined;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "repo_conventions" as const,
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
return Effect.succeed({ subject: "Create initial commit", body: "" });
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(generatedPolicy).toEqual({
|
||||
kind: "repo_conventions",
|
||||
commitInstructions:
|
||||
"Follow the repository's established commit message style when examples are available.",
|
||||
changeRequestInstructions:
|
||||
"Follow the repository's established change request title and body style when examples are available.",
|
||||
inferRepositoryConventions: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses custom commit message when provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -2535,6 +2641,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
NodeFS.mkdirSync(NodePath.join(repoDir, ".github"));
|
||||
NodeFS.writeFileSync(
|
||||
NodePath.join(repoDir, ".github", "pull_request_template.md"),
|
||||
"## What changed?\n\n## Verification",
|
||||
);
|
||||
yield* runGit(repoDir, ["add", ".github/pull_request_template.md"]);
|
||||
yield* runGit(repoDir, ["commit", "-m", "Add pull request template"]);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature-create-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
@@ -2543,8 +2656,26 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
yield* runGit(repoDir, ["commit", "-m", "Feature commit"]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature-create-pr"]);
|
||||
yield* runGit(repoDir, ["config", "branch.feature-create-pr.gh-merge-base", "main"]);
|
||||
let generatedPolicy: TextGeneration.PrContentGenerationInput["policy"] = undefined;
|
||||
let generatedChangeRequestTemplate: string | undefined;
|
||||
|
||||
const { manager, ghCalls } = yield* makeManager({
|
||||
serverSettings: {
|
||||
sourceControlWritingStyle: {
|
||||
mode: "custom" as const,
|
||||
customInstructions: "Lead with user impact.",
|
||||
},
|
||||
},
|
||||
textGeneration: {
|
||||
generatePrContent: (input) => {
|
||||
generatedPolicy = input.policy;
|
||||
generatedChangeRequestTemplate = input.changeRequestTemplate;
|
||||
return Effect.succeed({
|
||||
title: "Add stacked git actions",
|
||||
body: "## What changed?\nAdded stacked git actions.",
|
||||
});
|
||||
},
|
||||
},
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
"[]",
|
||||
@@ -2569,6 +2700,10 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(generatedPolicy).toMatchObject({
|
||||
changeRequestInstructions: "Lead with user impact.",
|
||||
});
|
||||
expect(generatedChangeRequestTemplate).toBe("## What changed?\n\n## Verification");
|
||||
expect(ghCalls.filter((call) => call.startsWith("pr list "))).toHaveLength(2);
|
||||
expect(
|
||||
ghCalls.some((call) => call.includes("pr create --base main --head feature-create-pr")),
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
type VcsStatusRemoteResult,
|
||||
VcsStatusResult,
|
||||
ModelSelection,
|
||||
type SourceControlWritingStyleSettings,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
detectSourceControlProviderFromGitRemoteUrl,
|
||||
@@ -44,12 +45,19 @@ import {
|
||||
|
||||
import { GitManagerError, GitPullRequestMaterializationError } from "@t3tools/contracts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import {
|
||||
conventionalCommitsTextGenerationPolicy,
|
||||
customTextGenerationPolicy,
|
||||
repositoryConventionsTextGenerationPolicy,
|
||||
} from "../textGeneration/TextGenerationPresets.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "./remoteRefs.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts";
|
||||
import { detectPrTemplate } from "../sourceControl/PrTemplateDetection.ts";
|
||||
import type { ChangeRequest } from "@t3tools/contracts";
|
||||
|
||||
export interface GitActionProgressReporter {
|
||||
@@ -61,6 +69,11 @@ export interface GitRunStackedActionOptions {
|
||||
readonly progressReporter?: GitActionProgressReporter;
|
||||
}
|
||||
|
||||
interface SourceControlTextGenerationSettings {
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly style: SourceControlWritingStyleSettings;
|
||||
}
|
||||
|
||||
export class GitManager extends Context.Service<
|
||||
GitManager,
|
||||
{
|
||||
@@ -565,11 +578,58 @@ export const make = Effect.gen(function* () {
|
||||
const gitCore = yield* GitVcsDriver.GitVcsDriver;
|
||||
const sourceControlProviders = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const projectSetupScriptRunner = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
const sourceControlProvider = (cwd: string) => sourceControlProviders.resolve({ cwd });
|
||||
const serverSettingsService = yield* ServerSettings.ServerSettingsService;
|
||||
|
||||
const readRecentCommitSubjects = (cwd: string) =>
|
||||
gitCore
|
||||
.execute({
|
||||
operation: "GitManager.readRecentCommitSubjects",
|
||||
cwd,
|
||||
args: ["log", "-n", "20", "--no-merges", "--pretty=format:%s"],
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) =>
|
||||
result.stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
Effect.orElseSucceed(() => []),
|
||||
);
|
||||
|
||||
const resolveStylePolicy = (cwd: string, style: SourceControlWritingStyleSettings) =>
|
||||
Effect.gen(function* () {
|
||||
switch (style.mode) {
|
||||
case "conventional_commits":
|
||||
return conventionalCommitsTextGenerationPolicy;
|
||||
case "custom":
|
||||
return customTextGenerationPolicy(
|
||||
style.customInstructions
|
||||
? {
|
||||
commitInstructions: style.customInstructions,
|
||||
changeRequestInstructions: style.customInstructions,
|
||||
}
|
||||
: {},
|
||||
);
|
||||
case "repo_conventions": {
|
||||
const subjects = yield* readRecentCommitSubjects(cwd);
|
||||
if (subjects.length === 0) {
|
||||
return repositoryConventionsTextGenerationPolicy;
|
||||
}
|
||||
const examples = ["Recent commit subjects from this repository:", ...subjects].join("\n");
|
||||
return {
|
||||
...repositoryConventionsTextGenerationPolicy,
|
||||
commitInstructions: `${repositoryConventionsTextGenerationPolicy.commitInstructions}\n\n${examples}`,
|
||||
changeRequestInstructions: `${repositoryConventionsTextGenerationPolicy.changeRequestInstructions}\n\n${examples}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
const randomUUIDv4 = (cwd: string) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
@@ -1330,7 +1390,7 @@ export const make = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
modelSelection: ModelSelection;
|
||||
settings: SourceControlTextGenerationSettings;
|
||||
}) {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
if (!context) {
|
||||
@@ -1349,6 +1409,8 @@ export const make = Effect.gen(function* () {
|
||||
};
|
||||
}
|
||||
|
||||
const policy = yield* resolveStylePolicy(input.cwd, input.settings.style);
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
@@ -1356,7 +1418,8 @@ export const make = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
modelSelection: input.modelSelection,
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: input.settings.modelSelection,
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -1370,7 +1433,7 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const runCommitStep = Effect.fn("runCommitStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
action: "commit" | "commit_push" | "commit_push_pr",
|
||||
branch: string | null,
|
||||
@@ -1405,7 +1468,7 @@ export const make = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
@@ -1483,7 +1546,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runPrStep = Effect.fn("runPrStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
fallbackBranch: string | null,
|
||||
emit: GitActionProgressEmitter,
|
||||
@@ -1532,6 +1595,11 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
const baseRangeRef = yield* resolveBaseRangeRef(cwd, baseBranch);
|
||||
const rangeContext = yield* gitCore.readRangeContext(cwd, baseRangeRef);
|
||||
const policy = yield* resolveStylePolicy(cwd, settings.style);
|
||||
const changeRequestTemplate =
|
||||
settings.style.followChangeRequestTemplates && provider.kind === "github"
|
||||
? Option.getOrUndefined(yield* detectPrTemplate(cwd, baseRangeRef, gitCore.execute))
|
||||
: undefined;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd,
|
||||
@@ -1540,7 +1608,9 @@ export const make = Effect.gen(function* () {
|
||||
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
|
||||
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
|
||||
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
|
||||
modelSelection,
|
||||
...(changeRequestTemplate ? { changeRequestTemplate } : {}),
|
||||
...(policy ? { policy } : {}),
|
||||
modelSelection: settings.modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(
|
||||
@@ -1820,7 +1890,7 @@ export const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = Effect.fn("runFeatureBranchStep")(function* (
|
||||
modelSelection: ModelSelection,
|
||||
settings: SourceControlTextGenerationSettings,
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
@@ -1832,7 +1902,7 @@ export const make = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
modelSelection,
|
||||
settings,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* new GitManagerError({
|
||||
@@ -1921,8 +1991,23 @@ export const make = Effect.gen(function* () {
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
const modelSelection = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.textGenerationModelSelection),
|
||||
const textGenerationSettings = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.flatMap((settings) =>
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? Effect.succeed({
|
||||
modelSelection: settings.textGenerationModelSelection,
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})
|
||||
: providerRegistry.getProviders.pipe(
|
||||
Effect.map((providers) => ({
|
||||
modelSelection: ServerSettings.resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
providers,
|
||||
),
|
||||
style: settings.sourceControlWritingStyle,
|
||||
})),
|
||||
),
|
||||
),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new GitManagerError({
|
||||
@@ -1942,7 +2027,7 @@ export const make = Effect.gen(function* () {
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
@@ -1968,7 +2053,7 @@ export const make = Effect.gen(function* () {
|
||||
? yield* Ref.set(currentPhase, Option.some("commit")).pipe(
|
||||
Effect.flatMap(() =>
|
||||
runCommitStep(
|
||||
modelSelection,
|
||||
textGenerationSettings,
|
||||
input.cwd,
|
||||
commitAction,
|
||||
currentBranch,
|
||||
@@ -2005,7 +2090,7 @@ export const make = Effect.gen(function* () {
|
||||
.pipe(
|
||||
Effect.tap(() => Ref.set(currentPhase, Option.some("pr"))),
|
||||
Effect.flatMap(() =>
|
||||
runPrStep(modelSelection, input.cwd, currentBranch, progress.emit),
|
||||
runPrStep(textGenerationSettings, input.cwd, currentBranch, progress.emit),
|
||||
),
|
||||
)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
@@ -80,7 +80,15 @@ const makeMcpAuthMiddleware = McpSessionRegistry.McpSessionRegistry.pipe(
|
||||
? authorization.slice("Bearer ".length).trim()
|
||||
: "";
|
||||
const invocation = yield* registry.resolve(token);
|
||||
if (!invocation) return unauthorized;
|
||||
if (!invocation) {
|
||||
// Without this the only symptom of a dead credential is the agent
|
||||
// quietly losing the whole `t3-code` toolkit for the rest of its
|
||||
// session, with nothing on the server to explain why.
|
||||
yield* Effect.logWarning("rejected MCP request with an unusable credential", {
|
||||
reason: token.length === 0 ? "missing_bearer_token" : "unknown_or_expired_token",
|
||||
});
|
||||
return unauthorized;
|
||||
}
|
||||
return yield* httpEffect.pipe(
|
||||
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation),
|
||||
Effect.map(normalizeMcpHttpResponse),
|
||||
|
||||
@@ -21,7 +21,10 @@ const fakeEnvironment = ServerEnvironment.ServerEnvironment.of({
|
||||
|
||||
const makeRegistry = (now: () => number, httpServer = fakeHttpServer) =>
|
||||
McpSessionRegistry.__testing
|
||||
.make({ now })
|
||||
.make({
|
||||
now,
|
||||
livenessWindowMs: 100,
|
||||
})
|
||||
.pipe(
|
||||
Effect.provideService(HttpServer.HttpServer, httpServer),
|
||||
Effect.provideService(ServerEnvironment.ServerEnvironment, fakeEnvironment),
|
||||
@@ -72,7 +75,7 @@ it.effect("builds MCP endpoints from the bound server host", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps credentials valid until they are explicitly revoked", () =>
|
||||
it.effect("expires credentials once their session stops showing signs of life", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
@@ -81,12 +84,47 @@ it.effect("keeps credentials valid until they are explicitly revoked", () =>
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
const resolved = yield* registry.resolve(token);
|
||||
expect(resolved?.providerSessionId).toBe(issued.config.providerSessionId);
|
||||
timestamp += 365 * 24 * 60 * 60 * 1_000;
|
||||
expect(yield* registry.resolve(token)).toEqual(resolved);
|
||||
|
||||
yield* registry.revokeProviderSession(issued.config.providerSessionId);
|
||||
timestamp += 101;
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps a credential alive across turns that never touch an MCP tool", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const threadId = ThreadId.make("thread-3");
|
||||
const issued = yield* registry.issue({
|
||||
threadId,
|
||||
providerInstanceId: ProviderInstanceId.make("claude"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
|
||||
// Well past the liveness window in total, but each turn reports in before
|
||||
// it lapses — this is the long-session case that used to lose the toolkit.
|
||||
for (let turn = 0; turn < 10; turn += 1) {
|
||||
timestamp += 99;
|
||||
yield* registry.touch(threadId);
|
||||
}
|
||||
|
||||
expect((yield* registry.resolve(token))?.threadId).toBe(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not keep credentials of other threads alive", () =>
|
||||
Effect.gen(function* () {
|
||||
let timestamp = 1_000;
|
||||
const registry = yield* makeRegistry(() => timestamp);
|
||||
const issued = yield* registry.issue({
|
||||
threadId: ThreadId.make("thread-4"),
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
});
|
||||
const token = issued.config.authorizationHeader.replace(/^Bearer\s+/, "");
|
||||
|
||||
timestamp += 99;
|
||||
yield* registry.touch(ThreadId.make("thread-unrelated"));
|
||||
timestamp += 2;
|
||||
|
||||
expect(yield* registry.resolve(token)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
@@ -19,6 +19,7 @@ export const layer = Layer.succeed(
|
||||
},
|
||||
}),
|
||||
resolve: () => Effect.succeed(undefined),
|
||||
touch: () => Effect.void,
|
||||
revokeProviderSession: () => Effect.void,
|
||||
revokeThread: () => Effect.void,
|
||||
revokeAll: Effect.void,
|
||||
|
||||
@@ -21,11 +21,16 @@ export interface McpIssuedCredential {
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryShape {
|
||||
/** Credentials have no time-based expiry and must be explicitly revoked by their owner. */
|
||||
readonly issue: (request: McpCredentialRequest) => Effect.Effect<McpIssuedCredential>;
|
||||
readonly resolve: (
|
||||
rawToken: string,
|
||||
) => Effect.Effect<McpInvocationContext.McpInvocationScope | undefined>;
|
||||
/**
|
||||
* Records a sign of life for every credential bound to `threadId`. Provider
|
||||
* turns call this so that a session which is plainly alive keeps its
|
||||
* credential even when it goes a long time without touching an MCP tool.
|
||||
*/
|
||||
readonly touch: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
readonly revokeProviderSession: (providerSessionId: string) => Effect.Effect<void>;
|
||||
readonly revokeThread: (threadId: ThreadId) => Effect.Effect<void>;
|
||||
readonly revokeAll: Effect.Effect<void>;
|
||||
@@ -37,7 +42,9 @@ export class McpSessionRegistry extends Context.Service<
|
||||
>()("t3/mcp/McpSessionRegistry") {}
|
||||
|
||||
interface CredentialRecord {
|
||||
readonly tokenHash: string;
|
||||
readonly scope: McpInvocationContext.McpInvocationScope;
|
||||
readonly lastAliveAt: number;
|
||||
}
|
||||
|
||||
interface RegistryState {
|
||||
@@ -45,9 +52,26 @@ interface RegistryState {
|
||||
}
|
||||
|
||||
export interface McpSessionRegistryOptions {
|
||||
readonly livenessWindowMs?: number;
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
/**
|
||||
* How long a credential outlives the last sign of life from its provider
|
||||
* session.
|
||||
*
|
||||
* Liveness is refreshed both by MCP traffic and by `touch` on every provider
|
||||
* turn, so a session that is still doing work never expires no matter how long
|
||||
* it goes between browser tool calls. This window therefore only bounds
|
||||
* credentials whose session died without a clean stop — the normal paths
|
||||
* (`stopSession`, `stopAll`) revoke eagerly and do not wait for it.
|
||||
*
|
||||
* The bound matters because `/mcp` is mounted outside the environment auth
|
||||
* stack and is reachable on whatever host the server binds to, so this token is
|
||||
* the only thing guarding the preview toolkit on a remote-reachable server.
|
||||
*/
|
||||
const DEFAULT_LIVENESS_WINDOW_MS = 24 * 60 * 60 * 1_000;
|
||||
|
||||
const bytesToHex = (bytes: Uint8Array): string =>
|
||||
Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
@@ -73,6 +97,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
const httpServer = yield* HttpServer.HttpServer;
|
||||
const state = yield* SynchronizedRef.make<RegistryState>({ records: new Map() });
|
||||
const currentTimeMillis = options.now ? Effect.sync(options.now) : Clock.currentTimeMillis;
|
||||
const livenessWindowMs = options.livenessWindowMs ?? DEFAULT_LIVENESS_WINDOW_MS;
|
||||
const endpoint =
|
||||
httpServer.address._tag === "TcpAddress"
|
||||
? `http://${getHttpMcpEndpointHost(httpServer.address.hostname)}:${httpServer.address.port}/mcp`
|
||||
@@ -83,6 +108,15 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
.digest("SHA-256", new TextEncoder().encode(token))
|
||||
.pipe(Effect.map(bytesToHex), Effect.orDie);
|
||||
|
||||
const pruneDead = (records: ReadonlyMap<string, CredentialRecord>, timestamp: number) => {
|
||||
const next = new Map(
|
||||
Array.from(records).filter(
|
||||
([, record]) => timestamp - record.lastAliveAt <= livenessWindowMs,
|
||||
),
|
||||
);
|
||||
return next.size === records.size ? records : next;
|
||||
};
|
||||
|
||||
const issue: McpSessionRegistryShape["issue"] = Effect.fn("McpSessionRegistry.issue")(
|
||||
function* (request) {
|
||||
const issuedAt = yield* currentTimeMillis;
|
||||
@@ -98,8 +132,8 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
issuedAt,
|
||||
};
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
const next = new Map(records);
|
||||
next.set(tokenHash, { scope });
|
||||
const next = new Map(pruneDead(records, issuedAt));
|
||||
next.set(tokenHash, { tokenHash, scope, lastAliveAt: issuedAt });
|
||||
return { records: next };
|
||||
});
|
||||
return {
|
||||
@@ -119,8 +153,31 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
function* (rawToken) {
|
||||
if (rawToken.length === 0) return undefined;
|
||||
const tokenHash = yield* hashToken(rawToken);
|
||||
const record = (yield* SynchronizedRef.get(state)).records.get(tokenHash);
|
||||
return record?.scope;
|
||||
const timestamp = yield* currentTimeMillis;
|
||||
return yield* SynchronizedRef.modify(state, ({ records }) => {
|
||||
const current = pruneDead(records, timestamp);
|
||||
const record = current.get(tokenHash);
|
||||
if (!record) return [undefined, { records: current }] as const;
|
||||
const next = new Map(current);
|
||||
next.set(tokenHash, { ...record, lastAliveAt: timestamp });
|
||||
return [record.scope, { records: next }] as const;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const touch: McpSessionRegistryShape["touch"] = Effect.fn("McpSessionRegistry.touch")(
|
||||
function* (threadId) {
|
||||
const timestamp = yield* currentTimeMillis;
|
||||
yield* SynchronizedRef.update(state, ({ records }) => {
|
||||
const current = pruneDead(records, timestamp);
|
||||
const next = new Map(current);
|
||||
for (const [tokenHash, record] of current) {
|
||||
if (record.scope.threadId === threadId) {
|
||||
next.set(tokenHash, { ...record, lastAliveAt: timestamp });
|
||||
}
|
||||
}
|
||||
return { records: next };
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -132,6 +189,7 @@ const makeWithOptions = Effect.fn("McpSessionRegistry.make")(function* (
|
||||
return McpSessionRegistry.of({
|
||||
issue,
|
||||
resolve,
|
||||
touch,
|
||||
revokeProviderSession: Effect.fn("McpSessionRegistry.revokeProviderSession")(
|
||||
function* (providerSessionId) {
|
||||
yield* revokeWhere((record) => record.scope.providerSessionId === providerSessionId);
|
||||
@@ -173,6 +231,13 @@ export const issueActiveMcpCredential = (
|
||||
.pipe(Effect.andThen(activeMcpSessionRegistry.issue(request)))
|
||||
: Effect.sync((): McpIssuedCredential | undefined => undefined);
|
||||
|
||||
/**
|
||||
* Refreshes the liveness of a thread's MCP credential. Called on every provider
|
||||
* turn so an active session is never mistaken for an abandoned one.
|
||||
*/
|
||||
export const touchActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.touch(threadId) : Effect.void;
|
||||
|
||||
export const revokeActiveMcpThread = (threadId: ThreadId): Effect.Effect<void> =>
|
||||
activeMcpSessionRegistry ? activeMcpSessionRegistry.revokeThread(threadId) : Effect.void;
|
||||
|
||||
|
||||
@@ -74,6 +74,14 @@ interface PendingRequest {
|
||||
readonly context: PreviewAutomationRequestErrorContext;
|
||||
}
|
||||
|
||||
/**
|
||||
* A lease pinning one provider session to one desktop runtime. It lives exactly
|
||||
* as long as the connection it names: `connectionId`/`queue` identity is what
|
||||
* makes a lease valid, so a disconnected or replaced host is dropped on the next
|
||||
* lookup. The lease deliberately has no clock of its own — it used to inherit
|
||||
* the MCP credential's expiry, which coupled host stickiness to an unrelated
|
||||
* auth deadline and could migrate a live session to another runtime mid-flow.
|
||||
*/
|
||||
interface HostAssignment {
|
||||
readonly clientId: ClientConnection["clientId"];
|
||||
readonly connectionId: ClientConnection["connectionId"];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
CheckpointScopeId,
|
||||
CommandId,
|
||||
@@ -32,6 +32,7 @@ import * as Option from "effect/Option";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
@@ -307,6 +308,77 @@ it.effect("rechecks run ownership immediately before calling the provider", () =
|
||||
}).pipe(Effect.provide(RunExecutionTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("refreshes MCP credential liveness before calling the provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const runExecution = yield* RunExecutionServiceV2;
|
||||
const order = yield* Ref.make<ReadonlyArray<string>>([]);
|
||||
const threadId = ThreadId.make("thread:run-execution-mcp-liveness");
|
||||
const touchActiveMcpThread = vi
|
||||
.spyOn(McpSessionRegistry, "touchActiveMcpThread")
|
||||
.mockImplementation((touchedThreadId) =>
|
||||
Ref.update(order, (entries) => [...entries, `touch:${touchedThreadId}`]),
|
||||
);
|
||||
|
||||
yield* runExecution
|
||||
.startRootRun({
|
||||
commandId: CommandId.make("command:run-execution-mcp-liveness"),
|
||||
appThread: { id: threadId } as OrchestrationV2AppThread,
|
||||
providerSessionId: ProviderSessionId.make("session:run-execution-mcp-liveness"),
|
||||
session: {
|
||||
events: Stream.never,
|
||||
startTurn: () => Ref.update(order, (entries) => [...entries, "start-turn"]),
|
||||
} as unknown as ProviderAdapterV2SessionRuntime,
|
||||
run: {
|
||||
id: RunId.make("run:run-execution-mcp-liveness"),
|
||||
threadId,
|
||||
ordinal: 1,
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
} as OrchestrationV2Run,
|
||||
rootNode: {
|
||||
id: NodeId.make("node:run-execution-mcp-liveness"),
|
||||
} as OrchestrationV2ExecutionNode,
|
||||
checkpointScope: {
|
||||
id: CheckpointScopeId.make("checkpoint-scope:run-execution-mcp-liveness"),
|
||||
} as OrchestrationV2CheckpointScope,
|
||||
providerThread: {
|
||||
id: ProviderThreadId.make("provider-thread:run-execution-mcp-liveness"),
|
||||
driver,
|
||||
} as OrchestrationV2ProviderThread,
|
||||
attempt: {
|
||||
id: RunAttemptId.make("attempt:run-execution-mcp-liveness"),
|
||||
providerTurnId: null,
|
||||
} as OrchestrationV2RunAttempt,
|
||||
attemptId: RunAttemptId.make("attempt:run-execution-mcp-liveness"),
|
||||
providerTurnOrdinal: 1,
|
||||
message: {
|
||||
messageId: MessageId.make("message:run-execution-mcp-liveness"),
|
||||
text: "Keep the MCP credential alive.",
|
||||
attachments: [],
|
||||
createdBy: "user",
|
||||
creationSource: "web",
|
||||
},
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
runtimePolicy: {
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
cwd: process.cwd(),
|
||||
approvalPolicy: "never",
|
||||
sandboxPolicy: {
|
||||
type: "readOnly",
|
||||
access: { type: "fullAccess" },
|
||||
networkAccess: false,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.ensuring(Effect.sync(() => touchActiveMcpThread.mockRestore())));
|
||||
|
||||
assert.deepEqual(yield* Ref.get(order), [`touch:${threadId}`, "start-turn"]);
|
||||
}).pipe(Effect.provide(RunExecutionTestLayer)),
|
||||
);
|
||||
|
||||
it.effect("keeps ingesting owned child events after the root turn terminalizes", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = ThreadId.make("thread:run-execution-late-child");
|
||||
|
||||
@@ -31,6 +31,7 @@ import * as Ref from "effect/Ref";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import * as McpSessionRegistry from "../mcp/McpSessionRegistry.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import { CheckpointServiceV2 } from "./CheckpointService.ts";
|
||||
import { EventSinkV2 } from "./EventSink.ts";
|
||||
@@ -1094,6 +1095,10 @@ export const layer: Layer.Layer<
|
||||
return;
|
||||
}
|
||||
|
||||
// A provider turn is a sign that the session is still alive. Keep
|
||||
// its already-issued MCP credential valid even when the agent goes
|
||||
// a long time between browser-tool calls.
|
||||
yield* McpSessionRegistry.touchActiveMcpThread(input.run.threadId);
|
||||
yield* input.session
|
||||
.startTurn({
|
||||
appThread: input.appThread,
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ServerProvider,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
@@ -20,6 +22,8 @@ import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||
import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import { makeProviderRegistryLayer } from "../provider/testUtils/providerRegistryMock.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
|
||||
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
||||
@@ -61,6 +65,9 @@ interface HarnessOptions {
|
||||
readonly createWorktree?: GitWorkflow.GitWorkflowService["Service"]["createWorktree"];
|
||||
readonly runSetup?: ProjectSetupScriptRunner.ProjectSetupScriptRunner["Service"]["runForThread"];
|
||||
readonly generateTitle?: TextGeneration.TextGeneration["Service"]["generateThreadTitle"];
|
||||
readonly generateBranchName?: TextGeneration.TextGeneration["Service"]["generateBranchName"];
|
||||
readonly serverSettings?: Parameters<typeof ServerSettings.layerTest>[0];
|
||||
readonly providers?: ReadonlyArray<ServerProvider>;
|
||||
}
|
||||
|
||||
function makeHarness(options: HarnessOptions = {}) {
|
||||
@@ -84,6 +91,9 @@ function makeHarness(options: HarnessOptions = {}) {
|
||||
const runSetup = vi.fn(
|
||||
options.runSetup ?? (() => Effect.succeed({ status: "no-script" as const })),
|
||||
);
|
||||
const generateBranchName = vi.fn(
|
||||
options.generateBranchName ?? (() => Effect.succeed({ branch: "generated-branch" })),
|
||||
);
|
||||
const externalServices = Layer.mergeAll(
|
||||
Layer.succeed(ProjectService.ProjectService, {
|
||||
create: () => Effect.die("unused"),
|
||||
@@ -107,8 +117,10 @@ function makeHarness(options: HarnessOptions = {}) {
|
||||
Layer.mock(TextGeneration.TextGeneration)({
|
||||
generateThreadTitle:
|
||||
options.generateTitle ?? (() => Effect.succeed({ title: "Generated title" })),
|
||||
generateBranchName: () => Effect.succeed({ branch: "generated-branch" }),
|
||||
generateBranchName,
|
||||
}),
|
||||
ServerSettings.layerTest(options.serverSettings),
|
||||
makeProviderRegistryLayer(options.providers),
|
||||
);
|
||||
const launch = ThreadLaunch.layer.pipe(
|
||||
Layer.provide(Layer.mergeAll(externalServices, threadManagement, receipts, IdAllocator.layer)),
|
||||
@@ -116,6 +128,7 @@ function makeHarness(options: HarnessOptions = {}) {
|
||||
return {
|
||||
layer: Layer.mergeAll(launch, threadManagement, outbox, database),
|
||||
createWorktree,
|
||||
generateBranchName,
|
||||
runSetup,
|
||||
};
|
||||
}
|
||||
@@ -443,6 +456,98 @@ it.effect("does not put optional title generation on the provisioning critical p
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the available source control writer for generated worktree branches", () =>
|
||||
Effect.gen(function* () {
|
||||
const writerInstanceId = ProviderInstanceId.make("source-control-writer");
|
||||
const writerModelSelection = {
|
||||
instanceId: writerInstanceId,
|
||||
model: "branch-writer-model",
|
||||
} as const;
|
||||
const harness = makeHarness({
|
||||
serverSettings: {
|
||||
providerInstances: {
|
||||
[writerInstanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection: writerModelSelection,
|
||||
},
|
||||
providers: [
|
||||
{
|
||||
instanceId: writerInstanceId,
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-07-28T00:00:00.000Z",
|
||||
availability: "available",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const launches = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* launches.launch(
|
||||
launchInput({
|
||||
command: "command:launch:source-control-writer",
|
||||
thread: "thread:launch:source-control-writer",
|
||||
message: "Generate a branch with the configured writer",
|
||||
workspace: { type: "worktree", baseRef: "main" },
|
||||
}),
|
||||
);
|
||||
yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
|
||||
assert.deepEqual(
|
||||
harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
|
||||
writerModelSelection,
|
||||
);
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back when the source control writer is unavailable", () =>
|
||||
Effect.gen(function* () {
|
||||
const writerInstanceId = ProviderInstanceId.make("missing-source-control-writer");
|
||||
const harness = makeHarness({
|
||||
serverSettings: {
|
||||
providerInstances: {
|
||||
[writerInstanceId]: {
|
||||
driver: ProviderDriverKind.make("missing-driver"),
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection: {
|
||||
instanceId: writerInstanceId,
|
||||
model: "missing-branch-writer-model",
|
||||
},
|
||||
},
|
||||
providers: [],
|
||||
});
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const launches = yield* ThreadLaunch.ThreadLaunchService;
|
||||
yield* launches.launch(
|
||||
launchInput({
|
||||
command: "command:launch:source-control-writer-fallback",
|
||||
thread: "thread:launch:source-control-writer-fallback",
|
||||
message: "Generate a branch with the available writer",
|
||||
workspace: { type: "worktree", baseRef: "main" },
|
||||
}),
|
||||
);
|
||||
yield* waitUntil(() => Effect.sync(() => harness.generateBranchName.mock.calls.length === 1));
|
||||
assert.deepEqual(
|
||||
harness.generateBranchName.mock.calls[0]?.[0].modelSelection,
|
||||
DEFAULT_SERVER_SETTINGS.textGenerationModelSelection,
|
||||
);
|
||||
}).pipe(Effect.provide(harness.layer));
|
||||
}),
|
||||
);
|
||||
|
||||
for (const failurePoint of ["worktree", "setup"] as const) {
|
||||
it.effect(
|
||||
`${failurePoint} failure keeps the thread and message visible and emits failure items`,
|
||||
|
||||
@@ -25,6 +25,8 @@ import * as Scope from "effect/Scope";
|
||||
import * as GitWorkflow from "../git/GitWorkflowService.ts";
|
||||
import * as ProjectService from "../project/ProjectService.ts";
|
||||
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
|
||||
import * as ProviderRegistry from "../provider/Services/ProviderRegistry.ts";
|
||||
import * as ServerSettings from "../serverSettings.ts";
|
||||
import * as TextGeneration from "../textGeneration/TextGeneration.ts";
|
||||
import * as CommandReceiptStore from "./CommandReceiptStore.ts";
|
||||
import * as IdAllocator from "./IdAllocator.ts";
|
||||
@@ -132,6 +134,8 @@ export const make = Effect.gen(function* () {
|
||||
const projects = yield* ProjectService.ProjectService;
|
||||
const git = yield* GitWorkflow.GitWorkflowService;
|
||||
const setupScripts = yield* ProjectSetupScriptRunner.ProjectSetupScriptRunner;
|
||||
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
|
||||
const serverSettings = yield* ServerSettings.ServerSettingsService;
|
||||
const textGeneration = yield* TextGeneration.TextGeneration;
|
||||
const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
|
||||
const ids = yield* IdAllocator.IdAllocatorV2;
|
||||
@@ -222,21 +226,29 @@ export const make = Effect.gen(function* () {
|
||||
);
|
||||
}
|
||||
|
||||
const initialMessage = input.initialMessage;
|
||||
let branch =
|
||||
input.workspaceStrategy.type === "worktree" &&
|
||||
input.workspaceStrategy.branch === undefined &&
|
||||
input.initialMessage !== undefined
|
||||
? yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: project.workspaceRoot,
|
||||
message: input.initialMessage.text,
|
||||
attachments: input.initialMessage.attachments,
|
||||
modelSelection: input.modelSelection,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.branch),
|
||||
Effect.mapError(mapError(input, "generate-metadata", threadId)),
|
||||
)
|
||||
initialMessage !== undefined
|
||||
? yield* Effect.gen(function* () {
|
||||
const settings = yield* serverSettings.getSettings;
|
||||
const modelSelection =
|
||||
settings.sourceControlWriterModelSelection === null
|
||||
? settings.textGenerationModelSelection
|
||||
: ServerSettings.resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
yield* providerRegistry.getProviders,
|
||||
);
|
||||
return yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: project.workspaceRoot,
|
||||
message: initialMessage.text,
|
||||
attachments: initialMessage.attachments,
|
||||
modelSelection,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.branch));
|
||||
}).pipe(Effect.mapError(mapError(input, "generate-metadata", threadId)))
|
||||
: (input.workspaceStrategy.branch ??
|
||||
(input.workspaceStrategy.type === "worktree" ? fallbackBranchName(threadId) : null));
|
||||
let worktreePath =
|
||||
|
||||
@@ -325,6 +325,73 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"preserves the source control writer selection when its provider instance is disabled",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
const serverConfig = yield* ServerConfig.ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const instanceId = ProviderInstanceId.make("codex_writer");
|
||||
const sourceControlWriterModelSelection = {
|
||||
instanceId,
|
||||
model: "gpt-5.4-mini",
|
||||
};
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
sourceControlWriterModelSelection,
|
||||
});
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: false,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.sourceControlWriterModelSelection, sourceControlWriterModelSelection);
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(next),
|
||||
next.textGenerationModelSelection,
|
||||
);
|
||||
assert.deepEqual(
|
||||
(yield* serverSettings.getSettings).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
|
||||
assert.deepEqual(
|
||||
// @effect-diagnostics-next-line preferSchemaOverJson:off
|
||||
JSON.parse(raw).sourceControlWriterModelSelection,
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
|
||||
const restored = yield* serverSettings.updateSettings({
|
||||
providerInstances: {
|
||||
[instanceId]: {
|
||||
driver: ProviderDriverKind.make("codex"),
|
||||
enabled: true,
|
||||
config: {},
|
||||
},
|
||||
},
|
||||
});
|
||||
assert.deepEqual(
|
||||
ServerSettingsModule.resolveSourceControlWriterModelSelection(restored),
|
||||
sourceControlWriterModelSelection,
|
||||
);
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("drops stale text generation options when resetting model selection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsModule.ServerSettingsService;
|
||||
|
||||
@@ -11,11 +11,10 @@
|
||||
* @module ServerSettings
|
||||
*/
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
isProviderDriverKind,
|
||||
type ModelSelection,
|
||||
type ProviderInstanceConfig,
|
||||
type ProviderInstanceEnvironmentVariable,
|
||||
@@ -47,9 +46,14 @@ import { writeFileStringAtomically } from "./atomicWrite.ts";
|
||||
import * as ServerConfig from "./config.ts";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
applyServerSettingsPatch,
|
||||
isModelSelectionProviderEnabled,
|
||||
} from "@t3tools/shared/serverSettings";
|
||||
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
|
||||
|
||||
export { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
|
||||
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
|
||||
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
|
||||
@@ -148,12 +152,13 @@ const makeTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
return {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Ref.get(currentSettingsRef),
|
||||
getSettings: Ref.get(currentSettingsRef).pipe(Effect.map(resolveTextGenerationProvider)),
|
||||
updateSettings: (patch) =>
|
||||
Ref.get(currentSettingsRef).pipe(
|
||||
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
|
||||
Effect.flatMap(normalizeServerSettings),
|
||||
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
|
||||
Effect.map(resolveTextGenerationProvider),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsService["Service"];
|
||||
@@ -165,35 +170,10 @@ export const layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
const decodeServerSettingsJsonExit = Schema.decodeUnknownExit(ServerSettingsJson);
|
||||
|
||||
type LegacyProviderSettings = ServerSettings["providers"][keyof ServerSettings["providers"]];
|
||||
|
||||
const getLegacyProviderSettings = (
|
||||
settings: ServerSettings,
|
||||
provider: ProviderDriverKind,
|
||||
): LegacyProviderSettings | undefined =>
|
||||
(settings.providers as Record<string, LegacyProviderSettings | undefined>)[provider];
|
||||
|
||||
/**
|
||||
* Ensure the `textGenerationModelSelection` points to an enabled provider.
|
||||
* If the selected provider is disabled, fall back to the first enabled
|
||||
* provider with its default model. This is applied at read-time so the
|
||||
* persisted preference is preserved for when a provider is re-enabled.
|
||||
*/
|
||||
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
const selection = settings.textGenerationModelSelection;
|
||||
const instanceConfig = settings.providerInstances[selection.instanceId];
|
||||
if (instanceConfig !== undefined) {
|
||||
return (instanceConfig.enabled ?? true) ? settings : fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
if (
|
||||
isProviderDriverKind(selection.instanceId) &&
|
||||
getLegacyProviderSettings(settings, selection.instanceId)?.enabled
|
||||
) {
|
||||
return settings;
|
||||
}
|
||||
|
||||
return fallbackTextGenerationProvider(settings);
|
||||
return isModelSelectionProviderEnabled(settings, settings.textGenerationModelSelection)
|
||||
? settings
|
||||
: fallbackTextGenerationProvider(settings);
|
||||
}
|
||||
|
||||
function fallbackTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
@@ -208,9 +188,9 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
textGenerationModelSelection: {
|
||||
instanceId: ProviderInstanceId.make(fallback),
|
||||
model:
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_MODEL_BY_PROVIDER[fallback] ??
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
DEFAULT_TEXT_GENERATION_MODEL,
|
||||
} satisfies ModelSelection,
|
||||
};
|
||||
}
|
||||
@@ -218,6 +198,7 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
|
||||
"automaticGitFetchInterval",
|
||||
"sourceControlWriterModelSelection",
|
||||
"textGenerationModelSelection",
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
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 Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsProcess from "../vcs/VcsProcess.ts";
|
||||
import { detectPrTemplate } from "./PrTemplateDetection.ts";
|
||||
|
||||
const SINGLE_TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const PrTemplateDetectionTestLayer = GitVcsDriver.layer.pipe(
|
||||
Layer.provide(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-pr-template-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runGit = (cwd: string, args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* git.execute({
|
||||
operation: "PrTemplateDetection.test.runGit",
|
||||
cwd,
|
||||
args,
|
||||
});
|
||||
});
|
||||
|
||||
const runWithTempDirectory = <A, E, R>(
|
||||
test: (cwd: string) => Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
|
||||
) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const cwd = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-pr-template-" });
|
||||
yield* runGit(cwd, ["init", "--initial-branch=main"]);
|
||||
yield* runGit(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* runGit(cwd, ["config", "user.name", "Test User"]);
|
||||
return yield* test(cwd);
|
||||
}),
|
||||
).pipe(Effect.provide(PrTemplateDetectionTestLayer));
|
||||
|
||||
const writeTemplate = (cwd: string, relativePath: string, contents: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templatePath = path.join(cwd, relativePath);
|
||||
yield* fileSystem.makeDirectory(path.dirname(templatePath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(templatePath, contents);
|
||||
return templatePath;
|
||||
});
|
||||
|
||||
const commitTemplates = (cwd: string) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit(cwd, ["add", "-A"]);
|
||||
yield* runGit(cwd, ["commit", "--allow-empty", "-m", "Add pull request templates"]);
|
||||
});
|
||||
|
||||
const detectTemplate = (cwd: string, treeish = "HEAD") =>
|
||||
Effect.gen(function* () {
|
||||
const git = yield* GitVcsDriver.GitVcsDriver;
|
||||
return yield* detectPrTemplate(cwd, treeish, git.execute);
|
||||
});
|
||||
|
||||
it.effect.each(SINGLE_TEMPLATE_PATHS)("recognizes $0", (relativePath) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, relativePath, `template from ${relativePath}`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), `template from ${relativePath}`);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads templates from the requested base tree", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, "README.md", "initial\n");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["branch", "feature"]);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", "base template");
|
||||
yield* commitTemplates(cwd);
|
||||
yield* runGit(cwd, ["checkout", "feature"]);
|
||||
|
||||
assert.isTrue(Option.isNone(yield* detectTemplate(cwd)));
|
||||
assert.strictEqual(
|
||||
Option.getOrUndefined(yield* detectTemplate(cwd, "main")),
|
||||
"base template",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("uses the first non-empty template in the configured path order", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", " \n");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE.md", " ## Preferred template \n");
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "## Later template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "## Preferred template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect.each(TEMPLATE_DIRECTORIES)("recognizes the $0 directory", (relativeDirectory) =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, `${relativeDirectory}/template.MD`, "directory template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "directory template");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("skips unusable directory entries and uses the one valid template", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const templateDirectory = path.join(cwd, ".github", "PULL_REQUEST_TEMPLATE");
|
||||
yield* fileSystem.makeDirectory(path.join(templateDirectory, "b-directory.md"), {
|
||||
recursive: true,
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "a-empty.md"), " \n");
|
||||
yield* fileSystem.symlink(
|
||||
path.join(templateDirectory, "missing.md"),
|
||||
path.join(templateDirectory, "c-broken.md"),
|
||||
);
|
||||
yield* fileSystem.writeFileString(path.join(templateDirectory, "z-valid.md"), "valid");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "valid");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not guess between multiple directory templates", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/a.md", "first");
|
||||
yield* writeTemplate(cwd, ".github/PULL_REQUEST_TEMPLATE/b.md", "second");
|
||||
yield* writeTemplate(cwd, "PULL_REQUEST_TEMPLATE/fallback.md", "fallback");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.isTrue(Option.isNone(template));
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("rejects a committed template symlink escaping the repository", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const outsideTemplate = path.join(outsideDirectory, "secret.md");
|
||||
yield* fileSystem.writeFileString(outsideTemplate, "LOCAL_SECRET_SENTINEL");
|
||||
const escapedTemplatePath = path.join(cwd, ".github", "pull_request_template.md");
|
||||
yield* fileSystem.makeDirectory(path.dirname(escapedTemplatePath), { recursive: true });
|
||||
yield* fileSystem.symlink(outsideTemplate, escapedTemplatePath);
|
||||
yield* writeTemplate(cwd, "pull_request_template.md", "safe template");
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "safe template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("reads the committed template when a worktree parent is replaced", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const outsideDirectory = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-pr-template-outside-",
|
||||
});
|
||||
const templatePath = yield* writeTemplate(
|
||||
cwd,
|
||||
".github/pull_request_template.md",
|
||||
"committed template",
|
||||
);
|
||||
yield* commitTemplates(cwd);
|
||||
yield* writeTemplate(outsideDirectory, "pull_request_template.md", "LOCAL_SECRET_SENTINEL");
|
||||
|
||||
const templateDirectory = path.dirname(templatePath);
|
||||
yield* fileSystem.rename(templateDirectory, path.join(cwd, ".github-original"));
|
||||
yield* fileSystem.symlink(outsideDirectory, templateDirectory);
|
||||
|
||||
const template = yield* detectTemplate(cwd);
|
||||
assert.strictEqual(Option.getOrUndefined(template), "committed template");
|
||||
assert.notInclude(
|
||||
Option.getOrElse(template, () => ""),
|
||||
"LOCAL_SECRET_SENTINEL",
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("bounds template reads and marks truncated content", () =>
|
||||
runWithTempDirectory((cwd) =>
|
||||
Effect.gen(function* () {
|
||||
const prefix = "a".repeat(8_000);
|
||||
yield* writeTemplate(cwd, ".github/pull_request_template.md", `${prefix}SECRET_SENTINEL`);
|
||||
yield* commitTemplates(cwd);
|
||||
|
||||
const template = Option.getOrThrow(yield* detectTemplate(cwd));
|
||||
assert.strictEqual(template, `${prefix}\n\n[truncated]`);
|
||||
assert.lengthOf(template.match(/\[truncated\]/g) ?? [], 1);
|
||||
assert.notInclude(template, "SECRET_SENTINEL");
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { GitCommandError } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
|
||||
import type * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
|
||||
const TEMPLATE_MAX_BYTES = 8_000;
|
||||
const TREE_LIST_MAX_BYTES = 100_000;
|
||||
const TRUNCATION_MARKER = "[truncated]";
|
||||
|
||||
const TEMPLATE_PATHS = [
|
||||
".github/pull_request_template.md",
|
||||
".github/PULL_REQUEST_TEMPLATE.md",
|
||||
"pull_request_template.md",
|
||||
"PULL_REQUEST_TEMPLATE.md",
|
||||
"docs/pull_request_template.md",
|
||||
"docs/PULL_REQUEST_TEMPLATE.md",
|
||||
] as const;
|
||||
|
||||
const TEMPLATE_DIRECTORIES = [
|
||||
".github/PULL_REQUEST_TEMPLATE",
|
||||
"PULL_REQUEST_TEMPLATE",
|
||||
"docs/PULL_REQUEST_TEMPLATE",
|
||||
] as const;
|
||||
|
||||
const TREE_PATHS = [...TEMPLATE_PATHS, ...TEMPLATE_DIRECTORIES] as const;
|
||||
|
||||
type ExecuteGit = GitVcsDriver.GitVcsDriver["Service"]["execute"];
|
||||
|
||||
interface TemplateTreeEntry {
|
||||
readonly objectId: string;
|
||||
readonly path: string;
|
||||
}
|
||||
|
||||
function parseTemplateTreeEntries(output: string): ReadonlyArray<TemplateTreeEntry> {
|
||||
const entries: TemplateTreeEntry[] = [];
|
||||
for (const record of output.split("\0")) {
|
||||
if (record.length === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const separator = record.indexOf("\t");
|
||||
if (separator < 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const [mode, type, objectId] = record.slice(0, separator).split(" ");
|
||||
if (
|
||||
type !== "blob" ||
|
||||
(mode !== "100644" && mode !== "100755") ||
|
||||
!objectId ||
|
||||
!/^[0-9a-f]{40,64}$/.test(objectId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
entries.push({ objectId, path: record.slice(separator + 1) });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
function readTemplateBlob(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entry: TemplateTreeEntry;
|
||||
}): Effect.Effect<Option.Option<string>, GitCommandError> {
|
||||
return input
|
||||
.executeGit({
|
||||
operation: "PrTemplateDetection.readTemplateBlob",
|
||||
cwd: input.cwd,
|
||||
args: ["cat-file", "blob", input.entry.objectId],
|
||||
maxOutputBytes: TEMPLATE_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
const template = result.stdout.trim();
|
||||
if (template.length === 0) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some(
|
||||
result.stdoutTruncated && !template.endsWith(TRUNCATION_MARKER)
|
||||
? `${template}\n\n${TRUNCATION_MARKER}`
|
||||
: template,
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
type DirectoryTemplateResult =
|
||||
| { readonly _tag: "None" }
|
||||
| { readonly _tag: "Ambiguous" }
|
||||
| { readonly _tag: "Template"; readonly template: string };
|
||||
|
||||
function readTemplateDirectory(input: {
|
||||
readonly cwd: string;
|
||||
readonly executeGit: ExecuteGit;
|
||||
readonly entries: ReadonlyArray<TemplateTreeEntry>;
|
||||
readonly directory: string;
|
||||
}): Effect.Effect<DirectoryTemplateResult, GitCommandError> {
|
||||
return Effect.gen(function* () {
|
||||
const prefix = `${input.directory}/`;
|
||||
const candidates = input.entries.filter((entry) => {
|
||||
if (!entry.path.startsWith(prefix)) {
|
||||
return false;
|
||||
}
|
||||
const relativePath = entry.path.slice(prefix.length);
|
||||
return !relativePath.includes("/") && relativePath.toLowerCase().endsWith(".md");
|
||||
});
|
||||
|
||||
const templates: string[] = [];
|
||||
for (const entry of candidates) {
|
||||
const template = yield* readTemplateBlob({ ...input, entry });
|
||||
if (Option.isSome(template)) {
|
||||
templates.push(template.value);
|
||||
if (templates.length > 1) {
|
||||
return { _tag: "Ambiguous" } as const;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return templates[0]
|
||||
? ({ _tag: "Template", template: templates[0] } as const)
|
||||
: ({ _tag: "None" } as const);
|
||||
});
|
||||
}
|
||||
|
||||
export const detectPrTemplate = Effect.fn("detectPrTemplate")(function* (
|
||||
cwd: string,
|
||||
treeish: string,
|
||||
executeGit: ExecuteGit,
|
||||
) {
|
||||
return yield* Effect.gen(function* () {
|
||||
// Worktree paths can be replaced between validation and open. Read regular blobs from the
|
||||
// committed base tree so repository-controlled symlinks and path races never reach the host filesystem.
|
||||
const result = yield* executeGit({
|
||||
operation: "PrTemplateDetection.listTemplates",
|
||||
cwd,
|
||||
args: ["ls-tree", "-r", "-z", "--full-tree", treeish, "--", ...TREE_PATHS],
|
||||
maxOutputBytes: TREE_LIST_MAX_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
});
|
||||
if (result.stdoutTruncated) {
|
||||
return Option.none();
|
||||
}
|
||||
|
||||
const entries = parseTemplateTreeEntries(result.stdout);
|
||||
const entriesByPath = new Map(entries.map((entry) => [entry.path, entry]));
|
||||
for (const templatePath of TEMPLATE_PATHS) {
|
||||
const entry = entriesByPath.get(templatePath);
|
||||
if (!entry) {
|
||||
continue;
|
||||
}
|
||||
const template = yield* readTemplateBlob({ cwd, executeGit, entry });
|
||||
if (Option.isSome(template)) {
|
||||
return template;
|
||||
}
|
||||
}
|
||||
|
||||
for (const directory of TEMPLATE_DIRECTORIES) {
|
||||
const directoryTemplate = yield* readTemplateDirectory({
|
||||
cwd,
|
||||
executeGit,
|
||||
entries,
|
||||
directory,
|
||||
});
|
||||
if (directoryTemplate._tag === "Template") {
|
||||
return Option.some(directoryTemplate.template);
|
||||
}
|
||||
if (directoryTemplate._tag === "Ambiguous") {
|
||||
return Option.none();
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
}).pipe(Effect.orElseSucceed(() => Option.none()));
|
||||
});
|
||||
@@ -272,6 +272,7 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
@@ -299,6 +300,8 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
|
||||
@@ -305,6 +305,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
@@ -332,6 +333,8 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
|
||||
@@ -163,6 +163,7 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")((
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
@@ -190,6 +191,8 @@ export const makeCursorTextGeneration = Effect.fn("makeCursorTextGeneration")((
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runCursorJson({
|
||||
|
||||
@@ -164,6 +164,7 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
@@ -191,6 +192,8 @@ export const makeGrokTextGeneration = Effect.fn("makeGrokTextGeneration")(functi
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
|
||||
const generated = yield* runGrokJson({
|
||||
|
||||
@@ -530,6 +530,7 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
stagedSummary: input.stagedSummary,
|
||||
stagedPatch: input.stagedPatch,
|
||||
includeBranch: input.includeBranch === true,
|
||||
policy: input.policy,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generateCommitMessage",
|
||||
@@ -556,6 +557,8 @@ export const makeOpenCodeTextGeneration = Effect.fn("makeOpenCodeTextGeneration"
|
||||
commitSummary: input.commitSummary,
|
||||
diffSummary: input.diffSummary,
|
||||
diffPatch: input.diffPatch,
|
||||
policy: input.policy,
|
||||
changeRequestTemplate: input.changeRequestTemplate,
|
||||
});
|
||||
const generated = yield* runOpenCodeJson({
|
||||
operation: "generatePrContent",
|
||||
|
||||
@@ -6,6 +6,7 @@ import { TextGenerationError } from "@t3tools/contracts";
|
||||
|
||||
import * as ProviderInstanceRegistry from "../provider/Services/ProviderInstanceRegistry.ts";
|
||||
import type { ProviderInstance } from "../provider/ProviderDriver.ts";
|
||||
import type { TextGenerationPolicy } from "./TextGenerationPolicy.ts";
|
||||
|
||||
export type TextGenerationProvider = "codex" | "claudeAgent" | "cursor" | "grok" | "opencode";
|
||||
|
||||
@@ -16,6 +17,7 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -34,6 +36,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
@@ -77,7 +81,7 @@ export interface TextGenerationService {
|
||||
}
|
||||
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
* TextGeneration - Service tag for commit and change request text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<
|
||||
TextGeneration,
|
||||
@@ -90,7 +94,7 @@ export class TextGeneration extends Context.Service<
|
||||
) => Effect.Effect<CommitMessageGenerationResult, TextGenerationError>;
|
||||
|
||||
/**
|
||||
* Generate pull request title/body from branch and diff context.
|
||||
* Generate change request title/body from branch and diff context.
|
||||
*/
|
||||
readonly generatePrContent: (
|
||||
input: PrContentGenerationInput,
|
||||
|
||||
@@ -49,6 +49,23 @@ describe("buildCommitMessagePrompt", () => {
|
||||
|
||||
expect(result.prompt).toContain("Branch: (detached)");
|
||||
});
|
||||
|
||||
it("includes policy instructions", () => {
|
||||
const result = buildCommitMessagePrompt({
|
||||
branch: "main",
|
||||
stagedSummary: "M a.ts",
|
||||
stagedPatch: "diff",
|
||||
includeBranch: false,
|
||||
policy: {
|
||||
kind: "custom",
|
||||
commitInstructions: "Use a terse repository-specific subject.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Additional instructions:");
|
||||
expect(result.prompt).toContain("Use a terse repository-specific subject.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPrContentPrompt", () => {
|
||||
@@ -69,6 +86,30 @@ describe("buildPrContentPrompt", () => {
|
||||
expect(result.prompt).toContain("3 files changed");
|
||||
expect(result.prompt).toContain("Diff patch:");
|
||||
expect(result.prompt).toContain("export function login()");
|
||||
expect(result.prompt).toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
|
||||
it("follows a repository PR template instead of the default body headings", () => {
|
||||
const result = buildPrContentPrompt({
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/auth",
|
||||
commitSummary: "feat: add login page",
|
||||
diffSummary: "3 files changed",
|
||||
diffPatch: "diff",
|
||||
changeRequestTemplate: "<!-- remove me -->\n## What changed\n\n## Verification",
|
||||
policy: {
|
||||
kind: "custom",
|
||||
changeRequestInstructions: "Keep the title in sentence case.",
|
||||
inferRepositoryConventions: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.prompt).toContain("Keep the title in sentence case.");
|
||||
expect(result.prompt).toContain("follow the repository change request template structure");
|
||||
expect(result.prompt).toContain("drop HTML comments from the template");
|
||||
expect(result.prompt).toContain("Repository change request template:");
|
||||
expect(result.prompt).toContain("<!-- remove me -->\n## What changed\n\n## Verification");
|
||||
expect(result.prompt).not.toContain("include headings '## Summary' and '## Testing'");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -25,12 +25,12 @@ export interface CommitMessagePromptInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
includeBranch: boolean;
|
||||
includeBranch?: boolean;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
const wantsBranch = input.includeBranch;
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
@@ -76,7 +76,7 @@ export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PR content
|
||||
// Change request content
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface PrContentPromptInput {
|
||||
@@ -85,19 +85,34 @@ export interface PrContentPromptInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
changeRequestTemplate?: string | undefined;
|
||||
policy?: TextGenerationPolicy | undefined;
|
||||
}
|
||||
|
||||
export function buildPrContentPrompt(input: PrContentPromptInput) {
|
||||
const changeRequestTemplate = input.changeRequestTemplate?.trim();
|
||||
const bodyRules = changeRequestTemplate
|
||||
? [
|
||||
"- body must be markdown and follow the repository change request template structure",
|
||||
"- fill in the template sections appropriately for this change",
|
||||
"- drop HTML comments from the template in the generated body",
|
||||
"- keep the template's markdown structure",
|
||||
]
|
||||
: [
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
];
|
||||
const prompt = [
|
||||
"You write GitHub pull request content.",
|
||||
"You write source control change request content.",
|
||||
"Return a JSON object with keys: title, body.",
|
||||
"Rules:",
|
||||
"- title should be concise and specific",
|
||||
"- body must be markdown and include headings '## Summary' and '## Testing'",
|
||||
"- under Summary, provide short bullet points",
|
||||
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
|
||||
...bodyRules,
|
||||
...policyInstruction(input.policy?.changeRequestInstructions),
|
||||
...(changeRequestTemplate
|
||||
? ["", "Repository change request template:", limitSection(changeRequestTemplate, 8_000)]
|
||||
: []),
|
||||
"",
|
||||
`Base branch: ${input.baseBranch}`,
|
||||
`Head branch: ${input.headBranch}`,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
|
||||
import { resolveAvailableEditorsForConfig } from "./ws.ts";
|
||||
|
||||
it.effect("does not block server config when editor discovery never resolves", () =>
|
||||
Effect.gen(function* () {
|
||||
const discoveryInterrupted = yield* Deferred.make<void>();
|
||||
const responseFiber = yield* resolveAvailableEditorsForConfig(
|
||||
Effect.never.pipe(
|
||||
Effect.onInterrupt(() => Deferred.succeed(discoveryInterrupted, undefined)),
|
||||
),
|
||||
).pipe(Effect.forkChild);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(5));
|
||||
|
||||
const availableEditors = yield* Fiber.join(responseFiber);
|
||||
yield* Deferred.await(discoveryInterrupted);
|
||||
assert.deepEqual(availableEditors, []);
|
||||
}),
|
||||
);
|
||||
+13
-1
@@ -133,6 +133,16 @@ import * as SessionStore from "./auth/SessionStore.ts";
|
||||
import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
|
||||
const EDITOR_DISCOVERY_TIMEOUT = Duration.seconds(5);
|
||||
|
||||
export const resolveAvailableEditorsForConfig = <A, E, R>(
|
||||
discovery: Effect.Effect<ReadonlyArray<A>, E, R>,
|
||||
) =>
|
||||
discovery.pipe(
|
||||
Effect.timeoutOption(EDITOR_DISCOVERY_TIMEOUT),
|
||||
Effect.map(Option.getOrElse(() => [])),
|
||||
);
|
||||
|
||||
function unexpectedCompatibilityError(error: never): never {
|
||||
throw new Error(`Unhandled compatibility error: ${String(error)}`);
|
||||
}
|
||||
@@ -606,7 +616,9 @@ const makeWsRpcLayer = (
|
||||
keybindings: keybindingsConfig.keybindings,
|
||||
issues: keybindingsConfig.issues,
|
||||
providers,
|
||||
availableEditors: yield* externalLauncher.resolveAvailableEditors(),
|
||||
availableEditors: yield* resolveAvailableEditorsForConfig(
|
||||
externalLauncher.resolveAvailableEditors(),
|
||||
),
|
||||
observability: {
|
||||
logsDirectoryPath: config.logsDir,
|
||||
localTracingEnabled: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.28",
|
||||
"version": "0.0.29",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -11,6 +11,51 @@ export function formatAppDisplayName(input: {
|
||||
return `${input.baseName} (${input.stageLabel})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the sidebar v2 beta is on by default for a build stage.
|
||||
*
|
||||
* Nightly and local dev opt in; Alpha and Latest stay on v1. This is resolved
|
||||
* from the client's own stage label rather than the connected server's version:
|
||||
* v2 only exists in the client, so a stable client on a nightly server has
|
||||
* nothing to turn on.
|
||||
*/
|
||||
export function resolveSidebarV2Default(stageLabel: string): boolean {
|
||||
const stage = stageLabel.trim().toLowerCase();
|
||||
return stage === "nightly" || stage === "dev";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolved sidebar v2 state: an explicit choice if the user has made one,
|
||||
* otherwise the default for this build stage.
|
||||
*
|
||||
* A stored `enabled: true` counts as an explicit choice even without the
|
||||
* companion flag. `true` was never the schema default, so it can only have come
|
||||
* from the Settings → Beta toggle — settings written before that flag existed
|
||||
* would otherwise lose the opt-in and drop such users back to v1 on production.
|
||||
* Mirrors how `normalizeDesktopSettingsDocument` treats a legacy stored
|
||||
* `updateChannel: "nightly"` as user-configured.
|
||||
*
|
||||
* `settingsHydrated` guards the startup window: client settings load
|
||||
* asynchronously and the pre-hydration snapshot is just the schema defaults, so
|
||||
* resolving against it would mount one sidebar and swap it out a tick later,
|
||||
* remounting the tree. While hydrating, hold v1 — where both paths already
|
||||
* start.
|
||||
*/
|
||||
export function resolveSidebarV2Enabled(input: {
|
||||
readonly enabled: boolean;
|
||||
readonly configuredByUser: boolean;
|
||||
readonly settingsHydrated: boolean;
|
||||
readonly stageLabel: string;
|
||||
}): boolean {
|
||||
if (!input.settingsHydrated) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return input.configuredByUser || input.enabled
|
||||
? input.enabled
|
||||
: resolveSidebarV2Default(input.stageLabel);
|
||||
}
|
||||
|
||||
export function resolveServerBackedAppStageLabel(input: {
|
||||
readonly primaryServerVersion: string | null | undefined;
|
||||
readonly fallbackStageLabel: string;
|
||||
|
||||
@@ -2,6 +2,8 @@ import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
resolveServerBackedAppDisplayName,
|
||||
resolveServerBackedAppStageLabel,
|
||||
resolveSidebarV2Default,
|
||||
resolveSidebarV2Enabled,
|
||||
} from "./branding.logic";
|
||||
|
||||
const originalWindow = globalThis.window;
|
||||
@@ -114,3 +116,74 @@ describe("branding logic", () => {
|
||||
).toBe("T3 Code (Alpha)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Default", () => {
|
||||
it.each(["Nightly", "Dev", "nightly", " dev "])("enables the beta for %s builds", (stage) => {
|
||||
expect(resolveSidebarV2Default(stage)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["Alpha", "Latest", ""])("leaves the beta off for %s builds", (stage) => {
|
||||
expect(resolveSidebarV2Default(stage)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarV2Enabled", () => {
|
||||
const hydrated = { settingsHydrated: true } as const;
|
||||
|
||||
it.each(["Alpha", "Latest"])(
|
||||
"keeps a legacy opt-in on %s builds even without the companion flag",
|
||||
(stageLabel) => {
|
||||
// `true` was never the schema default, so it can only be an explicit
|
||||
// opt-in from settings written before `sidebarV2ConfiguredByUser` existed.
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: true,
|
||||
configuredByUser: false,
|
||||
stageLabel,
|
||||
}),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("applies the stage default when the beta was never enabled or configured", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: false,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: false,
|
||||
stageLabel: "Latest",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("honors an explicit opt-out over the stage default", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
...hydrated,
|
||||
enabled: false,
|
||||
configuredByUser: true,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("holds v1 until settings hydrate so the sidebar does not remount", () => {
|
||||
expect(
|
||||
resolveSidebarV2Enabled({
|
||||
enabled: true,
|
||||
configuredByUser: true,
|
||||
settingsHydrated: false,
|
||||
stageLabel: "Nightly",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import { useActivePreviewSessions } from "~/previewStateStore";
|
||||
import { readPreviewAnnotationTheme } from "./annotationTheme";
|
||||
import { useBrowserPointerStore } from "./browserPointerStore";
|
||||
import { HostedBrowserWebview } from "./HostedBrowserWebview";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
export function ElectronBrowserHost() {
|
||||
const { resolvedTheme } = useTheme();
|
||||
@@ -23,6 +24,11 @@ export function ElectronBrowserHost() {
|
||||
? Object.values(previewState.sessions).map((snapshot) => ({
|
||||
threadRef,
|
||||
snapshot,
|
||||
runtimeTabId: previewRuntimeTabId(
|
||||
threadRef,
|
||||
previewState.serverEpoch,
|
||||
snapshot.tabId,
|
||||
),
|
||||
zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
|
||||
}))
|
||||
: [];
|
||||
@@ -74,13 +80,14 @@ export function ElectronBrowserHost() {
|
||||
if (!isElectron) return null;
|
||||
return (
|
||||
<div className="contents" data-electron-browser-host>
|
||||
{sessions.map(({ threadRef, snapshot, zoomFactor }) => {
|
||||
{sessions.map(({ threadRef, snapshot, runtimeTabId, zoomFactor }) => {
|
||||
const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
|
||||
return (
|
||||
<HostedBrowserWebview
|
||||
key={snapshot.tabId}
|
||||
key={runtimeTabId}
|
||||
threadRef={threadRef}
|
||||
tabId={snapshot.tabId}
|
||||
runtimeTabId={runtimeTabId}
|
||||
initialUrl={url}
|
||||
viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
|
||||
zoomFactor={zoomFactor}
|
||||
|
||||
@@ -9,7 +9,11 @@ import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
|
||||
import { browserViewportSettingKey, resolveBrowserViewportLayout } from "./browserViewportLayout";
|
||||
import {
|
||||
browserViewportSettingKey,
|
||||
resolveBrowserViewportLayout,
|
||||
resolveFittedBrowserViewport,
|
||||
} from "./browserViewportLayout";
|
||||
import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
|
||||
import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
|
||||
import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
|
||||
@@ -40,11 +44,12 @@ declare global {
|
||||
export function HostedBrowserWebview(props: {
|
||||
readonly threadRef: ScopedThreadRef;
|
||||
readonly tabId: string;
|
||||
readonly runtimeTabId: string;
|
||||
readonly initialUrl: string | null;
|
||||
readonly viewport: PreviewViewportSetting;
|
||||
readonly zoomFactor: number;
|
||||
}) {
|
||||
const { threadRef, tabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const { threadRef, tabId, runtimeTabId, initialUrl, viewport, zoomFactor } = props;
|
||||
const config = usePreviewWebviewConfig(threadRef.environmentId);
|
||||
const [initialSrc] = useState(() => initialUrl ?? "about:blank");
|
||||
const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
|
||||
@@ -54,27 +59,28 @@ export function HostedBrowserWebview(props: {
|
||||
const [aspectRatioLocked, setAspectRatioLocked] = useState(false);
|
||||
const presentation = useBrowserSurfaceStore(
|
||||
useShallow((state) => {
|
||||
const current = state.byTabId[tabId];
|
||||
const current = state.byTabId[runtimeTabId];
|
||||
return {
|
||||
content: current?.content ?? null,
|
||||
cornerRadius: current?.cornerRadius ?? 0,
|
||||
fitSourceContent: current?.fitSourceContent ?? false,
|
||||
fittedSourceContent: current?.fittedSourceContent ?? null,
|
||||
rect: resolveBrowserSurfacePanelRect(state.byTabId, tabId),
|
||||
rect: resolveBrowserSurfacePanelRect(state.byTabId, runtimeTabId),
|
||||
visible: current?.visible ?? false,
|
||||
};
|
||||
}),
|
||||
);
|
||||
usePreviewBridge({ threadRef, tabId });
|
||||
usePreviewBridge({ threadRef, tabId, runtimeTabId });
|
||||
|
||||
useEffect(() => {
|
||||
crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
|
||||
const lease = acquireDesktopTab(tabId);
|
||||
const lease = acquireDesktopTab(runtimeTabId);
|
||||
tabLeaseRef.current = lease;
|
||||
return () => {
|
||||
if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
|
||||
lease.release();
|
||||
};
|
||||
}, [tabId]);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const [webviewGeneration, setWebviewGeneration] = useState(0);
|
||||
const [recoverySrc, setRecoverySrc] = useState(initialSrc);
|
||||
@@ -107,7 +113,7 @@ export function HostedBrowserWebview(props: {
|
||||
if (disposed || webviewRef.current !== webview) return;
|
||||
const webContentsId = webview.getWebContentsId();
|
||||
if (Number.isInteger(webContentsId) && webContentsId > 0) {
|
||||
await bridge.registerWebview(tabId, webContentsId);
|
||||
await bridge.registerWebview(runtimeTabId, webContentsId);
|
||||
}
|
||||
} catch {
|
||||
// did-attach/dom-ready will retry if the guest was not ready yet.
|
||||
@@ -138,7 +144,7 @@ export function HostedBrowserWebview(props: {
|
||||
webview.removeEventListener("dom-ready", register);
|
||||
webview.removeEventListener("render-process-gone", recoverGuest);
|
||||
};
|
||||
}, [config, initialSrc, tabId, webviewGeneration]);
|
||||
}, [config, initialSrc, runtimeTabId, webviewGeneration]);
|
||||
|
||||
const active = presentation.visible && presentation.rect !== null;
|
||||
const lastRect = presentation.rect;
|
||||
@@ -152,13 +158,22 @@ export function HostedBrowserWebview(props: {
|
||||
const handleAspectRatioChange = useCallback((aspectRatio: number | null) => {
|
||||
setAspectRatioLocked(aspectRatio !== null);
|
||||
}, []);
|
||||
const hiddenContentSize = presentation.content
|
||||
? {
|
||||
width: presentation.content.width / presentation.content.scale,
|
||||
height: presentation.content.height / presentation.content.scale,
|
||||
}
|
||||
: null;
|
||||
const hiddenSize =
|
||||
viewport._tag !== "fill"
|
||||
? {
|
||||
width: viewport.width * normalizedZoomFactor,
|
||||
height: viewport.height * normalizedZoomFactor,
|
||||
}
|
||||
: { width: lastRect?.width ?? 1280, height: lastRect?.height ?? 800 };
|
||||
: {
|
||||
width: hiddenContentSize?.width ?? lastRect?.width ?? 1280,
|
||||
height: hiddenContentSize?.height ?? lastRect?.height ?? 800,
|
||||
};
|
||||
const containerSize = active && lastRect ? lastRect : hiddenSize;
|
||||
const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
|
||||
const {
|
||||
@@ -169,7 +184,7 @@ export function HostedBrowserWebview(props: {
|
||||
handleResizePointerDown,
|
||||
layout: viewportLayout,
|
||||
} = useBrowserViewportResize({
|
||||
tabId,
|
||||
tabId: runtimeTabId,
|
||||
viewport,
|
||||
zoomFactor,
|
||||
containerSize,
|
||||
@@ -178,31 +193,11 @@ export function HostedBrowserWebview(props: {
|
||||
});
|
||||
const fittedSourceViewport =
|
||||
presentation.fitSourceContent && lastRect
|
||||
? presentation.fittedSourceContent
|
||||
? {
|
||||
_tag: "freeform" as const,
|
||||
width: Math.max(
|
||||
1,
|
||||
Math.round(
|
||||
presentation.fittedSourceContent.width /
|
||||
presentation.fittedSourceContent.scale /
|
||||
normalizedZoomFactor,
|
||||
),
|
||||
),
|
||||
height: Math.max(
|
||||
1,
|
||||
Math.round(
|
||||
presentation.fittedSourceContent.height /
|
||||
presentation.fittedSourceContent.scale /
|
||||
normalizedZoomFactor,
|
||||
),
|
||||
),
|
||||
}
|
||||
: {
|
||||
_tag: "freeform" as const,
|
||||
width: viewport._tag === "fill" ? 1280 : viewport.width,
|
||||
height: viewport._tag === "fill" ? 800 : viewport.height,
|
||||
}
|
||||
? resolveFittedBrowserViewport(
|
||||
viewport,
|
||||
presentation.fittedSourceContent,
|
||||
normalizedZoomFactor,
|
||||
)
|
||||
: null;
|
||||
const layout =
|
||||
fittedSourceViewport && lastRect
|
||||
@@ -212,7 +207,7 @@ export function HostedBrowserWebview(props: {
|
||||
const syncContentPresentation = useCallback(() => {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
useBrowserSurfaceStore.getState().presentContent(tabId, {
|
||||
useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
|
||||
x: layout.viewportX,
|
||||
y: layout.viewportY,
|
||||
width: layout.viewportWidth,
|
||||
@@ -221,7 +216,7 @@ export function HostedBrowserWebview(props: {
|
||||
scrollLeft: wrapper.scrollLeft,
|
||||
scrollTop: wrapper.scrollTop,
|
||||
});
|
||||
}, [layout, tabId]);
|
||||
}, [layout, runtimeTabId]);
|
||||
|
||||
useEffect(() => {
|
||||
const frameId = window.requestAnimationFrame(syncContentPresentation);
|
||||
@@ -232,7 +227,7 @@ export function HostedBrowserWebview(props: {
|
||||
const wrapper = wrapperRef.current;
|
||||
if (!wrapper) return;
|
||||
wrapper.scrollTo({ left: 0, top: 0 });
|
||||
}, [tabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
}, [runtimeTabId, viewport._tag, viewportHeight, viewportWidth]);
|
||||
|
||||
if (!config) return null;
|
||||
|
||||
@@ -249,7 +244,7 @@ export function HostedBrowserWebview(props: {
|
||||
className="fixed overflow-hidden bg-muted/35"
|
||||
style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
|
||||
onScroll={syncContentPresentation}
|
||||
data-preview-viewport={tabId}
|
||||
data-preview-viewport={runtimeTabId}
|
||||
>
|
||||
<div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
|
||||
{deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
|
||||
@@ -268,7 +263,8 @@ export function HostedBrowserWebview(props: {
|
||||
partition={config.partition}
|
||||
webpreferences={config.webPreferences}
|
||||
{...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
|
||||
data-preview-tab={tabId}
|
||||
data-preview-tab={runtimeTabId}
|
||||
data-preview-server-tab={tabId}
|
||||
data-preview-viewport-mode={effectiveViewport._tag}
|
||||
data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
|
||||
data-preview-css-width={
|
||||
|
||||
@@ -89,10 +89,13 @@ import {
|
||||
BROWSER_RECORDING_FIRST_FRAME_SIZE_TIMEOUT_MS,
|
||||
BROWSER_RECORDING_STARTUP_SETTLE_TIMEOUT_MS,
|
||||
BrowserRecordingConflictError,
|
||||
findActiveBrowserRecordingRuntimeTabId,
|
||||
readActiveBrowserRecordingTabIds,
|
||||
readActiveBrowserRecordingTargets,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from "./browserRecording";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
class FakeMediaRecorder {
|
||||
static isTypeSupported(): boolean {
|
||||
@@ -363,6 +366,46 @@ describe("browser recording", () => {
|
||||
expect(save).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("keeps a recording reachable through its runtime id after a server epoch changes", async () => {
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("environment-recording"),
|
||||
threadId: ThreadId.make("thread-recording-scoped"),
|
||||
};
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, "epoch-a", "tab_1");
|
||||
surfaceState.byTabId = {
|
||||
[runtimeTabId]: {
|
||||
visible: false,
|
||||
rect: { x: 0, y: 0, width: 1280, height: 800 },
|
||||
content: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 1280,
|
||||
height: 800,
|
||||
scale: 1,
|
||||
scrollLeft: 0,
|
||||
scrollTop: 0,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
await startBrowserRecording(runtimeTabId, threadRef, "tab_1");
|
||||
|
||||
expect(startScreencast).toHaveBeenCalledWith(runtimeTabId);
|
||||
expect(readActiveBrowserRecordingTabIds(threadRef)).toEqual(new Set([runtimeTabId]));
|
||||
expect(readActiveBrowserRecordingTargets(threadRef)).toEqual([
|
||||
{ runtimeTabId, serverTabId: "tab_1" },
|
||||
]);
|
||||
expect(findActiveBrowserRecordingRuntimeTabId(threadRef, "tab_1")).toBe(runtimeTabId);
|
||||
|
||||
const replacementRuntimeTabId = previewRuntimeTabId(threadRef, "epoch-b", "tab_1");
|
||||
await expect(
|
||||
startBrowserRecording(replacementRuntimeTabId, threadRef, "tab_1"),
|
||||
).rejects.toBeInstanceOf(BrowserRecordingConflictError);
|
||||
expect(startScreencast).toHaveBeenCalledTimes(1);
|
||||
|
||||
await stopBrowserRecording(runtimeTabId);
|
||||
});
|
||||
|
||||
it("does not report success for a second start while the first is still starting", async () => {
|
||||
let finishStartingScreencast: (() => void) | undefined;
|
||||
startScreencast.mockImplementationOnce(async (tabId: string) => {
|
||||
|
||||
@@ -82,7 +82,10 @@ type BrowserRecordingLifecycle =
|
||||
};
|
||||
|
||||
interface ActiveRecording {
|
||||
/** Desktop-scoped identity used by capture and surface stores. */
|
||||
readonly tabId: string;
|
||||
/** Server-local identity returned by preview automation tools. */
|
||||
readonly serverTabId: string;
|
||||
readonly threadRef: ScopedThreadRef | null;
|
||||
readonly canvas: HTMLCanvasElement;
|
||||
readonly context: CanvasRenderingContext2D;
|
||||
@@ -99,6 +102,11 @@ interface ActiveRecording {
|
||||
lifecycle: BrowserRecordingLifecycle;
|
||||
}
|
||||
|
||||
export interface ActiveBrowserRecordingTarget {
|
||||
readonly runtimeTabId: string;
|
||||
readonly serverTabId: string;
|
||||
}
|
||||
|
||||
interface ActiveBrowserRecordingIndex {
|
||||
readonly tabIds: ReadonlySet<string>;
|
||||
}
|
||||
@@ -131,6 +139,28 @@ export function readActiveBrowserRecordingTabIds(threadRef?: ScopedThreadRef): R
|
||||
return tabIds;
|
||||
}
|
||||
|
||||
export function readActiveBrowserRecordingTargets(
|
||||
threadRef: ScopedThreadRef,
|
||||
): ReadonlyArray<ActiveBrowserRecordingTarget> {
|
||||
return Array.from(activeRecordings.values()).flatMap((recording) =>
|
||||
recording.threadRef?.environmentId === threadRef.environmentId &&
|
||||
recording.threadRef.threadId === threadRef.threadId
|
||||
? [{ runtimeTabId: recording.tabId, serverTabId: recording.serverTabId }]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
export function findActiveBrowserRecordingRuntimeTabId(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverTabId: string,
|
||||
): string | null {
|
||||
return (
|
||||
readActiveBrowserRecordingTargets(threadRef).find(
|
||||
(recording) => recording.serverTabId === serverTabId,
|
||||
)?.runtimeTabId ?? null
|
||||
);
|
||||
}
|
||||
|
||||
const preferredMimeType = (): string => {
|
||||
const candidates = ["video/mp4;codecs=avc1.42E01E", "video/webm;codecs=vp9", "video/webm"];
|
||||
return candidates.find((candidate) => MediaRecorder.isTypeSupported(candidate)) ?? "video/webm";
|
||||
@@ -283,6 +313,7 @@ const isStartupWaitTimeout = (error: unknown): error is BrowserRecordingOperatio
|
||||
export async function startBrowserRecording(
|
||||
tabId: string,
|
||||
threadRef: ScopedThreadRef | null = null,
|
||||
serverTabId = tabId,
|
||||
): Promise<string> {
|
||||
const bridge = previewBridge;
|
||||
if (!bridge) throw new BrowserRecordingUnavailableError({ tabId });
|
||||
@@ -296,6 +327,14 @@ export async function startBrowserRecording(
|
||||
activeTabId: activeRecording.tabId,
|
||||
});
|
||||
}
|
||||
const activeLogicalRecording =
|
||||
threadRef === null ? null : findActiveBrowserRecordingRuntimeTabId(threadRef, serverTabId);
|
||||
if (activeLogicalRecording !== null) {
|
||||
throw new BrowserRecordingConflictError({
|
||||
requestedTabId: tabId,
|
||||
activeTabId: activeLogicalRecording,
|
||||
});
|
||||
}
|
||||
const surface = useBrowserSurfaceStore.getState().byTabId[tabId];
|
||||
const recordingSize = surface?.content ?? surface?.rect;
|
||||
const canvas = document.createElement("canvas");
|
||||
@@ -321,6 +360,7 @@ export async function startBrowserRecording(
|
||||
});
|
||||
const recording: ActiveRecording = {
|
||||
tabId,
|
||||
serverTabId,
|
||||
threadRef,
|
||||
canvas,
|
||||
context,
|
||||
|
||||
@@ -86,7 +86,7 @@ describe("browserSurfaceStore", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("uses the live panel rect for a hidden background tab", () => {
|
||||
it("keeps a hidden background tab on its own last rect", () => {
|
||||
const staleRect = { x: 0, y: 0, width: 500, height: 700 };
|
||||
const liveRect = { x: 10, y: 20, width: 900, height: 640 };
|
||||
expect(
|
||||
@@ -115,7 +115,7 @@ describe("browserSurfaceStore", () => {
|
||||
},
|
||||
"hidden",
|
||||
),
|
||||
).toEqual(liveRect);
|
||||
).toEqual(staleRect);
|
||||
});
|
||||
|
||||
it("ignores updates and releases from a stale surface lease", () => {
|
||||
|
||||
@@ -52,19 +52,7 @@ export function resolveBrowserSurfacePanelRect(
|
||||
tabId: string,
|
||||
): BrowserSurfaceRect | null {
|
||||
const current = byTabId[tabId];
|
||||
if (current?.visible && current.rect) return current.rect;
|
||||
|
||||
let latestVisible: BrowserSurfacePresentation | undefined;
|
||||
for (const presentation of Object.values(byTabId)) {
|
||||
if (
|
||||
presentation.visible &&
|
||||
presentation.rect &&
|
||||
(!latestVisible || presentation.updatedAt > latestVisible.updatedAt)
|
||||
) {
|
||||
latestVisible = presentation;
|
||||
}
|
||||
}
|
||||
return latestVisible?.rect ?? current?.rect ?? null;
|
||||
return current?.rect ?? null;
|
||||
}
|
||||
|
||||
const rectEquals = (left: BrowserSurfaceRect | null, right: BrowserSurfaceRect): boolean =>
|
||||
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
|
||||
import {
|
||||
BROWSER_VIEWPORT_COMMIT_TIMEOUT_MS,
|
||||
commitBrowserViewportChange,
|
||||
runBrowserViewportMutation,
|
||||
subscribeBrowserViewportChange,
|
||||
} from "./browserViewportActions";
|
||||
|
||||
@@ -71,6 +72,33 @@ describe("browserViewportActions", () => {
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("serializes background mutations with visible viewport commits", async () => {
|
||||
let releaseBackground: (() => void) | undefined;
|
||||
const backgroundPending = new Promise<void>((resolve) => {
|
||||
releaseBackground = resolve;
|
||||
});
|
||||
const calls: string[] = [];
|
||||
const background = runBrowserViewportMutation("tab-shared", async () => {
|
||||
calls.push("background");
|
||||
await backgroundPending;
|
||||
});
|
||||
const unsubscribe = subscribeBrowserViewportChange("tab-shared", async () => {
|
||||
calls.push("visible");
|
||||
});
|
||||
const visible = commitBrowserViewportChange("tab-shared", {
|
||||
_tag: "freeform",
|
||||
width: 900,
|
||||
height: 700,
|
||||
});
|
||||
|
||||
await vi.waitFor(() => expect(calls).toEqual(["background"]));
|
||||
releaseBackground?.();
|
||||
await Promise.all([background, visible]);
|
||||
|
||||
expect(calls).toEqual(["background", "visible"]);
|
||||
unsubscribe();
|
||||
});
|
||||
|
||||
it("does not let a timed-out handler overtake a newer viewport commit", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
|
||||
@@ -15,6 +15,41 @@ export class BrowserViewportCommitTimeoutError extends Error {
|
||||
const handlers = new Map<string, BrowserViewportHandler>();
|
||||
const commitTails = new Map<string, Promise<void>>();
|
||||
|
||||
const queueBrowserViewportMutation = <A>(
|
||||
tabId: string,
|
||||
start: () => Promise<A>,
|
||||
): {
|
||||
readonly started: Promise<{ readonly operation: Promise<A> }>;
|
||||
readonly execution: Promise<A>;
|
||||
} => {
|
||||
const previous = commitTails.get(tabId) ?? Promise.resolve();
|
||||
const started = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => ({
|
||||
operation: Promise.resolve().then(start),
|
||||
}));
|
||||
const execution = started.then(({ operation }) => operation);
|
||||
const tail = execution.then(() => undefined);
|
||||
commitTails.set(tabId, tail);
|
||||
const clear = () => {
|
||||
if (commitTails.get(tabId) === tail) commitTails.delete(tabId);
|
||||
};
|
||||
void tail.then(clear, clear);
|
||||
return { started, execution };
|
||||
};
|
||||
|
||||
/**
|
||||
* Serializes every server-side viewport mutation for one desktop runtime tab.
|
||||
* Both visible UI commits and background automation use this queue so a
|
||||
* compensating rollback cannot overtake a newer resize.
|
||||
*/
|
||||
export function runBrowserViewportMutation<A>(
|
||||
tabId: string,
|
||||
mutation: () => Promise<A>,
|
||||
): Promise<A> {
|
||||
return queueBrowserViewportMutation(tabId, mutation).execution;
|
||||
}
|
||||
|
||||
const runHandlerWithTimeout = (tabId: string, operation: Promise<void>): Promise<void> => {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<never>((_resolve, reject) => {
|
||||
@@ -42,25 +77,14 @@ export function commitBrowserViewportChange(
|
||||
tabId: string,
|
||||
setting: PreviewViewportSetting,
|
||||
): Promise<void> {
|
||||
const previous = commitTails.get(tabId) ?? Promise.resolve();
|
||||
const started = previous
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
const handler = handlers.get(tabId);
|
||||
const operation = handler
|
||||
? Promise.resolve().then(() => handler(setting))
|
||||
: Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
|
||||
return { operation };
|
||||
});
|
||||
// The queue follows the real handler lifetime, not the caller-facing timeout.
|
||||
// A slow commit therefore cannot time out, release the queue, and overwrite a
|
||||
// newer viewport after that newer request has already completed.
|
||||
const execution = started.then(({ operation }) => operation);
|
||||
const { started } = queueBrowserViewportMutation(tabId, () => {
|
||||
const handler = handlers.get(tabId);
|
||||
return handler
|
||||
? handler(setting)
|
||||
: Promise.reject(new Error(`No visible browser viewport handler for tab ${tabId}`));
|
||||
});
|
||||
// The queue follows the real handler lifetime, while the caller-facing
|
||||
// timeout starts only once this commit reaches the front of that queue.
|
||||
const result = started.then(({ operation }) => runHandlerWithTimeout(tabId, operation));
|
||||
commitTails.set(tabId, execution);
|
||||
const clear = () => {
|
||||
if (commitTails.get(tabId) === execution) commitTails.delete(tabId);
|
||||
};
|
||||
void execution.then(clear, clear);
|
||||
return result;
|
||||
}
|
||||
@@ -4,11 +4,27 @@ import {
|
||||
resizeBrowserViewportFromRail,
|
||||
resizeFreeformViewport,
|
||||
resolveBrowserDeviceViewportLayout,
|
||||
resolveFittedBrowserViewport,
|
||||
resolveBrowserViewportLayout,
|
||||
resolveResponsiveBrowserViewportSize,
|
||||
} from "./browserViewportLayout";
|
||||
|
||||
describe("resolveBrowserViewportLayout", () => {
|
||||
it("uses the current fixed viewport instead of stale fitted source dimensions", () => {
|
||||
expect(
|
||||
resolveFittedBrowserViewport(
|
||||
{ _tag: "freeform", width: 900, height: 600 },
|
||||
{ width: 1280, height: 800, scale: 1 },
|
||||
),
|
||||
).toEqual({ _tag: "freeform", width: 900, height: 600 });
|
||||
});
|
||||
|
||||
it("preserves the last logical viewport when fitting a fill-mode surface", () => {
|
||||
expect(
|
||||
resolveFittedBrowserViewport({ _tag: "fill" }, { width: 320, height: 200, scale: 0.25 }),
|
||||
).toEqual({ _tag: "freeform", width: 1280, height: 800 });
|
||||
});
|
||||
|
||||
it("fills the available surface in fill mode", () => {
|
||||
expect(resolveBrowserViewportLayout({ width: 700, height: 500 }, { _tag: "fill" })).toEqual({
|
||||
canvasWidth: 700,
|
||||
|
||||
@@ -40,6 +40,33 @@ export const browserViewportSettingKey = (setting: PreviewViewportSetting): stri
|
||||
const normalizeZoomFactor = (zoomFactor: number): number =>
|
||||
Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
|
||||
|
||||
export function resolveFittedBrowserViewport(
|
||||
setting: PreviewViewportSetting,
|
||||
sourceContent: {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly scale: number;
|
||||
} | null,
|
||||
zoomFactor = 1,
|
||||
): Exclude<PreviewViewportSetting, { readonly _tag: "fill" }> {
|
||||
if (setting._tag !== "fill") return setting;
|
||||
const normalizedZoomFactor = normalizeZoomFactor(zoomFactor);
|
||||
if (sourceContent) {
|
||||
return {
|
||||
_tag: "freeform",
|
||||
width: Math.max(
|
||||
1,
|
||||
Math.round(sourceContent.width / sourceContent.scale / normalizedZoomFactor),
|
||||
),
|
||||
height: Math.max(
|
||||
1,
|
||||
Math.round(sourceContent.height / sourceContent.scale / normalizedZoomFactor),
|
||||
),
|
||||
};
|
||||
}
|
||||
return { _tag: "freeform", width: 1280, height: 800 };
|
||||
}
|
||||
|
||||
export function resolveBrowserDeviceViewportArea(container: {
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const { closeTab, createTab, stopBrowserRecording } = vi.hoisted(() => ({
|
||||
@@ -15,6 +16,7 @@ vi.mock("./browserRecording", () => ({
|
||||
}));
|
||||
|
||||
import { acquireDesktopTab } from "./desktopTabLifetime";
|
||||
import { previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
describe("desktopTabLifetime", () => {
|
||||
beforeEach(() => {
|
||||
@@ -55,6 +57,39 @@ describe("desktopTabLifetime", () => {
|
||||
expect(ready).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps identical server tab ids from two environments in separate desktop slots", async () => {
|
||||
vi.useFakeTimers();
|
||||
createTab.mockResolvedValue(undefined);
|
||||
const tabA = previewRuntimeTabId(
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
},
|
||||
"epoch-a",
|
||||
"tab_1",
|
||||
);
|
||||
const tabB = previewRuntimeTabId(
|
||||
{
|
||||
environmentId: EnvironmentId.make("environment-b"),
|
||||
threadId: ThreadId.make("thread-b"),
|
||||
},
|
||||
"epoch-b",
|
||||
"tab_1",
|
||||
);
|
||||
|
||||
const first = acquireDesktopTab(tabA);
|
||||
const second = acquireDesktopTab(tabB);
|
||||
await Promise.all([first.ready, second.ready]);
|
||||
|
||||
expect(createTab).toHaveBeenCalledWith(tabA);
|
||||
expect(createTab).toHaveBeenCalledWith(tabB);
|
||||
expect(createTab).toHaveBeenCalledTimes(2);
|
||||
|
||||
first.release();
|
||||
second.release();
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
});
|
||||
|
||||
it("stops recording before closing the final desktop tab lease", async () => {
|
||||
vi.useFakeTimers();
|
||||
let resolveStop: (() => void) | undefined;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { isCurrentPreviewRuntimeTab, previewRuntimeTabId } from "./previewRuntimeTabId";
|
||||
|
||||
describe("previewRuntimeTabId", () => {
|
||||
it("scopes process-local tab ids to their environment, thread, and server epoch", () => {
|
||||
const base = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId(
|
||||
{ ...base, environmentId: EnvironmentId.make("environment-b") },
|
||||
"epoch-a",
|
||||
"tab_1",
|
||||
),
|
||||
);
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId({ ...base, threadId: ThreadId.make("thread-b") }, "epoch-a", "tab_1"),
|
||||
);
|
||||
expect(previewRuntimeTabId(base, "epoch-a", "tab_1")).not.toBe(
|
||||
previewRuntimeTabId(base, "epoch-b", "tab_1"),
|
||||
);
|
||||
});
|
||||
|
||||
it("is stable for the same runtime tab", () => {
|
||||
const ref = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
expect(previewRuntimeTabId(ref, null, "tab_1")).toBe(previewRuntimeTabId(ref, null, "tab_1"));
|
||||
});
|
||||
|
||||
it("rejects a pinned operation target after the server epoch changes", () => {
|
||||
const ref = {
|
||||
environmentId: EnvironmentId.make("environment-a"),
|
||||
threadId: ThreadId.make("thread-a"),
|
||||
};
|
||||
const runtimeTabId = previewRuntimeTabId(ref, "epoch-a", "tab_1");
|
||||
|
||||
expect(isCurrentPreviewRuntimeTab(ref, "epoch-a", "tab_1", runtimeTabId)).toBe(true);
|
||||
expect(isCurrentPreviewRuntimeTab(ref, "epoch-b", "tab_1", runtimeTabId)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* The server only guarantees preview tab ids are unique within one process.
|
||||
* Desktop resources live across every connected environment, so they need a
|
||||
* stronger identity that also changes when a server process restarts.
|
||||
*/
|
||||
export function previewRuntimeTabId(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverEpoch: string | null,
|
||||
tabId: string,
|
||||
): string {
|
||||
return JSON.stringify([threadRef.environmentId, threadRef.threadId, serverEpoch, tabId]);
|
||||
}
|
||||
|
||||
export function isCurrentPreviewRuntimeTab(
|
||||
threadRef: ScopedThreadRef,
|
||||
serverEpoch: string | null,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
): boolean {
|
||||
return previewRuntimeTabId(threadRef, serverEpoch, tabId) === runtimeTabId;
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { getLocalStorageItem } from "../hooks/useLocalStorage";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
import { cn, isMacPlatform } from "../lib/utils";
|
||||
import { primaryServerKeybindingsAtom } from "../state/server";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { useSidebarV2Enabled } from "../hooks/useSettings";
|
||||
import ThreadSidebar from "./Sidebar";
|
||||
import ThreadSidebarV2 from "./SidebarV2";
|
||||
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
|
||||
@@ -115,7 +115,7 @@ function SidebarControl() {
|
||||
|
||||
export function AppSidebarLayout({ children }: { children: ReactNode }) {
|
||||
const navigate = useNavigate();
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarV2Enabled = useSidebarV2Enabled();
|
||||
// Settings routes render the settings nav, which lives in the v1 component
|
||||
// and is identical for both sidebars — so v1 stays mounted there.
|
||||
const pathname = useLocation({ select: (location) => location.pathname });
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveEffectiveEnvMode,
|
||||
resolveEnvModeLabel,
|
||||
resolveBranchTriggerLabel,
|
||||
resolveBranchToolbarPrBranch,
|
||||
resolveBranchToolbarValue,
|
||||
resolveLockedWorkspaceLabel,
|
||||
@@ -175,6 +176,101 @@ describe("resolveBranchToolbarValue", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchTriggerLabel", () => {
|
||||
it("shows the origin ref when a new worktree will start from origin", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/main");
|
||||
});
|
||||
|
||||
it("shows the origin ref for local branch names that contain slashes", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "feature/demo",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/feature/demo");
|
||||
});
|
||||
|
||||
it("shows the local ref when start from origin is disabled", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: false,
|
||||
}),
|
||||
).toBe("From main");
|
||||
});
|
||||
|
||||
it("does not duplicate the origin prefix for an explicit remote ref", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "origin/feature/demo",
|
||||
resolvedActiveBranchIsRemote: true,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From origin/feature/demo");
|
||||
});
|
||||
|
||||
it("preserves an explicit ref from a non-origin remote", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "upstream/feature/demo",
|
||||
resolvedActiveBranchIsRemote: true,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From upstream/feature/demo");
|
||||
});
|
||||
|
||||
it("keeps current-checkout labels and empty state unchanged", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "local",
|
||||
resolvedActiveBranch: "main",
|
||||
resolvedActiveBranchIsRemote: false,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("main");
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: null,
|
||||
resolvedActiveBranchIsRemote: null,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("Select ref");
|
||||
});
|
||||
|
||||
it("does not fabricate an origin ref while branch metadata is loading", () => {
|
||||
expect(
|
||||
resolveBranchTriggerLabel({
|
||||
activeWorktreePath: null,
|
||||
effectiveEnvMode: "worktree",
|
||||
resolvedActiveBranch: "upstream/feature/demo",
|
||||
resolvedActiveBranchIsRemote: null,
|
||||
startFromOrigin: true,
|
||||
}),
|
||||
).toBe("From upstream/feature/demo");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveBranchToolbarPrBranch", () => {
|
||||
it("uses the explicit thread branch when it matches the displayed branch", () => {
|
||||
expect(
|
||||
|
||||
@@ -163,6 +163,33 @@ export function resolveBranchToolbarValue(input: {
|
||||
return currentGitBranch ?? activeThreadBranch;
|
||||
}
|
||||
|
||||
export function resolveBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: EnvMode;
|
||||
resolvedActiveBranch: string | null;
|
||||
resolvedActiveBranchIsRemote: boolean | null;
|
||||
startFromOrigin: boolean;
|
||||
}): string {
|
||||
const {
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
resolvedActiveBranchIsRemote,
|
||||
startFromOrigin,
|
||||
} = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
const baseRef =
|
||||
startFromOrigin && resolvedActiveBranchIsRemote === false
|
||||
? `origin/${resolvedActiveBranch}`
|
||||
: resolvedActiveBranch;
|
||||
return `From ${baseRef}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function resolveBranchToolbarPrBranch(input: {
|
||||
activeThreadBranch: string | null;
|
||||
resolvedActiveBranch: string | null;
|
||||
|
||||
@@ -41,6 +41,7 @@ import { parsePullRequestReference } from "../pullRequestReference";
|
||||
import { getSourceControlPresentation } from "../sourceControlPresentation";
|
||||
import {
|
||||
deriveLocalBranchNameFromRemoteRef,
|
||||
resolveBranchTriggerLabel,
|
||||
resolveBranchToolbarPrBranch,
|
||||
resolveBranchSelectionTarget,
|
||||
resolveBranchToolbarValue,
|
||||
@@ -88,21 +89,6 @@ function toBranchActionErrorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : "An error occurred.";
|
||||
}
|
||||
|
||||
function getBranchTriggerLabel(input: {
|
||||
activeWorktreePath: string | null;
|
||||
effectiveEnvMode: "local" | "worktree";
|
||||
resolvedActiveBranch: string | null;
|
||||
}): string {
|
||||
const { activeWorktreePath, effectiveEnvMode, resolvedActiveBranch } = input;
|
||||
if (!resolvedActiveBranch) {
|
||||
return "Select ref";
|
||||
}
|
||||
if (effectiveEnvMode === "worktree" && !activeWorktreePath) {
|
||||
return `From ${resolvedActiveBranch}`;
|
||||
}
|
||||
return resolvedActiveBranch;
|
||||
}
|
||||
|
||||
export function BranchToolbarBranchSelector({
|
||||
className,
|
||||
displayMode = "toolbar",
|
||||
@@ -316,6 +302,29 @@ export function BranchToolbarBranchSelector({
|
||||
canonicalActiveBranch,
|
||||
(_currentBranch: string | null, optimisticBranch: string | null) => optimisticBranch,
|
||||
);
|
||||
const listedActiveBranch =
|
||||
resolvedActiveBranch === null ? null : (branchByName.get(resolvedActiveBranch) ?? null);
|
||||
const activeBranchRefQuery = useEnvironmentQuery(
|
||||
branchCwd !== null && resolvedActiveBranch !== null
|
||||
? vcsEnvironment.listRefs({
|
||||
environmentId,
|
||||
input: {
|
||||
cwd: branchCwd,
|
||||
query: resolvedActiveBranch,
|
||||
limit: 10,
|
||||
},
|
||||
})
|
||||
: null,
|
||||
);
|
||||
const queriedActiveBranch = activeBranchRefQuery.data?.refs.find(
|
||||
(refName) => refName.name === resolvedActiveBranch,
|
||||
);
|
||||
const resolvedActiveBranchIsRemote =
|
||||
listedActiveBranch !== null
|
||||
? listedActiveBranch.isRemote === true
|
||||
: queriedActiveBranch
|
||||
? queriedActiveBranch.isRemote === true
|
||||
: null;
|
||||
const [isBranchActionPending, startBranchActionTransition] = useTransition();
|
||||
const totalBranchCount = branchRefState.data?.totalCount ?? 0;
|
||||
const branchStatusText = isInitialBranchesLoadPending
|
||||
@@ -592,10 +601,12 @@ export function BranchToolbarBranchSelector({
|
||||
maybeFetchNextBranchPage();
|
||||
}, [refs.length, maybeFetchNextBranchPage]);
|
||||
|
||||
const triggerLabel = getBranchTriggerLabel({
|
||||
const triggerLabel = resolveBranchTriggerLabel({
|
||||
activeWorktreePath,
|
||||
effectiveEnvMode,
|
||||
resolvedActiveBranch,
|
||||
resolvedActiveBranchIsRemote,
|
||||
startFromOrigin,
|
||||
});
|
||||
|
||||
// PR pill shown next to the branch selector when the active branch has one.
|
||||
|
||||
@@ -224,6 +224,7 @@ import { threadEnvironment } from "../state/threads";
|
||||
import { vcsEnvironment } from "../state/vcs";
|
||||
import { useEnvironments, usePrimaryEnvironment } from "../state/environments";
|
||||
import {
|
||||
resolveThreadDetailRef,
|
||||
useProject,
|
||||
useProjects,
|
||||
useThreadProjection,
|
||||
@@ -1214,10 +1215,21 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
);
|
||||
const composerDraftTarget: ScopedThreadRef | DraftId =
|
||||
routeKind === "server" ? routeThreadRef : props.draftId;
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
routeKind === "server"
|
||||
? store.getDraftSessionByRef(routeThreadRef)
|
||||
: draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: null,
|
||||
);
|
||||
const serverThread = useThreadShell(routeThreadRef);
|
||||
const serverThreadProjection = useThreadProjection(routeThreadRef);
|
||||
const routeThreadDetailRef = resolveThreadDetailRef(routeThreadRef, {
|
||||
shellExists: serverThread !== null,
|
||||
waitForShell: draftThread !== null,
|
||||
});
|
||||
const serverThreadProjection = useThreadProjection(routeThreadDetailRef);
|
||||
const serverProjection = serverThreadProjection?.projection ?? null;
|
||||
const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadRef);
|
||||
const serverVisibleTurnItems = useThreadVisibleTurnItems(routeThreadDetailRef);
|
||||
const committedServerMessageIds = useMemo(
|
||||
() => deriveCommittedServerUserMessageIds(serverVisibleTurnItems),
|
||||
[serverVisibleTurnItems],
|
||||
@@ -1274,13 +1286,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const setLogicalProjectDraftThreadId = useComposerDraftStore(
|
||||
(store) => store.setLogicalProjectDraftThreadId,
|
||||
);
|
||||
const draftThread = useComposerDraftStore((store) =>
|
||||
routeKind === "server"
|
||||
? store.getDraftSessionByRef(routeThreadRef)
|
||||
: draftId
|
||||
? store.getDraftSession(draftId)
|
||||
: null,
|
||||
);
|
||||
const promptRef = useRef("");
|
||||
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);
|
||||
|
||||
@@ -41,7 +41,7 @@ export function CommandPaletteResults(props: CommandPaletteResultsProps) {
|
||||
<CommandList>
|
||||
{props.groups.map((group) => (
|
||||
<CommandGroup items={group.items} key={group.value}>
|
||||
<CommandGroupLabel>{group.label}</CommandGroupLabel>
|
||||
<CommandGroupLabel className="ps-[9px]">{group.label}</CommandGroupLabel>
|
||||
<CommandCollection>
|
||||
{(item) =>
|
||||
item.disabled ? (
|
||||
@@ -133,13 +133,13 @@ function CommandPaletteResultRow(props: {
|
||||
)}
|
||||
{props.item.titleTrailingContent}
|
||||
{props.item.timestamp ? (
|
||||
<span className="min-w-12 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground/70">
|
||||
<span className="min-w-12 shrink-0 text-right text-xs tabular-nums text-muted-foreground/70">
|
||||
{props.item.timestamp}
|
||||
</span>
|
||||
) : null}
|
||||
{shortcutLabel ? <CommandShortcut>{shortcutLabel}</CommandShortcut> : null}
|
||||
{props.item.kind === "submenu" ? (
|
||||
<ChevronRightIcon className="ml-auto size-4 shrink-0 text-muted-foreground/50" />
|
||||
<ChevronRightIcon className="-me-0.5 ms-auto size-4 shrink-0 text-muted-foreground/70" />
|
||||
) : null}
|
||||
</CommandItem>
|
||||
);
|
||||
|
||||
@@ -30,6 +30,7 @@ import { useTheme } from "../hooks/useTheme";
|
||||
import {
|
||||
buildFileDiffRenderKey,
|
||||
getDiffCollapseIconClassName,
|
||||
getDiffLineStat,
|
||||
getRenderablePatch,
|
||||
resolveDiffThemeName,
|
||||
resolveFileDiffPath,
|
||||
@@ -41,6 +42,7 @@ import { resolveThreadRouteRef } from "../threadRoutes";
|
||||
import { useClientSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { DiffStatLabel } from "./chat/DiffStatLabel";
|
||||
import { AnnotatableCodeView, type AnnotatableCodeViewHandle } from "./diffs/AnnotatableCodeView";
|
||||
import { Button } from "./ui/button";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -453,6 +455,7 @@ export default function DiffPanel({
|
||||
);
|
||||
const diffFileKeys = useMemo(() => codeViewFiles.map((file) => file.fileKey), [codeViewFiles]);
|
||||
const allDiffFilesCollapsed = areAllDiffFilesCollapsed(diffFileKeys, collapsedDiffFileKeys);
|
||||
const diffLineStat = useMemo(() => getDiffLineStat(renderableFiles), [renderableFiles]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath) return;
|
||||
@@ -724,6 +727,14 @@ export default function DiffPanel({
|
||||
)}
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
{codeViewFiles.length > 0 && (
|
||||
<DiffStatLabel
|
||||
additions={diffLineStat.additions}
|
||||
deletions={diffLineStat.deletions}
|
||||
className="mr-1 text-[11px]"
|
||||
layout="inline"
|
||||
/>
|
||||
)}
|
||||
{codeViewFiles.length > 0 && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FolderIcon } from "lucide-react";
|
||||
import type { ComponentType } from "react";
|
||||
import { useState } from "react";
|
||||
import { useAssetUrl } from "../assets/assetUrls";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const loadedProjectFaviconSrcs = new Set<string>();
|
||||
|
||||
@@ -40,7 +41,7 @@ function ProjectFaviconFallback({
|
||||
readonly className?: string | undefined;
|
||||
readonly icon: ComponentType<{ className?: string }>;
|
||||
}) {
|
||||
return <Icon className={`size-3.5 shrink-0 text-muted-foreground/50 ${className ?? ""}`} />;
|
||||
return <Icon className={cn("size-3.5 shrink-0 text-muted-foreground/50", className)} />;
|
||||
}
|
||||
|
||||
function ProjectFaviconImage({
|
||||
@@ -64,7 +65,11 @@ function ProjectFaviconImage({
|
||||
<img
|
||||
src={src}
|
||||
alt=""
|
||||
className={`size-3.5 shrink-0 rounded-sm object-contain ${status === "loaded" ? "" : "hidden"} ${className ?? ""}`}
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 rounded-sm object-contain",
|
||||
status !== "loaded" && "hidden",
|
||||
className,
|
||||
)}
|
||||
onLoad={() => {
|
||||
loadedProjectFaviconSrcs.add(src);
|
||||
setStatus("loaded");
|
||||
|
||||
@@ -154,6 +154,10 @@ export default function ProjectScriptsControl({
|
||||
const panelAnchorRef = React.useRef<HTMLDivElement | null>(null);
|
||||
const addScriptFormId = React.useId();
|
||||
const [editingScriptId, setEditingScriptId] = useState<string | null>(null);
|
||||
const [actionsMenuOpen, setActionsMenuOpen] = useState({
|
||||
scripts: false,
|
||||
imports: false,
|
||||
});
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [command, setCommand] = useState("");
|
||||
@@ -271,6 +275,7 @@ export default function ProjectScriptsControl({
|
||||
};
|
||||
|
||||
const openEditDialog = (script: ProjectScript) => {
|
||||
setActionsMenuOpen({ scripts: false, imports: false });
|
||||
setEditingScriptId(script.id);
|
||||
setName(script.name);
|
||||
setCommand(script.command);
|
||||
@@ -384,7 +389,11 @@ export default function ProjectScriptsControl({
|
||||
) : (
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
)}
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<Menu
|
||||
highlightItemOnHover={false}
|
||||
open={actionsMenuOpen.scripts}
|
||||
onOpenChange={(open) => setActionsMenuOpen({ scripts: open, imports: false })}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
@@ -456,7 +465,11 @@ export default function ProjectScriptsControl({
|
||||
</Menu>
|
||||
</ActionGroup>
|
||||
) : importableScripts.length > 0 ? (
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<Menu
|
||||
highlightItemOnHover={false}
|
||||
open={actionsMenuOpen.imports}
|
||||
onOpenChange={(open) => setActionsMenuOpen({ scripts: false, imports: open })}
|
||||
>
|
||||
<MenuTrigger render={<Button size="xs" variant="outline" aria-label="Project actions" />}>
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
|
||||
@@ -68,6 +68,10 @@ function updateProviderUpdateToast(input: {
|
||||
title: input.view.title,
|
||||
description: input.view.description,
|
||||
timeout: 0,
|
||||
// Base UI merges toast updates with the existing toast. Explicitly clear
|
||||
// the prompt action so its guarded Update handler cannot linger as a
|
||||
// visible no-op while the update is running (or after it succeeds).
|
||||
actionProps: undefined,
|
||||
data: {
|
||||
hideCopyButton: true,
|
||||
...(input.view.dismissAfterVisibleMs !== undefined
|
||||
|
||||
@@ -2254,9 +2254,8 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
|
||||
<div className="group/project-header relative">
|
||||
<SidebarMenuButton
|
||||
ref={isManualProjectSorting ? dragHandleProps?.setActivatorNodeRef : undefined}
|
||||
size="sm"
|
||||
className={`h-8 gap-2 rounded-md px-2 py-1.5 pr-8 text-left hover:bg-sidebar-row-hover group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${
|
||||
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : "cursor-pointer"
|
||||
className={`pr-8 group-hover/project-header:bg-sidebar-row-hover group-hover/project-header:text-sidebar-foreground max-sm:pr-14 ${
|
||||
isManualProjectSorting ? "cursor-grab active:cursor-grabbing" : ""
|
||||
}`}
|
||||
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.attributes : {})}
|
||||
{...(isManualProjectSorting && dragHandleProps ? dragHandleProps.listeners : {})}
|
||||
@@ -2858,30 +2857,33 @@ const SidebarProjectsContent = memo(function SidebarProjectsContent(
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 gap-2 rounded-md px-2 py-1.5 text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span className="flex-1 truncate text-left text-sm font-medium">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
<SidebarContent
|
||||
className="gap-0"
|
||||
fixedHeader={
|
||||
<SidebarGroup className="px-2 pt-2 pb-1">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
className="focus-visible:ring-0"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon />
|
||||
<span className="flex-1 truncate">Search</span>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
}
|
||||
>
|
||||
{showArm64IntelBuildWarning && arm64IntelBuildWarningDescription ? (
|
||||
<SidebarGroup className="px-2 pt-2 pb-0">
|
||||
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8">
|
||||
|
||||
@@ -96,7 +96,11 @@ import { threadEnvironment } from "../state/threads";
|
||||
import { projectEnvironment } from "../state/projects";
|
||||
import { useEnvironmentQuery } from "../state/query";
|
||||
import { useAtomCommand } from "../state/use-atom-command";
|
||||
import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";
|
||||
import {
|
||||
buildThreadRouteParams,
|
||||
resolveActiveThreadRouteRef,
|
||||
resolveThreadRouteTarget,
|
||||
} from "../threadRoutes";
|
||||
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
|
||||
import type { SidebarThreadSummary } from "../types";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -239,41 +243,40 @@ function SidebarV2ThreadTooltip({
|
||||
<TooltipPopup
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
className="dropdown-glass max-w-80 border-0! text-left whitespace-normal shadow-lg/10 before:hidden dark:shadow-none"
|
||||
style={{
|
||||
background:
|
||||
"color-mix(in srgb, var(--popover) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
|
||||
}}
|
||||
sideOffset={4}
|
||||
variant="glass"
|
||||
className="max-w-80 text-left whitespace-normal"
|
||||
>
|
||||
<div className="flex max-w-80 flex-col gap-2 p-2">
|
||||
<div className="whitespace-nowrap text-sm font-medium text-foreground">{thread.title}</div>
|
||||
<div className="grid gap-1.5 text-xs text-muted-foreground">
|
||||
<div className="flex min-w-0 max-w-80 flex-col gap-2 px-0.5 py-1.5">
|
||||
<div className="min-w-0 truncate text-xs leading-none font-medium text-foreground">
|
||||
{thread.title}
|
||||
</div>
|
||||
<div className="grid gap-1.5 pl-0.5 text-xs text-muted-foreground">
|
||||
{projectTitle ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ProjectFavicon
|
||||
environmentId={thread.environmentId}
|
||||
cwd={projectCwd ?? ""}
|
||||
className="size-4 shrink-0 stroke-muted-foreground"
|
||||
className="size-3 shrink-0 stroke-muted-foreground"
|
||||
/>
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{projectTitle}</div>
|
||||
<div className="min-w-0 truncate text-foreground/75">{projectTitle}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{environmentLabel ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<ServerIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{environmentLabel}</div>
|
||||
<ServerIcon className="size-3 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 truncate text-foreground/75">{environmentLabel}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{thread.branch ? (
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<GitBranchIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{thread.branch}</div>
|
||||
<GitBranchIcon className="size-3 shrink-0 stroke-muted-foreground" />
|
||||
<div className="min-w-0 truncate text-foreground/75">{thread.branch}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{branchMismatch ? (
|
||||
<div className="flex min-w-0 items-start gap-2 text-warning">
|
||||
<CircleAlertIcon aria-hidden className="mt-0.5 size-4 shrink-0 stroke-current" />
|
||||
<CircleAlertIcon aria-hidden className="mt-0.5 size-3 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 flex-1 wrap-break-word leading-5">
|
||||
You're currently checked out on another branch.
|
||||
</div>
|
||||
@@ -284,15 +287,15 @@ function SidebarV2ThreadTooltip({
|
||||
<ProviderInstanceIcon
|
||||
driverKind={driverKind}
|
||||
displayName={thread.runtime?.providerName ?? modelInstanceId}
|
||||
iconClassName="size-4 shrink-0"
|
||||
iconClassName="size-3 shrink-0 grayscale opacity-60"
|
||||
/>
|
||||
<div className="min-w-0 wrap-break-word text-foreground/90">{modelLabel}</div>
|
||||
<div className="min-w-0 truncate text-foreground/75">{modelLabel}</div>
|
||||
</div>
|
||||
) : null}
|
||||
{thread.runtime?.lastError ? (
|
||||
<div className="flex min-w-0 items-center gap-2 text-red-600 dark:text-red-400">
|
||||
<CircleAlertIcon className="size-4 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 wrap-break-word">{thread.runtime.lastError}</div>
|
||||
<CircleAlertIcon className="size-3 shrink-0 stroke-current" />
|
||||
<div className="min-w-0 truncate">Error occurred</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -815,9 +818,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
type="button"
|
||||
aria-label="Un-settle thread"
|
||||
onClick={handleUnsettleClick}
|
||||
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
|
||||
className="absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
<Undo2Icon className="mb-px size-3.5" />
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
@@ -917,7 +920,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
{props.settlementSupported || showSnoozeButton ? (
|
||||
<span
|
||||
className={cn(
|
||||
"absolute inset-y-0 right-0 flex items-stretch gap-0.5 opacity-0 transition-opacity focus-within:opacity-100 group-hover/v2-row:opacity-100",
|
||||
"absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity focus-within:opacity-100 group-hover/v2-row:opacity-100",
|
||||
snoozeMenuOpen && "opacity-100",
|
||||
)}
|
||||
>
|
||||
@@ -933,9 +936,9 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
|
||||
type="button"
|
||||
aria-label="Settle thread"
|
||||
onClick={handleSettleClick}
|
||||
className="inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground hover:text-foreground"
|
||||
className="-mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<CheckIcon className="size-3" />
|
||||
<CheckIcon className="size-3.5" />
|
||||
Settle
|
||||
</button>
|
||||
) : null}
|
||||
@@ -1056,7 +1059,13 @@ export default function SidebarV2() {
|
||||
strict: false,
|
||||
select: (params) => resolveThreadRouteTarget(params),
|
||||
});
|
||||
const routeThreadRef = routeTarget?.kind === "server" ? routeTarget.threadRef : null;
|
||||
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 routeTargetRef = useRef(routeTarget);
|
||||
routeTargetRef.current = routeTarget;
|
||||
@@ -2209,151 +2218,158 @@ export default function SidebarV2() {
|
||||
return (
|
||||
<>
|
||||
<SidebarChromeHeader isElectron={isElectron} />
|
||||
<SidebarContent className="gap-0">
|
||||
<SidebarGroup className="px-2 pb-2 pt-3">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
aria-label="Search threads and commands"
|
||||
className="h-8 gap-2 rounded-md border-0 bg-transparent px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<div className="flex-1 truncate text-left">Search</div>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
<SidebarContent
|
||||
className="gap-0"
|
||||
fixedHeader={
|
||||
<SidebarGroup className="gap-1 p-2">
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="min-w-0 flex-1">
|
||||
<CommandDialogTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
type="button"
|
||||
className="relative size-8 justify-center rounded-md border-0 bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={handleNewThreadClick}
|
||||
disabled={projects.length === 0}
|
||||
aria-label="New thread"
|
||||
aria-label="Search threads and commands"
|
||||
className="focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
data-testid="command-palette-trigger"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<SquarePenIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarGroup>
|
||||
{projectGroups.length > 0 ? (
|
||||
<SidebarGroup className="px-2 pb-2 pt-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
|
||||
<MenuTrigger
|
||||
aria-label="Filter threads by project"
|
||||
className="flex h-8 min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md px-2 text-left text-sm font-medium text-sidebar-muted-foreground outline-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
>
|
||||
{scopedProjectGroup ? (
|
||||
<ProjectFavicon
|
||||
environmentId={scopedProjectGroup.environmentId}
|
||||
cwd={scopedProjectGroup.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<FolderIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{scopedProjectGroup?.displayName ?? "All projects"}
|
||||
</span>
|
||||
<ChevronDownIcon className="size-4 shrink-0 text-sidebar-muted-foreground/70" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" className="w-(--anchor-width)">
|
||||
<MenuRadioGroup
|
||||
value={projectScopeKey ?? "all"}
|
||||
onValueChange={(value) =>
|
||||
setProjectScopeKey(value === "all" ? null : (value as string))
|
||||
<SearchIcon />
|
||||
<div className="flex-1 truncate text-left">Search</div>
|
||||
{commandPaletteShortcutLabel ? (
|
||||
<Kbd className="mr-px h-4 min-w-0 rounded-sm bg-sidebar-control-surface px-1.5 text-[10px] text-sidebar-muted-foreground ring-1 ring-sidebar-border">
|
||||
{commandPaletteShortcutLabel}
|
||||
</Kbd>
|
||||
) : null}
|
||||
</CommandDialogTrigger>
|
||||
</div>
|
||||
<div className="shrink-0">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="icon"
|
||||
type="button"
|
||||
className="relative focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={handleNewThreadClick}
|
||||
disabled={projects.length === 0}
|
||||
aria-label="New thread"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<MenuRadioItem
|
||||
value="all"
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">All projects</span>
|
||||
</MenuRadioItem>
|
||||
{projectGroups.map((project) => {
|
||||
const scopeKey = project.projectKey;
|
||||
return (
|
||||
<MenuRadioItem
|
||||
key={scopeKey}
|
||||
value={scopeKey}
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project actions for ${project.displayName}`}
|
||||
title={`Project actions for ${project.displayName}`}
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectActions(event, project);
|
||||
}}
|
||||
>
|
||||
<EllipsisIcon className="size-3.5" />
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="relative size-8 shrink-0 justify-center rounded-md bg-transparent p-0 text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={openAddProjectCommandPalette}
|
||||
type="button"
|
||||
aria-label="New project"
|
||||
<SquarePenIcon />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FolderPlusIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">New project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">
|
||||
{newThreadShortcutLabel
|
||||
? `New thread (${newThreadShortcutLabel})`
|
||||
: "New thread"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
{projectGroups.length > 0 ? (
|
||||
<div className="flex items-center gap-1">
|
||||
<Menu open={projectScopeMenuOpen} onOpenChange={setProjectScopeMenuOpen}>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
aria-label="Filter threads by project"
|
||||
className="min-w-0 flex-1 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
/>
|
||||
}
|
||||
>
|
||||
{scopedProjectGroup ? (
|
||||
<ProjectFavicon
|
||||
environmentId={scopedProjectGroup.environmentId}
|
||||
cwd={scopedProjectGroup.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
) : (
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate">
|
||||
{scopedProjectGroup?.displayName ?? "All projects"}
|
||||
</span>
|
||||
<ChevronDownIcon className="-mr-px size-4 shrink-0" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start" className="w-(--anchor-width)">
|
||||
<MenuRadioGroup
|
||||
value={projectScopeKey ?? "all"}
|
||||
onValueChange={(value) =>
|
||||
setProjectScopeKey(value === "all" ? null : (value as string))
|
||||
}
|
||||
>
|
||||
<MenuRadioItem
|
||||
value="all"
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<FolderIcon className="size-4 shrink-0" />
|
||||
<span className="min-w-0 truncate text-sm">All projects</span>
|
||||
</MenuRadioItem>
|
||||
{projectGroups.map((project) => {
|
||||
const scopeKey = project.projectKey;
|
||||
return (
|
||||
<MenuRadioItem
|
||||
key={scopeKey}
|
||||
value={scopeKey}
|
||||
closeOnClick
|
||||
className="h-8 min-h-8 px-1 py-0 text-sm font-medium [&>span:last-child]:flex [&>span:last-child]:min-w-0 [&>span:last-child]:items-center [&>span:last-child]:gap-2"
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
cwd={project.workspaceRoot}
|
||||
className="size-4 shrink-0"
|
||||
/>
|
||||
<span className="min-w-0 truncate text-sm">{project.displayName}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Project actions for ${project.displayName}`}
|
||||
title={`Project actions for ${project.displayName}`}
|
||||
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
void handleProjectActions(event, project);
|
||||
}}
|
||||
>
|
||||
<EllipsisIcon className="size-3.5" />
|
||||
</button>
|
||||
</MenuRadioItem>
|
||||
);
|
||||
})}
|
||||
</MenuRadioGroup>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SidebarMenuButton
|
||||
size="icon"
|
||||
className="relative shrink-0 focus-visible:ring-offset-2 focus-visible:ring-offset-sidebar"
|
||||
onClick={openAddProjectCommandPalette}
|
||||
type="button"
|
||||
aria-label="New project"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<FolderPlusIcon />
|
||||
<span
|
||||
className="pointer-events-none absolute left-1/2 top-1/2 size-[max(100%,3rem)] -translate-1/2 pointer-fine:hidden"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup side="right">New project</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
) : null}
|
||||
</SidebarGroup>
|
||||
) : null}
|
||||
<SidebarGroup className="min-h-0 flex-1 overflow-y-auto px-2 py-1 [scrollbar-gutter:stable]">
|
||||
}
|
||||
>
|
||||
<SidebarGroup className="px-2 pb-1 pt-0">
|
||||
<TooltipProvider
|
||||
key="sidebar-thread-tooltips-150"
|
||||
delay={150}
|
||||
@@ -2515,12 +2531,10 @@ export default function SidebarV2() {
|
||||
<button
|
||||
type="button"
|
||||
onClick={showMoreSettled}
|
||||
className="mt-1 flex h-[30px] w-full items-center justify-center gap-1.5 rounded-md border border-dashed border-border font-mono text-[11px] text-muted-foreground transition-colors hover:border-solid hover:border-input hover:bg-background/45 hover:text-foreground dark:border-white/15 dark:hover:border-white/30 dark:hover:bg-transparent"
|
||||
className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-sidebar-muted-foreground/55 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon aria-hidden className="size-4 shrink-0" />
|
||||
Show {Math.min(hiddenSettledCount, SETTLED_TAIL_PAGE_COUNT)} more
|
||||
<span className="text-muted-foreground/50">
|
||||
({hiddenSettledCount} settled hidden)
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
) : null}
|
||||
@@ -2536,7 +2550,7 @@ export default function SidebarV2() {
|
||||
onClick={openAddProjectCommandPalette}
|
||||
className="inline-flex items-center gap-1.5 rounded-md border border-sidebar-border px-2.5 py-1 text-[11px] font-medium text-sidebar-muted-foreground transition-colors hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
>
|
||||
<PlusIcon className="size-3" />
|
||||
<PlusIcon className="-mx-0.5 size-3" />
|
||||
Add project
|
||||
</button>
|
||||
</>
|
||||
@@ -2556,48 +2570,52 @@ export default function SidebarV2() {
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader className="gap-1.5">
|
||||
<DialogHeader className="gap-3 pb-1!">
|
||||
<DialogTitle className="text-balance">Project settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
{projectActionsTarget && projectActionsTarget.memberProjects.length > 1
|
||||
? `${projectActionsTarget.displayName} has an entry in each environment. Changes apply only to the entry you choose.`
|
||||
: `Manage ${projectActionsTarget?.displayName ?? "this project"} in this environment.`}
|
||||
<DialogDescription className="sr-only">
|
||||
Manage project names, grouping rules, and environments.
|
||||
</DialogDescription>
|
||||
<div className="grid gap-1.5 text-base text-muted-foreground">
|
||||
{projectActionsTarget?.memberProjects.map((member) => (
|
||||
<div key={member.physicalProjectKey} className="flex min-w-0 items-center gap-3">
|
||||
<span className="flex min-w-0 items-center gap-1">
|
||||
<FolderIcon className="size-3.5 shrink-0 opacity-60" />
|
||||
<span className="min-w-0 truncate font-mono">{member.workspaceRoot}</span>
|
||||
<Button
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
className="size-4 shrink-0 rounded-sm"
|
||||
aria-label="Copy project path"
|
||||
title="Copy project path"
|
||||
onClick={() =>
|
||||
copyProjectPath(member.workspaceRoot, { path: member.workspaceRoot })
|
||||
}
|
||||
>
|
||||
<CopyIcon className="size-3.5" />
|
||||
</Button>
|
||||
</span>
|
||||
<span className="flex min-w-0 shrink-0 items-center gap-1">
|
||||
<ServerIcon className="size-3.5 shrink-0 opacity-60" />
|
||||
<span className="min-w-0 truncate">
|
||||
{member.environmentLabel ?? "Current environment"}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="p-0">
|
||||
<div className="divide-y divide-border/60">
|
||||
{projectActionsTarget?.memberProjects.map((member) => (
|
||||
<section
|
||||
key={member.physicalProjectKey}
|
||||
className="flex min-w-0 flex-col gap-4 px-6 py-5 sm:gap-3 sm:py-4"
|
||||
className="grid min-w-0 gap-5 px-6 pb-5 pt-2 sm:gap-4 sm:pb-4 sm:pt-2"
|
||||
>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<ProjectFavicon
|
||||
environmentId={member.environmentId}
|
||||
cwd={member.workspaceRoot}
|
||||
className="size-5 shrink-0 sm:size-4"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="flex min-w-0 items-center gap-1.5 text-base text-muted-foreground sm:text-sm">
|
||||
<ServerIcon className="size-4 shrink-0 stroke-muted-foreground" />
|
||||
<p className="min-w-0 truncate">
|
||||
{member.environmentLabel ?? "Current environment"}
|
||||
</p>
|
||||
</div>
|
||||
<p
|
||||
className="truncate font-mono text-base text-muted-foreground/72 sm:text-sm"
|
||||
title={member.workspaceRoot}
|
||||
>
|
||||
{member.workspaceRoot}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid gap-4 sm:grid-cols-2 sm:gap-3 sm:pl-7">
|
||||
<div className="grid gap-4 sm:grid-cols-2 sm:gap-3">
|
||||
<label className="grid min-w-0 gap-1.5">
|
||||
<span className="font-medium text-foreground">Project name</span>
|
||||
<Input
|
||||
key={`${member.physicalProjectKey}:${member.title}`}
|
||||
size="sm"
|
||||
aria-label={`Project name in ${member.environmentLabel ?? "current environment"}`}
|
||||
defaultValue={member.title}
|
||||
onBlur={(event) => {
|
||||
@@ -2628,8 +2646,7 @@ export default function SidebarV2() {
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
size="sm"
|
||||
className="w-full"
|
||||
className="w-full sm:min-h-7.5"
|
||||
aria-label={`Grouping rule for ${member.environmentLabel ?? "current environment"}`}
|
||||
>
|
||||
<SelectValue>
|
||||
@@ -2661,32 +2678,23 @@ export default function SidebarV2() {
|
||||
</Select>
|
||||
</label>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center gap-2 sm:pl-7">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
copyProjectPath(member.workspaceRoot, { path: member.workspaceRoot })
|
||||
}
|
||||
>
|
||||
<CopyIcon />
|
||||
Copy path
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground sm:ml-auto"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
if (!projectGroup) return;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, [member]);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove
|
||||
</Button>
|
||||
</div>
|
||||
{projectActionsTarget.memberProjects.length > 1 ? (
|
||||
<div className="flex justify-end">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="text-destructive-foreground hover:bg-destructive/8 hover:text-destructive-foreground"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, [member]);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove project
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
@@ -2716,8 +2724,26 @@ export default function SidebarV2() {
|
||||
</div>
|
||||
) : null}
|
||||
</DialogPanel>
|
||||
<DialogFooter variant="bare">
|
||||
<Button onClick={() => setProjectActionsTarget(null)}>Done</Button>
|
||||
<DialogFooter
|
||||
variant="bare"
|
||||
className={cn(
|
||||
projectActionsTarget?.memberProjects.length === 1 && "sm:justify-between",
|
||||
)}
|
||||
>
|
||||
{projectActionsTarget?.memberProjects.length === 1 ? (
|
||||
<Button
|
||||
variant="destructive-outline"
|
||||
onClick={() => {
|
||||
const projectGroup = projectActionsTarget;
|
||||
setProjectActionsTarget(null);
|
||||
void handleRemoveProjectMembers(projectGroup, projectGroup.memberProjects);
|
||||
}}
|
||||
>
|
||||
<Trash2Icon />
|
||||
Remove project
|
||||
</Button>
|
||||
) : null}
|
||||
<Button onClick={() => setProjectActionsTarget(null)}>Close</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
|
||||
@@ -96,6 +96,7 @@ import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
|
||||
import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
|
||||
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
|
||||
import { ComposerControl, ComposerControlIcon, ComposerSelectControl } from "./ComposerControl";
|
||||
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
|
||||
import { searchSlashCommandItems } from "./composerSlashCommandSearch";
|
||||
import {
|
||||
@@ -168,7 +169,7 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:
|
||||
);
|
||||
}
|
||||
import { Button } from "../ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Select, SelectItem, SelectPopup, SelectValue } from "../ui/select";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import {
|
||||
@@ -309,15 +310,13 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
<ComposerControl
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
"shrink-0 whitespace-nowrap",
|
||||
props.interactionMode === "plan"
|
||||
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onToggleInteractionMode}
|
||||
aria-label={interactionModeTooltip}
|
||||
@@ -325,9 +324,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
}
|
||||
>
|
||||
{props.interactionMode === "plan" ? (
|
||||
<PencilRulerIcon className="text-current opacity-100" />
|
||||
<ComposerControlIcon icon={PencilRulerIcon} className="text-current opacity-100" />
|
||||
) : (
|
||||
<BotIcon />
|
||||
<ComposerControlIcon icon={BotIcon} opticalSize="large" />
|
||||
)}
|
||||
<span className="sr-only sm:not-sr-only">
|
||||
{props.interactionMode === "plan" ? "Plan" : "Build"}
|
||||
@@ -348,16 +347,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
onValueChange={(value) => props.onRuntimeModeChange(value!)}
|
||||
>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<SelectTrigger
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="font-medium"
|
||||
aria-label="Runtime mode"
|
||||
/>
|
||||
}
|
||||
render={<ComposerSelectControl className="font-medium" aria-label="Runtime mode" />}
|
||||
>
|
||||
<RuntimeModeIcon className="size-4" />
|
||||
<ComposerControlIcon icon={RuntimeModeIcon} />
|
||||
<SelectValue>{runtimeModeOption.label}</SelectValue>
|
||||
</TooltipTrigger>
|
||||
<SelectPopup alignItemWithTrigger={false}>
|
||||
@@ -393,22 +385,21 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
<ComposerControl
|
||||
className={cn(
|
||||
"shrink-0 whitespace-nowrap px-2 sm:px-3",
|
||||
"shrink-0 whitespace-nowrap",
|
||||
props.planSidebarOpen
|
||||
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
|
||||
: "text-muted-foreground/70 hover:text-foreground/80",
|
||||
)}
|
||||
size="sm"
|
||||
type="button"
|
||||
onClick={props.onTogglePlanSidebar}
|
||||
aria-label={planSidebarTooltip}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<ListTodoIcon
|
||||
<ComposerControlIcon
|
||||
icon={ListTodoIcon}
|
||||
className={props.planSidebarOpen ? "text-current opacity-100" : undefined}
|
||||
/>
|
||||
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
|
||||
|
||||
@@ -93,7 +93,7 @@ export function ComposerBannerStack({ className, items }: ComposerBannerStackPro
|
||||
{showCollapsedStackCap ? (
|
||||
<div
|
||||
className={cn(
|
||||
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-xl",
|
||||
"pointer-events-none absolute inset-x-0 -top-3 z-0 mx-auto h-3 rounded-t-[22px]",
|
||||
"border border-b-0 border-warning/24 bg-background/96 shadow-[0_6px_18px_rgba(0,0,0,0.06)]",
|
||||
"transition-opacity duration-150 ease-out",
|
||||
"group-hover/banner-stack:opacity-0 group-focus-within/banner-stack:opacity-0",
|
||||
@@ -174,7 +174,7 @@ function ComposerBannerStackAlert({
|
||||
return (
|
||||
<Alert
|
||||
variant={item.variant}
|
||||
className={cn("alert-glass", item.className)}
|
||||
className={cn("alert-glass rounded-[22px]", item.className)}
|
||||
data-variant={item.variant}
|
||||
>
|
||||
{item.icon}
|
||||
|
||||
@@ -139,7 +139,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div ref={listRef} className="dropdown-glass relative w-full overflow-hidden rounded-[20px]">
|
||||
<div
|
||||
ref={listRef}
|
||||
className="dropdown-glass relative w-full overflow-hidden rounded-[20px] **:data-[slot=scroll-area-scrollbar]:data-[orientation=vertical]:my-4"
|
||||
>
|
||||
{props.items.length > 0 ? (
|
||||
<CommandList className="max-h-72">
|
||||
{groups.map((group, groupIndex) => (
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import type { ComponentProps } from "react";
|
||||
import { ChevronDownIcon, type LucideIcon } from "lucide-react";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { SelectTrigger } from "../ui/select";
|
||||
|
||||
const composerControlClassName =
|
||||
"h-7 min-h-7 gap-1.5 px-2.5 text-muted-foreground/70 transition-none hover:text-foreground/80 [&_svg[data-composer-control-icon]]:mx-0 [&_svg[data-composer-control-chevron]]:-mx-0.5";
|
||||
|
||||
export function ComposerControl({
|
||||
className,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ComponentProps<typeof Button>) {
|
||||
return (
|
||||
<Button
|
||||
className={cn(composerControlClassName, className)}
|
||||
size={size}
|
||||
variant={variant}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerControlIcon({
|
||||
icon: Icon,
|
||||
className,
|
||||
opticalSize = "default",
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
className?: string | undefined;
|
||||
opticalSize?: "default" | "large";
|
||||
}) {
|
||||
return (
|
||||
<Icon
|
||||
aria-hidden="true"
|
||||
className={cn("shrink-0", opticalSize === "large" ? "size-4.5" : "size-4", className)}
|
||||
data-composer-control-icon
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerControlChevron() {
|
||||
return (
|
||||
<ChevronDownIcon
|
||||
aria-hidden="true"
|
||||
className="-mx-0.5 size-3.5 shrink-0 text-muted-foreground opacity-70"
|
||||
data-composer-control-chevron
|
||||
strokeWidth={2.25}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ComposerSelectControl({
|
||||
className,
|
||||
size = "sm",
|
||||
variant = "ghost",
|
||||
...props
|
||||
}: ComponentProps<typeof SelectTrigger>) {
|
||||
return (
|
||||
<SelectTrigger
|
||||
className={cn(composerControlClassName, className)}
|
||||
icon={<ComposerControlChevron />}
|
||||
size={size}
|
||||
variant={variant}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -101,11 +101,11 @@ export function DraftHeroHeadline({
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
aria-label={hasResolvedProject ? "Change project" : "Choose a project"}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-foreground underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline cursor-pointer border-foreground/60 border-b border-dotted text-foreground transition-colors hover:border-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectDisplayName ?? "Choose a project"}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="center" className="max-h-80 w-64 overflow-y-auto">
|
||||
<MenuPopup align="center" className="max-h-80 min-w-40! w-max max-w-64 overflow-y-auto">
|
||||
<MenuRadioGroup
|
||||
value={activeProjectKey}
|
||||
onValueChange={(value) => {
|
||||
@@ -138,7 +138,7 @@ export function DraftHeroHeadline({
|
||||
<button
|
||||
type="button"
|
||||
onClick={openAddProject}
|
||||
className="pointer-events-auto inline cursor-pointer border-current border-b border-dotted text-muted-foreground/60 underline-offset-8 transition-opacity hover:opacity-75 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
className="pointer-events-auto inline cursor-pointer border-muted-foreground/35 border-b border-dotted text-muted-foreground/60 transition-colors hover:border-muted-foreground/60 hover:text-muted-foreground/80 focus-visible:rounded-sm focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
{activeProjectTitle ?? "Add a project"}
|
||||
</button>
|
||||
|
||||
@@ -50,7 +50,7 @@ export const ModelListRow = memo(function ModelListRow(props: {
|
||||
disabled={Boolean(props.disabledReason)}
|
||||
contentClassName="flex w-full items-center gap-3"
|
||||
className={cn(
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2.5 transition-[background-color,box-shadow,color]",
|
||||
"group relative w-full !min-w-0 max-w-full cursor-pointer rounded-md px-2 py-2 transition-[background-color,box-shadow,color]",
|
||||
"hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-highlighted:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] data-selected:bg-foreground/[0.08] data-selected:text-foreground data-selected:ring-0 [&[data-highlighted][data-selected]]:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))]",
|
||||
props.disabledReason &&
|
||||
"data-disabled:pointer-events-auto data-disabled:cursor-not-allowed data-disabled:hover:bg-transparent",
|
||||
|
||||
@@ -43,6 +43,10 @@ type ModelPickerItem = {
|
||||
|
||||
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
|
||||
|
||||
function ModelListSeparator() {
|
||||
return <div className="h-0.5" />;
|
||||
}
|
||||
|
||||
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
|
||||
// can contain colons (e.g. some vendor model ids), so we only split on the
|
||||
// first colon — anything after that is the slug.
|
||||
@@ -521,7 +525,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
return (
|
||||
<TooltipProvider delay={0}>
|
||||
<div
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-96 w-screen max-w-100 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
className="dropdown-glass model-picker-surface relative flex h-screen max-h-86.5 w-screen max-w-90 flex-row overflow-hidden rounded-lg text-popover-foreground [clip-path:inset(0_round_var(--radius-lg))]"
|
||||
data-model-picker-content="true"
|
||||
>
|
||||
{/* Sidebar */}
|
||||
@@ -571,12 +575,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
<div
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col overflow-hidden bg-muted/40",
|
||||
showSidebar && "border-l",
|
||||
showSidebar && "border-l border-border/70",
|
||||
)}
|
||||
>
|
||||
{/* Search bar */}
|
||||
<div className="px-4 pt-2.5">
|
||||
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<div className="px-2 pt-2">
|
||||
<div className="border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
|
||||
<ComboboxInput
|
||||
ref={searchInputRef}
|
||||
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
|
||||
@@ -584,7 +588,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
placeholder="Search models..."
|
||||
showTrigger={false}
|
||||
startAddon={
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
|
||||
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground opacity-70" />
|
||||
}
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
@@ -618,8 +622,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
</div>
|
||||
|
||||
{/* Model list */}
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
<ComboboxListVirtualized className="model-picker-list size-full min-w-0 p-0">
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden pr-px">
|
||||
<ComboboxListVirtualized className="size-full min-w-0 p-0 not-empty:p-0">
|
||||
<LegendList<string>
|
||||
ref={modelListRef}
|
||||
data={filteredModelKeys}
|
||||
@@ -656,12 +660,14 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
|
||||
estimatedItemSize={60}
|
||||
drawDistance={480}
|
||||
recycleItems
|
||||
contentContainerClassName="pl-2 pr-px"
|
||||
ItemSeparatorComponent={ModelListSeparator}
|
||||
onLayout={updateModelListScrollFades}
|
||||
onScroll={updateModelListScrollFades}
|
||||
className={cn(
|
||||
"scrollbar-gutter-both h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
showTopScrollFade && "mask-t-from-[calc(100%-var(--fade-size))]",
|
||||
showBottomScrollFade && "mask-b-from-[calc(100%-var(--fade-size))]",
|
||||
"model-picker-list h-full overflow-x-hidden overscroll-y-contain py-1.5 [--fade-size:1.5rem]",
|
||||
showTopScrollFade && "model-picker-list-scroll-fade-top",
|
||||
showBottomScrollFade && "model-picker-list-scroll-fade-bottom",
|
||||
)}
|
||||
/>
|
||||
</ComboboxListVirtualized>
|
||||
|
||||
@@ -78,34 +78,20 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
if (!content) {
|
||||
return;
|
||||
}
|
||||
const selectedButton = Array.from(
|
||||
const selectedItem = Array.from(
|
||||
content.querySelectorAll<HTMLElement>("[data-model-picker-provider]"),
|
||||
).find((button) => button.dataset.modelPickerProvider === props.selectedInstanceId);
|
||||
if (!selectedButton) {
|
||||
).find((item) => item.dataset.modelPickerProvider === props.selectedInstanceId);
|
||||
if (!selectedItem) {
|
||||
setSelectedIndicatorTop(null);
|
||||
return;
|
||||
}
|
||||
const contentRect = content.getBoundingClientRect();
|
||||
const selectedButtonRect = selectedButton.getBoundingClientRect();
|
||||
setSelectedIndicatorTop(
|
||||
selectedButtonRect.top -
|
||||
contentRect.top +
|
||||
content.scrollTop +
|
||||
selectedButtonRect.height / 2 -
|
||||
10,
|
||||
);
|
||||
setSelectedIndicatorTop(selectedItem.offsetTop + selectedItem.offsetHeight / 2 - 10);
|
||||
}, [props.instanceEntries, props.selectedInstanceId, showFavorites]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="w-12 shrink-0 overflow-hidden border-r bg-muted/30"
|
||||
data-model-picker-sidebar="true"
|
||||
>
|
||||
<div className="w-11 shrink-0 overflow-hidden bg-muted/30" data-model-picker-sidebar="true">
|
||||
<div className="h-full overflow-y-auto overscroll-contain [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
|
||||
<div
|
||||
ref={sidebarContentRef}
|
||||
className="relative flex min-h-full flex-col gap-1 px-1 pb-1 pt-0.5"
|
||||
>
|
||||
<div ref={sidebarContentRef} className="relative flex min-h-full flex-col gap-1 p-1">
|
||||
{selectedIndicatorTop !== null ? (
|
||||
<div
|
||||
data-model-picker-selected-indicator="true"
|
||||
@@ -118,8 +104,8 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
) : null}
|
||||
{/* Favorites section */}
|
||||
{showFavorites ? (
|
||||
<div className="mb-1 border-b pb-1">
|
||||
<div className="relative w-full">
|
||||
<>
|
||||
<div className="relative w-full" data-model-picker-provider="favorites">
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
@@ -129,7 +115,6 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
)}
|
||||
onClick={() => handleSelect("favorites")}
|
||||
type="button"
|
||||
data-model-picker-provider="favorites"
|
||||
aria-label="Favorites"
|
||||
>
|
||||
<StarIcon className="size-5 fill-current shrink-0" aria-hidden />
|
||||
@@ -146,7 +131,8 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
<div className="border-b border-border/70" aria-hidden="true" />
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{/* Instance buttons (one per configured instance — built-in + custom) */}
|
||||
@@ -170,7 +156,6 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
|
||||
const button = (
|
||||
<button
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
className={cn(
|
||||
"relative isolate flex w-full cursor-pointer aspect-square items-center justify-center rounded-md transition-colors hover:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:bg-[color-mix(in_srgb,var(--popover)_90%,var(--foreground))] focus-visible:outline-none",
|
||||
isDisabled && "opacity-50 cursor-not-allowed hover:bg-transparent",
|
||||
@@ -228,7 +213,11 @@ export const ModelPickerSidebar = memo(function ModelPickerSidebar(props: {
|
||||
);
|
||||
|
||||
return (
|
||||
<div key={entry.instanceId} className="relative w-full">
|
||||
<div
|
||||
key={entry.instanceId}
|
||||
className="relative w-full"
|
||||
data-model-picker-provider={entry.instanceId}
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger render={trigger} />
|
||||
<TooltipPopup
|
||||
|
||||
@@ -5,8 +5,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { memo, useEffect, useMemo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import { buttonVariants } from "../ui/button";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -18,6 +17,7 @@ import {
|
||||
getTriggerDisplayModelName,
|
||||
} from "./providerIconUtils";
|
||||
import type { ProviderInstanceEntry } from "../../providerInstances";
|
||||
import { ComposerControl, ComposerControlChevron } from "./ComposerControl";
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
/**
|
||||
@@ -39,6 +39,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
open?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
triggerAriaLabel?: string;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
getModelDisabledReason?: (instanceId: ProviderInstanceId, model: string) => string | null;
|
||||
onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void;
|
||||
@@ -145,27 +146,27 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
<ComposerControl
|
||||
aria-label={props.triggerAriaLabel}
|
||||
variant={props.triggerVariant ?? "ghost"}
|
||||
data-chat-provider-model-picker="true"
|
||||
className={cn(
|
||||
"min-w-0 justify-between whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
|
||||
"min-w-0 justify-between whitespace-nowrap",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56",
|
||||
props.triggerClassName,
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
{activeEntry ? (
|
||||
<ProviderInstanceIcon
|
||||
driverKind={activeEntry.driverKind}
|
||||
displayName={activeEntry.displayName}
|
||||
accentColor={activeEntry.accentColor}
|
||||
showBadge={showInstanceBadge}
|
||||
className={showInstanceBadge ? "size-5" : "size-4"}
|
||||
className="size-4"
|
||||
iconClassName={cn("size-4", props.activeProviderIconClassName)}
|
||||
indicatorBackground="var(--input)"
|
||||
badgeClassName={cn(
|
||||
@@ -182,7 +183,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
</Tooltip>
|
||||
</span>
|
||||
<span aria-hidden="true" className="flex items-center">
|
||||
<ChevronDownIcon aria-hidden="true" className="!ms-0 !-me-1 size-3 shrink-0 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
<PopoverPopup
|
||||
|
||||
@@ -16,8 +16,8 @@ import {
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon, ZapIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import { ZapIcon } from "lucide-react";
|
||||
import { buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
@@ -31,6 +31,7 @@ import { useComposerDraftStore, DraftId } from "../../composerDraftStore";
|
||||
import { getProviderModelCapabilities } from "../../providerModels";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { ComposerControl, ComposerControlChevron, ComposerControlIcon } from "./ComposerControl";
|
||||
|
||||
type ProviderOptions = ReadonlyArray<ProviderOptionSelection>;
|
||||
|
||||
@@ -463,7 +464,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
});
|
||||
const fastModeIcon = showFastModeIcon ? (
|
||||
<>
|
||||
<ZapIcon aria-hidden="true" className="size-3 shrink-0 text-foreground/80 opacity-100" />
|
||||
<ComposerControlIcon icon={ZapIcon} className="text-foreground/80 opacity-100" />
|
||||
<span className="sr-only">Fast mode on</span>
|
||||
</>
|
||||
) : null;
|
||||
@@ -479,13 +480,12 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
<ComposerControl
|
||||
variant={triggerVariant ?? "ghost"}
|
||||
className={cn(
|
||||
isCodexStyle
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
: "shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3",
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap sm:max-w-48"
|
||||
: "shrink-0 whitespace-nowrap",
|
||||
triggerClassName,
|
||||
)}
|
||||
/>
|
||||
@@ -495,13 +495,13 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
<span className="flex min-w-0 w-full items-center gap-1.5 overflow-hidden">
|
||||
{fastModeIcon}
|
||||
<span className="min-w-0 truncate">{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
{fastModeIcon}
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
<ComposerControlChevron />
|
||||
</>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
|
||||
@@ -53,12 +53,8 @@ function ConfiguredT3ConnectSidebarSignIn() {
|
||||
<>
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={openAuthPrompt}
|
||||
>
|
||||
<LogInIcon className="size-4 shrink-0" />
|
||||
<SidebarMenuButton onClick={openAuthPrompt}>
|
||||
<LogInIcon />
|
||||
<span>Sign in to T3 Connect</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -32,12 +32,14 @@ import {
|
||||
import { usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
|
||||
import { resolveBrowserNavigationTarget } from "~/browser/browserTargetResolver";
|
||||
import {
|
||||
readActiveBrowserRecordingTabIds,
|
||||
readActiveBrowserRecordingTargets,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
} from "~/browser/browserRecording";
|
||||
import { resolveBrowserRecordingStopTarget } from "~/browser/browserRecordingScope";
|
||||
import { useBrowserSurfaceStore } from "~/browser/browserSurfaceStore";
|
||||
import { runBrowserViewportMutation } from "~/browser/browserViewportActions";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { isElectron } from "~/env";
|
||||
import { useEnvironments } from "~/state/environments";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
@@ -46,7 +48,6 @@ import { useAtomCommand } from "~/state/use-atom-command";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
import {
|
||||
PreviewAutomationNavigationTimeoutError,
|
||||
PreviewAutomationOperationError,
|
||||
PreviewAutomationOverlayTimeoutError,
|
||||
PreviewAutomationRecordingNotActiveError,
|
||||
@@ -54,9 +55,14 @@ import {
|
||||
PreviewAutomationViewportTimeoutError,
|
||||
} from "./previewAutomationErrors";
|
||||
import {
|
||||
previewAutomationDefaultViewport,
|
||||
previewAutomationOpenNeedsOverlay,
|
||||
shouldOpenPreviewMiniPlayer,
|
||||
} from "./previewAutomationOpenReadiness";
|
||||
import {
|
||||
assertPreviewRuntimeCurrent,
|
||||
waitForNavigationReadiness,
|
||||
} from "./previewNavigationReadiness";
|
||||
import { createPreviewAutomationRequestConsumerAtom } from "./previewAutomationRequestConsumer";
|
||||
import { createPreviewAutomationClientId } from "./previewAutomationClientId";
|
||||
import {
|
||||
@@ -65,18 +71,34 @@ import {
|
||||
resolvePreviewAutomationTarget,
|
||||
} from "./previewAutomationTarget";
|
||||
import { isPreviewViewportReady } from "./previewViewportReadiness";
|
||||
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
|
||||
|
||||
const PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS = 500;
|
||||
|
||||
const waitForPreviewPresentation = async (runtimeTabId: string): Promise<void> => {
|
||||
const deadline = Date.now() + PREVIEW_PRESENTATION_SETTLE_TIMEOUT_MS;
|
||||
while (Date.now() <= deadline) {
|
||||
if (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible) return;
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 16));
|
||||
}
|
||||
};
|
||||
|
||||
const waitForDesktopOverlay = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
operation: PreviewAutomationRequest["operation"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const state = assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, {
|
||||
operation,
|
||||
requestId,
|
||||
});
|
||||
if (state.desktopByTabId[tabId] && previewBridge) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
if (status.available) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
@@ -89,38 +111,6 @@ const waitForDesktopOverlay = async (
|
||||
});
|
||||
};
|
||||
|
||||
const waitForNavigationReadiness = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
readiness: PreviewAutomationNavigateInput["readiness"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> => {
|
||||
const targetReadiness = readiness ?? "load";
|
||||
if (!previewBridge || targetReadiness === "none") return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
if (targetReadiness === "domContentLoaded") {
|
||||
const readyState = await previewBridge.automation.evaluate(tabId, {
|
||||
expression: "document.readyState",
|
||||
});
|
||||
if (readyState === "interactive" || readyState === "complete") return;
|
||||
} else {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
if (!status.loading) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
}
|
||||
throw new PreviewAutomationNavigationTimeoutError({
|
||||
requestId,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
readiness: targetReadiness,
|
||||
timeoutMs,
|
||||
});
|
||||
};
|
||||
|
||||
interface ExecutablePreviewWebview extends Element {
|
||||
readonly executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
|
||||
}
|
||||
@@ -148,8 +138,10 @@ const readWebviewViewport = async (
|
||||
: null;
|
||||
};
|
||||
|
||||
const readRenderedViewport = async (tabId: string): Promise<PreviewRenderedViewportSize | null> => {
|
||||
const webview = findPreviewWebview(tabId);
|
||||
const readRenderedViewport = async (
|
||||
runtimeTabId: string,
|
||||
): Promise<PreviewRenderedViewportSize | null> => {
|
||||
const webview = findPreviewWebview(runtimeTabId);
|
||||
if (!webview) return null;
|
||||
return await readWebviewViewport(webview);
|
||||
};
|
||||
@@ -165,19 +157,23 @@ const readDeclaredViewport = (
|
||||
};
|
||||
|
||||
const waitForRenderedViewport = async (
|
||||
threadRef: ScopedThreadRef,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
setting: PreviewViewportSetting,
|
||||
timeoutMs: number,
|
||||
context: {
|
||||
readonly requestId: PreviewAutomationRequest["requestId"];
|
||||
readonly operation: PreviewAutomationRequest["operation"];
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly threadId: PreviewAutomationRequest["threadId"];
|
||||
},
|
||||
): Promise<PreviewRenderedViewportSize> => {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, context);
|
||||
try {
|
||||
const webview = findPreviewWebview(tabId);
|
||||
const webview = findPreviewWebview(runtimeTabId);
|
||||
const appliedSettingKey = webview?.getAttribute("data-preview-viewport-key") ?? null;
|
||||
const declaredViewport = readDeclaredViewport(webview);
|
||||
const renderedViewport = webview ? await readWebviewViewport(webview) : null;
|
||||
@@ -211,18 +207,19 @@ const currentStatus = async (
|
||||
): Promise<PreviewAutomationStatus> => {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
const { snapshot, tabId } = resolvePreviewAutomationTarget(state, requestedTabId);
|
||||
const visible = tabId
|
||||
? (useBrowserSurfaceStore.getState().byTabId[tabId]?.visible ?? false)
|
||||
const runtimeTabId = tabId ? previewRuntimeTabId(threadRef, state.serverEpoch, tabId) : null;
|
||||
const visible = runtimeTabId
|
||||
? (useBrowserSurfaceStore.getState().byTabId[runtimeTabId]?.visible ?? false)
|
||||
: false;
|
||||
const viewportSetting = snapshot ? (snapshot.viewport ?? FILL_PREVIEW_VIEWPORT) : undefined;
|
||||
const viewport = tabId ? await readRenderedViewport(tabId).catch(() => null) : null;
|
||||
const viewport = runtimeTabId ? await readRenderedViewport(runtimeTabId).catch(() => null) : null;
|
||||
const viewportStatus = {
|
||||
...(viewportSetting === undefined ? {} : { viewportSetting }),
|
||||
...(viewport === null ? {} : { viewport }),
|
||||
};
|
||||
if (tabId && previewBridge && state.desktopByTabId[tabId]) {
|
||||
const status = await previewBridge.automation.status(tabId);
|
||||
return { ...status, visible, ...viewportStatus };
|
||||
if (runtimeTabId && tabId && previewBridge && state.desktopByTabId[tabId]) {
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
return { ...status, tabId, visible, ...viewportStatus };
|
||||
}
|
||||
const navStatus = snapshot?.navStatus;
|
||||
return {
|
||||
@@ -340,8 +337,21 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
if (!bridge || !readyTabId) {
|
||||
throw new PreviewAutomationTargetUnavailableError(unavailableTarget);
|
||||
}
|
||||
await waitForDesktopOverlay(threadRef, request.requestId, readyTabId, request.timeoutMs);
|
||||
return { bridge, tabId: readyTabId };
|
||||
const readyState = readThreadPreviewState(threadRef);
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, readyState.serverEpoch, readyTabId);
|
||||
await waitForDesktopOverlay(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
readyTabId,
|
||||
runtimeTabId,
|
||||
request.operation,
|
||||
request.timeoutMs,
|
||||
);
|
||||
return {
|
||||
bridge,
|
||||
tabId: readyTabId,
|
||||
runtimeTabId,
|
||||
};
|
||||
};
|
||||
switch (request.operation) {
|
||||
case "status":
|
||||
@@ -381,7 +391,45 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
activeSnapshot = snapshot;
|
||||
tabId = activeTabId;
|
||||
}
|
||||
if (shouldOpenPreviewMiniPlayer(input)) {
|
||||
const activeRuntimeTabId = previewRuntimeTabId(
|
||||
threadRef,
|
||||
readThreadPreviewState(threadRef).serverEpoch,
|
||||
activeTabId,
|
||||
);
|
||||
if (activeSnapshot) {
|
||||
const defaultViewport = previewAutomationDefaultViewport(
|
||||
reusedExistingTab,
|
||||
activeSnapshot,
|
||||
);
|
||||
if (defaultViewport) {
|
||||
const resizeResult = await runBrowserViewportMutation(
|
||||
activeRuntimeTabId,
|
||||
async () => {
|
||||
assertPreviewRuntimeCurrent(
|
||||
threadRef,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request,
|
||||
);
|
||||
return await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: activeTabId,
|
||||
viewport: defaultViewport,
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
if (resizeResult._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(resizeResult);
|
||||
}
|
||||
activeSnapshot = resizeResult.value;
|
||||
updatePreviewServerSnapshot(threadRef, resizeResult.value);
|
||||
}
|
||||
}
|
||||
const shouldPresentPreview = shouldOpenPreviewMiniPlayer(input);
|
||||
if (shouldPresentPreview) {
|
||||
usePreviewMiniPlayerStore.getState().open(threadRef, activeTabId);
|
||||
}
|
||||
if (activeSnapshot && previewAutomationOpenNeedsOverlay(input, activeSnapshot)) {
|
||||
@@ -389,15 +437,27 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
threadRef,
|
||||
request.requestId,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request.operation,
|
||||
request.timeoutMs,
|
||||
);
|
||||
}
|
||||
if (shouldPresentPreview) {
|
||||
// React commits the thread-bound surface asynchronously. Settle
|
||||
// briefly so active-thread opens report visible=true, without
|
||||
// turning a background thread's offscreen mini player into an
|
||||
// operation failure.
|
||||
await waitForPreviewPresentation(activeRuntimeTabId);
|
||||
}
|
||||
if (reusedExistingTab && resolvedInputUrl && previewBridge) {
|
||||
await previewBridge.navigate(activeTabId, resolvedInputUrl);
|
||||
assertPreviewRuntimeCurrent(threadRef, activeTabId, activeRuntimeTabId, request);
|
||||
await previewBridge.navigate(activeRuntimeTabId, resolvedInputUrl);
|
||||
await waitForNavigationReadiness(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
activeTabId,
|
||||
activeRuntimeTabId,
|
||||
request.operation,
|
||||
"load",
|
||||
request.timeoutMs,
|
||||
);
|
||||
@@ -414,11 +474,13 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
url: input.url!,
|
||||
},
|
||||
);
|
||||
await ready.bridge.navigate(ready.tabId, resolution.resolvedUrl);
|
||||
await ready.bridge.navigate(ready.runtimeTabId, resolution.resolvedUrl);
|
||||
await waitForNavigationReadiness(
|
||||
threadRef,
|
||||
request.requestId,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.operation,
|
||||
input.readiness ?? "load",
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
);
|
||||
@@ -428,28 +490,76 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationResizeInput;
|
||||
const setting = resolvePreviewViewport(input);
|
||||
const result = await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: setting,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(result);
|
||||
}
|
||||
updatePreviewServerSnapshot(threadRef, result.value);
|
||||
const viewport = await waitForRenderedViewport(
|
||||
ready.tabId,
|
||||
setting,
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
{
|
||||
requestId: request.requestId,
|
||||
const applied = await runBrowserViewportMutation(ready.runtimeTabId, async () => {
|
||||
const operationState = assertPreviewRuntimeCurrent(
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request,
|
||||
);
|
||||
const previousSetting =
|
||||
operationState.sessions[ready.tabId]?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
const result = await resize({
|
||||
environmentId,
|
||||
threadId: request.threadId,
|
||||
},
|
||||
);
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: setting,
|
||||
},
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
return raiseAtomCommandFailure(result);
|
||||
}
|
||||
updatePreviewServerSnapshot(threadRef, result.value);
|
||||
return {
|
||||
previousSetting,
|
||||
serverEpoch: operationState.serverEpoch,
|
||||
};
|
||||
});
|
||||
let viewport: PreviewRenderedViewportSize;
|
||||
try {
|
||||
viewport = await waitForRenderedViewport(
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
setting,
|
||||
input.timeoutMs ?? request.timeoutMs,
|
||||
{
|
||||
requestId: request.requestId,
|
||||
operation: request.operation,
|
||||
environmentId,
|
||||
threadId: request.threadId,
|
||||
},
|
||||
);
|
||||
} catch (cause) {
|
||||
await runBrowserViewportMutation(ready.runtimeTabId, async () => {
|
||||
const latestState = readThreadPreviewState(threadRef);
|
||||
const latestSetting =
|
||||
latestState.sessions[ready.tabId]?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
if (
|
||||
shouldRollbackPreviewViewport(
|
||||
applied.previousSetting,
|
||||
setting,
|
||||
latestSetting,
|
||||
applied.serverEpoch,
|
||||
latestState.serverEpoch,
|
||||
)
|
||||
) {
|
||||
const rollback = await resize({
|
||||
environmentId,
|
||||
input: {
|
||||
threadId: request.threadId,
|
||||
tabId: ready.tabId,
|
||||
viewport: applied.previousSetting,
|
||||
},
|
||||
});
|
||||
if (rollback._tag !== "Failure") {
|
||||
updatePreviewServerSnapshot(threadRef, rollback.value);
|
||||
}
|
||||
}
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
setting,
|
||||
@@ -459,7 +569,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
case "setColorScheme": {
|
||||
const ready = await requireReadyTab();
|
||||
const input = request.input as PreviewAutomationSetColorSchemeInput;
|
||||
await ready.bridge.setColorScheme(ready.tabId, input.colorScheme);
|
||||
await ready.bridge.setColorScheme(ready.runtimeTabId, input.colorScheme);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
colorScheme: input.colorScheme,
|
||||
@@ -467,53 +577,57 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
}
|
||||
case "snapshot": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.snapshot(ready.tabId);
|
||||
return await ready.bridge.automation.snapshot(ready.runtimeTabId);
|
||||
}
|
||||
case "click": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.click(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.click>[1],
|
||||
);
|
||||
}
|
||||
case "type": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.type(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.type>[1],
|
||||
);
|
||||
}
|
||||
case "press": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.press(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.press>[1],
|
||||
);
|
||||
}
|
||||
case "scroll": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.scroll(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.scroll>[1],
|
||||
);
|
||||
}
|
||||
case "evaluate": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.evaluate(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.evaluate>[1],
|
||||
);
|
||||
}
|
||||
case "waitFor": {
|
||||
const ready = await requireReadyTab();
|
||||
return await ready.bridge.automation.waitFor(
|
||||
ready.tabId,
|
||||
ready.runtimeTabId,
|
||||
request.input as Parameters<typeof ready.bridge.automation.waitFor>[1],
|
||||
);
|
||||
}
|
||||
case "recordingStart": {
|
||||
const ready = await requireReadyTab();
|
||||
const startedAt = await startBrowserRecording(ready.tabId, threadRef);
|
||||
const startedAt = await startBrowserRecording(
|
||||
ready.runtimeTabId,
|
||||
threadRef,
|
||||
ready.tabId,
|
||||
);
|
||||
return {
|
||||
tabId: ready.tabId,
|
||||
recording: true,
|
||||
@@ -521,15 +635,21 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
};
|
||||
}
|
||||
case "recordingStop": {
|
||||
const activeTabIds = readActiveBrowserRecordingTabIds(threadRef);
|
||||
const activeRecordings = readActiveBrowserRecordingTargets(threadRef);
|
||||
const activeTabIds = new Set(
|
||||
activeRecordings.map((recording) => recording.serverTabId),
|
||||
);
|
||||
const stopTabId = resolveBrowserRecordingStopTarget(
|
||||
activeTabIds,
|
||||
tabId,
|
||||
request.tabIdExplicit ? request.tabId : undefined,
|
||||
);
|
||||
tabId = stopTabId ?? tabId;
|
||||
const artifact = stopTabId ? await stopBrowserRecording(stopTabId) : null;
|
||||
if (!artifact) {
|
||||
const stopRuntimeTabId =
|
||||
activeRecordings.find((recording) => recording.serverTabId === stopTabId)
|
||||
?.runtimeTabId ?? null;
|
||||
const artifact = stopRuntimeTabId ? await stopBrowserRecording(stopRuntimeTabId) : null;
|
||||
if (!artifact || !stopTabId) {
|
||||
return raisePreviewAutomationHostError(
|
||||
new PreviewAutomationRecordingNotActiveError({
|
||||
requestId: request.requestId,
|
||||
@@ -539,7 +659,7 @@ function PreviewAutomationHost(props: { readonly environmentId: EnvironmentId })
|
||||
}),
|
||||
);
|
||||
}
|
||||
return artifact;
|
||||
return { ...artifact, tabId: stopTabId };
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
|
||||
@@ -90,6 +90,7 @@ vi.mock("~/state/use-atom-command", () => ({
|
||||
}));
|
||||
|
||||
vi.mock("~/browser/browserRecording", () => ({
|
||||
findActiveBrowserRecordingRuntimeTabId: vi.fn(() => null),
|
||||
startBrowserRecording: vi.fn(),
|
||||
stopBrowserRecording: vi.fn(),
|
||||
useActiveBrowserRecordingTabIds: () => new Set(),
|
||||
@@ -188,6 +189,13 @@ vi.mock("./useLoadingProgress", () => ({ useLoadingProgress: () => 0 }));
|
||||
vi.mock("./usePreviewSession", () => ({ usePreviewSession: vi.fn() }));
|
||||
|
||||
import { PreviewView } from "./PreviewView";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
|
||||
const TEST_THREAD_REF = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
} as const;
|
||||
const TEST_RUNTIME_TAB_ID = previewRuntimeTabId(TEST_THREAD_REF, null, "tab-1");
|
||||
|
||||
describe("PreviewView navigation", () => {
|
||||
beforeEach(() => {
|
||||
@@ -230,7 +238,9 @@ describe("PreviewView navigation", () => {
|
||||
expect(mocks.submittedUrl).not.toBeNull();
|
||||
mocks.submittedUrl?.(submitted);
|
||||
|
||||
await vi.waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith("tab-1", expected));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.navigate).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID, expected),
|
||||
);
|
||||
expect(mocks.rememberPreviewUrl).toHaveBeenCalledWith(
|
||||
{
|
||||
environmentId: "environment-1",
|
||||
@@ -258,7 +268,7 @@ describe("PreviewView navigation", () => {
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.navigate).toHaveBeenCalledWith(
|
||||
"tab-1",
|
||||
TEST_RUNTIME_TAB_ID,
|
||||
"http://172.25.85.75:5173/app?mode=test#top",
|
||||
),
|
||||
);
|
||||
@@ -306,11 +316,15 @@ describe("PreviewView navigation", () => {
|
||||
|
||||
renderToStaticMarkup(<PreviewView {...props} />);
|
||||
mocks.toggleNativePictureInPicture?.();
|
||||
await vi.waitFor(() => expect(mocks.openPictureInPicture).toHaveBeenCalledWith("tab-1"));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.openPictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
|
||||
);
|
||||
|
||||
mocks.pictureInPicture = true;
|
||||
renderToStaticMarkup(<PreviewView {...props} />);
|
||||
mocks.toggleNativePictureInPicture?.();
|
||||
await vi.waitFor(() => expect(mocks.closePictureInPicture).toHaveBeenCalledWith("tab-1"));
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.closePictureInPicture).toHaveBeenCalledWith(TEST_RUNTIME_TAB_ID),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ import {
|
||||
subscribeBrowserViewportChange,
|
||||
} from "~/browser/browserViewportActions";
|
||||
import { resolveResponsiveBrowserViewportSize } from "~/browser/browserViewportLayout";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { PreviewUnreachable } from "./PreviewUnreachable";
|
||||
import { revealInFileExplorerLabel } from "./fileExplorerLabel";
|
||||
import { shouldShowPreviewEmptyState } from "./previewEmptyStateLogic";
|
||||
@@ -47,6 +48,7 @@ import { usePreviewSession } from "./usePreviewSession";
|
||||
import { ZoomIndicator } from "./ZoomIndicator";
|
||||
import { AgentBrowserCursor } from "./AgentBrowserCursor";
|
||||
import {
|
||||
findActiveBrowserRecordingRuntimeTabId,
|
||||
startBrowserRecording,
|
||||
stopBrowserRecording,
|
||||
useActiveBrowserRecordingTabIds,
|
||||
@@ -93,6 +95,15 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, []);
|
||||
|
||||
const tabId = requestedTabId ?? previewState.activeTabId;
|
||||
const runtimeTabId = tabId
|
||||
? previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId)
|
||||
: null;
|
||||
const recordingRuntimeTabId =
|
||||
tabId && runtimeTabId
|
||||
? activeRecordingTabIds.has(runtimeTabId)
|
||||
? runtimeTabId
|
||||
: findActiveBrowserRecordingRuntimeTabId(threadRef, tabId)
|
||||
: null;
|
||||
const snapshot = tabId ? (previewState.sessions[tabId] ?? null) : null;
|
||||
const desktopOverlay = tabId ? (previewState.desktopByTabId[tabId] ?? null) : null;
|
||||
const navStatus = snapshot?.navStatus ?? { _tag: "Idle" as const };
|
||||
@@ -115,15 +126,15 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
: undefined;
|
||||
const viewport = snapshot?.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
const panelRect = useBrowserSurfaceStore((state) =>
|
||||
tabId ? (state.byTabId[tabId]?.rect ?? null) : null,
|
||||
runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
|
||||
);
|
||||
|
||||
const navigateToResolvedUrl = useCallback(
|
||||
async (resolvedUrl: string) => {
|
||||
if (tabId && previewBridge) {
|
||||
if (runtimeTabId && previewBridge) {
|
||||
// Drive the webview imperatively; `usePreviewBridge` mirrors the
|
||||
// resolved URL back to the server so other clients stay in sync.
|
||||
await previewBridge.navigate(tabId, resolvedUrl);
|
||||
await previewBridge.navigate(runtimeTabId, resolvedUrl);
|
||||
rememberPreviewUrl(threadRef, resolvedUrl);
|
||||
} else {
|
||||
await openPreviewSession({
|
||||
@@ -133,7 +144,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
});
|
||||
}
|
||||
},
|
||||
[open, tabId, threadRef],
|
||||
[open, runtimeTabId, threadRef],
|
||||
);
|
||||
|
||||
const handleSubmitUrl = useCallback(
|
||||
@@ -159,20 +170,20 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.refresh(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.refresh(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleZoomIn = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.zoomIn(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.zoomIn(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleZoomOut = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.zoomOut(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.zoomOut(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleResetZoom = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.resetZoom(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.resetZoom(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleViewportChange = useCallback(
|
||||
async (nextViewport: PreviewViewportSetting) => {
|
||||
@@ -200,32 +211,32 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
);
|
||||
|
||||
const handleToggleDeviceToolbar = () => {
|
||||
if (!tabId) return;
|
||||
if (!runtimeTabId) return;
|
||||
if (viewport._tag !== "fill") {
|
||||
void commitBrowserViewportChange(tabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
|
||||
void commitBrowserViewportChange(runtimeTabId, FILL_PREVIEW_VIEWPORT).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const responsiveSize = panelRect
|
||||
? resolveResponsiveBrowserViewportSize(panelRect, desktopOverlay?.zoomFactor)
|
||||
: { width: 1024, height: 768 };
|
||||
void commitBrowserViewportChange(tabId, { _tag: "freeform", ...responsiveSize }).catch(
|
||||
void commitBrowserViewportChange(runtimeTabId, { _tag: "freeform", ...responsiveSize }).catch(
|
||||
() => undefined,
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!tabId) return;
|
||||
return subscribeBrowserViewportChange(tabId, handleViewportChange);
|
||||
}, [handleViewportChange, tabId]);
|
||||
if (!runtimeTabId) return;
|
||||
return subscribeBrowserViewportChange(runtimeTabId, handleViewportChange);
|
||||
}, [handleViewportChange, runtimeTabId]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.goBack(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.goBack(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleForward = useCallback(() => {
|
||||
if (previewBridge && tabId) void previewBridge.goForward(tabId);
|
||||
}, [tabId]);
|
||||
if (previewBridge && runtimeTabId) void previewBridge.goForward(runtimeTabId);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
const handleOpenInBrowser = useCallback(() => {
|
||||
if (!localApi || !url) return;
|
||||
@@ -243,26 +254,25 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}, [miniPlayer?.tabId, tabId, threadRef]);
|
||||
|
||||
const handleNativePictureInPicture = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId) return;
|
||||
const operation = desktopOverlay?.pictureInPicture
|
||||
? previewBridge.pictureInPicture.close
|
||||
: previewBridge.pictureInPicture.open;
|
||||
void operation(tabId).catch((error) => {
|
||||
void operation(runtimeTabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to update popped-out preview",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [desktopOverlay?.pictureInPicture, tabId]);
|
||||
}, [desktopOverlay?.pictureInPicture, runtimeTabId]);
|
||||
|
||||
const handleCapture = useCallback(
|
||||
(record: boolean) => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId || !tabId) return;
|
||||
const bridge = previewBridge;
|
||||
const recordingThisTab = activeRecordingTabIds.has(tabId);
|
||||
if (recordingThisTab) {
|
||||
void stopBrowserRecording(tabId).then(
|
||||
if (recordingRuntimeTabId) {
|
||||
void stopBrowserRecording(recordingRuntimeTabId).then(
|
||||
(artifact) => {
|
||||
if (!artifact) return;
|
||||
let pathCopied = false;
|
||||
@@ -354,7 +364,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
return;
|
||||
}
|
||||
if (record) {
|
||||
void startBrowserRecording(tabId, threadRef).catch((error) => {
|
||||
void startBrowserRecording(runtimeTabId, threadRef, tabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to start recording",
|
||||
@@ -363,7 +373,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
});
|
||||
return;
|
||||
}
|
||||
void bridge.captureScreenshot(tabId).then(
|
||||
void bridge.captureScreenshot(runtimeTabId).then(
|
||||
(artifact) => {
|
||||
const revealAction = {
|
||||
children: revealInFileExplorerLabel(navigator.platform),
|
||||
@@ -493,13 +503,13 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
},
|
||||
);
|
||||
},
|
||||
[activeRecordingTabIds, tabId, threadRef],
|
||||
[recordingRuntimeTabId, runtimeTabId, tabId, threadRef],
|
||||
);
|
||||
|
||||
const handlePickElement = useCallback(() => {
|
||||
if (!previewBridge || !tabId) return;
|
||||
if (!previewBridge || !runtimeTabId) return;
|
||||
if (pickActiveRef.current) {
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
// Snapshot whatever the user was focused on (typically the chat
|
||||
@@ -513,7 +523,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
setPickActive(true);
|
||||
void (async () => {
|
||||
try {
|
||||
const annotation = await previewBridge.pickElement(tabId);
|
||||
const annotation = await previewBridge.pickElement(runtimeTabId);
|
||||
if (!annotation) return;
|
||||
addPreviewAnnotation(threadRef, annotation);
|
||||
const screenshotFile = await previewAnnotationScreenshotFile(annotation);
|
||||
@@ -551,7 +561,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
}
|
||||
}
|
||||
})();
|
||||
}, [addImage, addPreviewAnnotation, tabId, threadRef]);
|
||||
}, [addImage, addPreviewAnnotation, runtimeTabId, threadRef]);
|
||||
|
||||
// If the active tab changes mid-pick (close, thread switch, hot restart),
|
||||
// tell main to tear down the in-flight session AND reset our local toggle
|
||||
@@ -560,12 +570,12 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
return () => {
|
||||
if (!pickActiveRef.current) return;
|
||||
pickActiveRef.current = false;
|
||||
if (previewBridge && tabId) {
|
||||
void previewBridge.cancelPickElement(tabId).catch(() => undefined);
|
||||
if (previewBridge && runtimeTabId) {
|
||||
void previewBridge.cancelPickElement(runtimeTabId).catch(() => undefined);
|
||||
}
|
||||
if (isMountedRef.current) setPickActive(false);
|
||||
};
|
||||
}, [tabId]);
|
||||
}, [runtimeTabId]);
|
||||
|
||||
// Subscribe only while visible; `toggle-panel` is owned by ChatView's
|
||||
// URL-aware handler regardless of whether the panel is currently mounted.
|
||||
@@ -615,7 +625,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
onOpenInBrowser={tabId ? handleOpenInBrowser : undefined}
|
||||
onCapture={previewBridge && tabId ? handleCapture : undefined}
|
||||
captureDisabled={!desktopOverlay || isUnreachable}
|
||||
recording={tabId !== null && activeRecordingTabIds.has(tabId)}
|
||||
recording={recordingRuntimeTabId !== null}
|
||||
onPictureInPicture={previewBridge && tabId ? handlePictureInPicture : undefined}
|
||||
pictureInPicture={miniPlayer?.tabId === tabId}
|
||||
pictureInPictureDisabled={!desktopOverlay?.hasWebContents || isUnreachable}
|
||||
@@ -631,7 +641,7 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
trailingActions={
|
||||
previewBridge ? (
|
||||
<PreviewMoreMenu
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
hasWebContents={desktopOverlay?.hasWebContents ?? false}
|
||||
zoomFactor={desktopOverlay?.zoomFactor ?? 1}
|
||||
colorScheme={desktopOverlay?.colorScheme ?? "system"}
|
||||
@@ -645,10 +655,10 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
/>
|
||||
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
{tabId && snapshot && !showEmptyState ? (
|
||||
{runtimeTabId && snapshot && !showEmptyState ? (
|
||||
<BrowserSurfaceSlot
|
||||
key={tabId}
|
||||
tabId={tabId}
|
||||
key={runtimeTabId}
|
||||
tabId={runtimeTabId}
|
||||
visible={visible && !isUnreachable}
|
||||
className="absolute inset-0 h-full w-full"
|
||||
/>
|
||||
@@ -664,9 +674,9 @@ export function PreviewView({ threadRef, tabId: requestedTabId, configuredUrls,
|
||||
{snapshot && desktopOverlay ? (
|
||||
<ZoomIndicator zoomFactor={desktopOverlay.zoomFactor} />
|
||||
) : null}
|
||||
{tabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
|
||||
{runtimeTabId && desktopOverlay && !showEmptyState && !isUnreachable ? (
|
||||
<AgentBrowserCursor
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
zoomFactor={desktopOverlay.zoomFactor}
|
||||
controller={controller}
|
||||
/>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { PanelRightIcon, PictureInPicture2, XIcon } from "lucide-react";
|
||||
import { type PointerEvent as ReactPointerEvent, useLayoutEffect, useRef } from "react";
|
||||
|
||||
import { BrowserSurfaceSlot } from "~/browser/BrowserSurfaceSlot";
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { useThreadPreviewState } from "~/previewStateStore";
|
||||
@@ -49,6 +50,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
);
|
||||
const previewState = useThreadPreviewState(threadRef);
|
||||
const snapshot = previewState.sessions[tabId] ?? null;
|
||||
const runtimeTabId = previewRuntimeTabId(threadRef, previewState.serverEpoch, tabId);
|
||||
const desktopOverlay = previewState.desktopByTabId[tabId] ?? null;
|
||||
const position = miniPlayer?.tabId === tabId ? miniPlayer.position : null;
|
||||
const size =
|
||||
@@ -69,7 +71,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
const operation = desktopOverlay?.pictureInPicture
|
||||
? previewBridge.pictureInPicture.close
|
||||
: previewBridge.pictureInPicture.open;
|
||||
void operation(tabId).catch((error) => {
|
||||
void operation(runtimeTabId).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to update popped-out preview",
|
||||
@@ -284,7 +286,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
|
||||
<div className="relative h-full min-h-0">
|
||||
<div className="absolute inset-0 z-[29] rounded-xl bg-muted shadow-2xl/35" />
|
||||
<BrowserSurfaceSlot
|
||||
tabId={tabId}
|
||||
tabId={runtimeTabId}
|
||||
visible={Boolean(desktopOverlay?.hasWebContents)}
|
||||
cornerRadius={12}
|
||||
fitSourceContent
|
||||
|
||||
@@ -2,6 +2,8 @@ import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tool
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
DEFAULT_PREVIEW_AUTOMATION_VIEWPORT,
|
||||
previewAutomationDefaultViewport,
|
||||
previewAutomationOpenNeedsOverlay,
|
||||
shouldOpenPreviewMiniPlayer,
|
||||
} from "./previewAutomationOpenReadiness";
|
||||
@@ -58,4 +60,20 @@ describe("preview automation open readiness", () => {
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("gives newly-created automation tabs a stable desktop viewport", () => {
|
||||
expect(previewAutomationDefaultViewport(false, snapshot({ _tag: "Idle" }))).toEqual(
|
||||
DEFAULT_PREVIEW_AUTOMATION_VIEWPORT,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves reused and already-fixed browser viewports", () => {
|
||||
expect(previewAutomationDefaultViewport(true, snapshot({ _tag: "Idle" }))).toBeNull();
|
||||
expect(
|
||||
previewAutomationDefaultViewport(false, {
|
||||
...snapshot({ _tag: "Idle" }),
|
||||
viewport: { _tag: "freeform", width: 900, height: 600 },
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { PreviewAutomationOpenInput, PreviewSessionSnapshot } from "@t3tools/contracts";
|
||||
import {
|
||||
FILL_PREVIEW_VIEWPORT,
|
||||
type PreviewAutomationOpenInput,
|
||||
type PreviewSessionSnapshot,
|
||||
type PreviewViewportSetting,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export const DEFAULT_PREVIEW_AUTOMATION_VIEWPORT = {
|
||||
_tag: "freeform",
|
||||
width: 1280,
|
||||
height: 800,
|
||||
} as const satisfies PreviewViewportSetting;
|
||||
|
||||
export function shouldOpenPreviewMiniPlayer(input: PreviewAutomationOpenInput): boolean {
|
||||
return input.open ?? input.show ?? true;
|
||||
@@ -10,3 +21,13 @@ export function previewAutomationOpenNeedsOverlay(
|
||||
): boolean {
|
||||
return input.url !== undefined || snapshot.navStatus._tag !== "Idle";
|
||||
}
|
||||
|
||||
export function previewAutomationDefaultViewport(
|
||||
reusedExistingTab: boolean,
|
||||
snapshot: PreviewSessionSnapshot,
|
||||
): PreviewViewportSetting | null {
|
||||
const viewport = snapshot.viewport ?? FILL_PREVIEW_VIEWPORT;
|
||||
return !reusedExistingTab && viewport._tag === "fill"
|
||||
? DEFAULT_PREVIEW_AUTOMATION_VIEWPORT
|
||||
: null;
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readThreadPreviewState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/previewStateStore", () => ({
|
||||
applyPreviewServerSnapshot: vi.fn(),
|
||||
readThreadPreviewState: mocks.readThreadPreviewState,
|
||||
reconcilePreviewServerSessions: vi.fn(),
|
||||
updatePreviewServerSnapshot: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./previewBridge", () => ({
|
||||
previewBridge: {
|
||||
automation: {
|
||||
evaluate: vi.fn(),
|
||||
status: vi.fn(),
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
import { previewRuntimeTabId } from "~/browser/previewRuntimeTabId";
|
||||
|
||||
import { PreviewAutomationTargetUnavailableError } from "./previewAutomationErrors";
|
||||
import { waitForNavigationReadiness } from "./previewNavigationReadiness";
|
||||
|
||||
describe("waitForNavigationReadiness", () => {
|
||||
it("rejects a replaced runtime target even when readiness polling is disabled", async () => {
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("environment-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
const tabId = "tab_1";
|
||||
const staleRuntimeTabId = previewRuntimeTabId(threadRef, "epoch-1", tabId);
|
||||
mocks.readThreadPreviewState.mockReturnValue({
|
||||
serverEpoch: "epoch-2",
|
||||
sessions: {
|
||||
[tabId]: { tabId },
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForNavigationReadiness(
|
||||
threadRef,
|
||||
"request-1",
|
||||
tabId,
|
||||
staleRuntimeTabId,
|
||||
"navigate",
|
||||
"none",
|
||||
100,
|
||||
),
|
||||
).rejects.toBeInstanceOf(PreviewAutomationTargetUnavailableError);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import {
|
||||
type PreviewAutomationNavigateInput,
|
||||
type PreviewAutomationRequest,
|
||||
type ScopedThreadRef,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { isCurrentPreviewRuntimeTab } from "~/browser/previewRuntimeTabId";
|
||||
import { readThreadPreviewState } from "~/previewStateStore";
|
||||
|
||||
import { previewBridge } from "./previewBridge";
|
||||
import {
|
||||
PreviewAutomationNavigationTimeoutError,
|
||||
PreviewAutomationTargetUnavailableError,
|
||||
} from "./previewAutomationErrors";
|
||||
|
||||
export function assertPreviewRuntimeCurrent(
|
||||
threadRef: ScopedThreadRef,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
request: Pick<PreviewAutomationRequest, "operation" | "requestId">,
|
||||
) {
|
||||
const state = readThreadPreviewState(threadRef);
|
||||
if (
|
||||
state.sessions[tabId] &&
|
||||
isCurrentPreviewRuntimeTab(threadRef, state.serverEpoch, tabId, runtimeTabId)
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
throw new PreviewAutomationTargetUnavailableError({
|
||||
requestId: request.requestId,
|
||||
operation: request.operation,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
bridgeAvailable: Boolean(previewBridge),
|
||||
});
|
||||
}
|
||||
|
||||
export async function waitForNavigationReadiness(
|
||||
threadRef: ScopedThreadRef,
|
||||
requestId: string,
|
||||
tabId: string,
|
||||
runtimeTabId: string,
|
||||
operation: PreviewAutomationRequest["operation"],
|
||||
readiness: PreviewAutomationNavigateInput["readiness"],
|
||||
timeoutMs: number,
|
||||
): Promise<void> {
|
||||
const targetReadiness = readiness ?? "load";
|
||||
if (!previewBridge) return;
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
|
||||
if (targetReadiness === "none") return;
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() <= deadline) {
|
||||
assertPreviewRuntimeCurrent(threadRef, tabId, runtimeTabId, { operation, requestId });
|
||||
if (targetReadiness === "domContentLoaded") {
|
||||
const readyState = await previewBridge.automation.evaluate(runtimeTabId, {
|
||||
expression: "document.readyState",
|
||||
});
|
||||
if (readyState === "interactive" || readyState === "complete") return;
|
||||
} else {
|
||||
const status = await previewBridge.automation.status(runtimeTabId);
|
||||
if (status.available && !status.loading) return;
|
||||
}
|
||||
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
|
||||
}
|
||||
throw new PreviewAutomationNavigationTimeoutError({
|
||||
requestId,
|
||||
environmentId: threadRef.environmentId,
|
||||
threadId: threadRef.threadId,
|
||||
tabId,
|
||||
readiness: targetReadiness,
|
||||
timeoutMs,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { shouldRollbackPreviewViewport } from "./previewViewportRollback";
|
||||
|
||||
describe("shouldRollbackPreviewViewport", () => {
|
||||
const fill = { _tag: "fill" } as const;
|
||||
const requested = { _tag: "freeform", width: 900, height: 600 } as const;
|
||||
|
||||
it("rolls back a timed-out request that still owns the latest setting", () => {
|
||||
expect(shouldRollbackPreviewViewport(fill, requested, requested, "server-a", "server-a")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not overwrite a newer resize, replacement server, or repeated setting", () => {
|
||||
expect(
|
||||
shouldRollbackPreviewViewport(
|
||||
fill,
|
||||
requested,
|
||||
{
|
||||
_tag: "freeform",
|
||||
width: 1024,
|
||||
height: 768,
|
||||
},
|
||||
"server-a",
|
||||
"server-a",
|
||||
),
|
||||
).toBe(false);
|
||||
expect(shouldRollbackPreviewViewport(fill, requested, requested, "server-a", "server-b")).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
shouldRollbackPreviewViewport(requested, requested, requested, "server-a", "server-a"),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PreviewViewportSetting } from "@t3tools/contracts";
|
||||
|
||||
import { browserViewportSettingKey } from "~/browser/browserViewportLayout";
|
||||
|
||||
export function shouldRollbackPreviewViewport(
|
||||
previous: PreviewViewportSetting,
|
||||
requested: PreviewViewportSetting,
|
||||
latest: PreviewViewportSetting,
|
||||
operationServerEpoch: string | null,
|
||||
currentServerEpoch: string | null,
|
||||
): boolean {
|
||||
const requestedKey = browserViewportSettingKey(requested);
|
||||
return (
|
||||
currentServerEpoch === operationServerEpoch &&
|
||||
browserViewportSettingKey(latest) === requestedKey &&
|
||||
browserViewportSettingKey(previous) !== requestedKey
|
||||
);
|
||||
}
|
||||
@@ -19,8 +19,12 @@ import { previewBridge } from "./previewBridge";
|
||||
* Mirrors low-latency desktop state into the store and reflects navigation
|
||||
* events back to the server. Webview lifetime is owned by ElectronBrowserHost.
|
||||
*/
|
||||
export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: string }): void {
|
||||
const { threadRef, tabId } = input;
|
||||
export function usePreviewBridge(input: {
|
||||
threadRef: ScopedThreadRef;
|
||||
tabId: string;
|
||||
runtimeTabId: string;
|
||||
}): void {
|
||||
const { threadRef, tabId, runtimeTabId } = input;
|
||||
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
|
||||
const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
|
||||
const bridge = previewBridge;
|
||||
@@ -36,9 +40,9 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
|
||||
lastReportedKind.current = null;
|
||||
lastDesktopNavStatus.current = null;
|
||||
const unsubscribe = bridge.onStateChange((changedTabId, state) => {
|
||||
if (changedTabId !== tabId) return;
|
||||
if (changedTabId !== runtimeTabId) return;
|
||||
if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
|
||||
clearBrowserPointer(tabId);
|
||||
clearBrowserPointer(runtimeTabId);
|
||||
}
|
||||
lastDesktopNavStatus.current = state.navStatus;
|
||||
applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
|
||||
@@ -58,7 +62,7 @@ export function usePreviewBridge(input: { threadRef: ScopedThreadRef; tabId: str
|
||||
});
|
||||
});
|
||||
return unsubscribe;
|
||||
}, [bridge, clearBrowserPointer, reportStatus, tabId, threadRef]);
|
||||
}, [bridge, clearBrowserPointer, reportStatus, runtimeTabId, tabId, threadRef]);
|
||||
}
|
||||
|
||||
function shouldClearBrowserPointer(
|
||||
|
||||
@@ -39,7 +39,6 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
|
||||
return Atom.make((get) => {
|
||||
let disposed = false;
|
||||
let sessionsVersion = 0;
|
||||
let eventsVersion = 0;
|
||||
|
||||
const reconcileSessions = (result: Atom.Type<typeof sessionsAtom>) => {
|
||||
@@ -60,10 +59,8 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
get.addFinalizer(() => {
|
||||
disposed = true;
|
||||
});
|
||||
const initialSessions = get.once(sessionsAtom);
|
||||
const initialEvent = get.once(eventsAtom);
|
||||
get.subscribe(sessionsAtom, (result) => {
|
||||
sessionsVersion += 1;
|
||||
reconcileSessions(result);
|
||||
});
|
||||
get.subscribe(eventsAtom, (result) => {
|
||||
@@ -72,7 +69,10 @@ const previewSessionSyncAtom = Atom.family((threadKey: string) => {
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
if (disposed) return;
|
||||
if (sessionsVersion === 0) reconcileSessions(initialSessions);
|
||||
// The cached list can predate an automation-created tab. Keep the local
|
||||
// snapshot visible until an authoritative refresh arrives instead of
|
||||
// reconciling against a stale empty result when the panel first mounts.
|
||||
get.refresh(sessionsAtom);
|
||||
if (eventsVersion === 0) applyLatestEvent(initialEvent);
|
||||
});
|
||||
}).pipe(Atom.setIdleTTL(1_000), Atom.withLabel(`preview:session-sync:${threadKey}`));
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
import { useClientSettings, useUpdateClientSettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
useClientSettings,
|
||||
useSidebarV2Enabled,
|
||||
useUpdateClientSettings,
|
||||
} from "../../hooks/useSettings";
|
||||
import { Input } from "../ui/input";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
@@ -51,7 +55,7 @@ function AutoSettleDaysInput({
|
||||
}
|
||||
|
||||
export function BetaSettingsPanel() {
|
||||
const sidebarV2Enabled = useClientSettings((settings) => settings.sidebarV2Enabled);
|
||||
const sidebarV2Enabled = useSidebarV2Enabled();
|
||||
const sidebarAutoSettleAfterDays = useClientSettings(
|
||||
(settings) => settings.sidebarAutoSettleAfterDays,
|
||||
);
|
||||
@@ -66,7 +70,14 @@ export function BetaSettingsPanel() {
|
||||
control={
|
||||
<Switch
|
||||
checked={sidebarV2Enabled}
|
||||
onCheckedChange={(checked) => updateSettings({ sidebarV2Enabled: Boolean(checked) })}
|
||||
// Touching the switch pins the choice, so a nightly build that
|
||||
// defaults v2 on does not flip it back after the user opts out.
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sidebarV2Enabled: Boolean(checked),
|
||||
sidebarV2ConfiguredByUser: true,
|
||||
})
|
||||
}
|
||||
aria-label="Enable the sidebar v2 beta"
|
||||
/>
|
||||
}
|
||||
|
||||
@@ -394,7 +394,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -447,10 +447,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.confirmThreadDelete !== DEFAULT_UNIFIED_SETTINGS.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitWritingModelDirty ? ["Git writing model"] : []),
|
||||
...(isTextGenerationModelDirty ? ["Text generation model"] : []),
|
||||
],
|
||||
[
|
||||
isGitWritingModelDirty,
|
||||
isTextGenerationModelDirty,
|
||||
settings.autoOpenPlanSidebar,
|
||||
settings.confirmThreadArchive,
|
||||
settings.confirmThreadDelete,
|
||||
@@ -535,21 +535,21 @@ export function GeneralSettingsPanel() {
|
||||
const textGenInstanceId = textGenerationModelSelection.instanceId;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const gitModelInstanceEntries = sortProviderInstanceEntries(
|
||||
const textGenerationModelInstanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const textGenInstanceEntry = gitModelInstanceEntries.find(
|
||||
const textGenInstanceEntry = textGenerationModelInstanceEntries.find(
|
||||
(entry) => entry.instanceId === textGenInstanceId,
|
||||
);
|
||||
const textGenProvider: ProviderDriverKind =
|
||||
textGenInstanceEntry?.driverKind ?? DEFAULT_DRIVER_KIND;
|
||||
const gitModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
const textGenerationModelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
textGenInstanceId,
|
||||
textGenModel,
|
||||
);
|
||||
const isGitWritingModelDirty = !Equal.equals(
|
||||
const isTextGenerationModelDirty = !Equal.equals(
|
||||
settings.textGenerationModelSelection ?? null,
|
||||
DEFAULT_UNIFIED_SETTINGS.textGenerationModelSelection ?? null,
|
||||
);
|
||||
@@ -1002,9 +1002,9 @@ export function GeneralSettingsPanel() {
|
||||
|
||||
<SettingsRow
|
||||
title="Text generation model"
|
||||
description="Configure the model used for generated commit messages, PR titles, and similar Git text."
|
||||
description="Default model for generated text like thread titles and source control content. Source control settings can override it with a dedicated source control writer model."
|
||||
resetAction={
|
||||
isGitWritingModelDirty ? (
|
||||
isTextGenerationModelDirty ? (
|
||||
<SettingResetButton
|
||||
label="text generation model"
|
||||
onClick={() =>
|
||||
@@ -1022,8 +1022,8 @@ export function GeneralSettingsPanel() {
|
||||
activeInstanceId={textGenInstanceId}
|
||||
model={textGenModel}
|
||||
lockedProvider={null}
|
||||
instanceEntries={gitModelInstanceEntries}
|
||||
modelOptionsByInstance={gitModelOptionsByInstance}
|
||||
instanceEntries={textGenerationModelInstanceEntries}
|
||||
modelOptionsByInstance={textGenerationModelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
|
||||
@@ -75,7 +75,7 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
return (
|
||||
<>
|
||||
<SidebarContent className="overflow-x-hidden">
|
||||
<SidebarGroup className="px-2 py-3">
|
||||
<SidebarGroup className="p-2">
|
||||
<SidebarMenu>
|
||||
{SETTINGS_NAV_ITEMS.map((item) => {
|
||||
const Icon = item.icon;
|
||||
@@ -83,22 +83,10 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
return (
|
||||
<SidebarMenuItem key={item.to}>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={
|
||||
isActive
|
||||
? "h-8 items-center gap-2 rounded-md bg-sidebar-row-active px-2 py-1.5 text-left text-sm font-medium text-sidebar-foreground"
|
||||
: "h-8 items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
}
|
||||
onClick={() => handleSectionClick(item.to)}
|
||||
>
|
||||
<Icon
|
||||
className={
|
||||
isActive
|
||||
? "size-4 shrink-0 text-sidebar-foreground"
|
||||
: "size-4 shrink-0 text-sidebar-muted-foreground/60"
|
||||
}
|
||||
/>
|
||||
<Icon />
|
||||
<span className="truncate">{item.label}</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
@@ -109,15 +97,11 @@ export function SettingsSidebarNav({ pathname }: { pathname: string }) {
|
||||
</SidebarContent>
|
||||
<SidebarFooter className="p-2">
|
||||
<T3ConnectSidebarSignIn />
|
||||
<div className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-1">
|
||||
<SidebarMenu className="min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<SidebarMenu className="min-w-0 flex-1">
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={handleBackClick}
|
||||
>
|
||||
<ArrowLeftIcon className="size-4" />
|
||||
<SidebarMenuButton onClick={handleBackClick}>
|
||||
<ArrowLeftIcon />
|
||||
<span>Back</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
type Icon,
|
||||
} from "../Icons";
|
||||
import { RedactedSensitiveText } from "./RedactedSensitiveText";
|
||||
import { SourceControlWritingSettingsSection } from "./SourceControlWritingSettings";
|
||||
import { SettingResetButton, SettingsPageContainer, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const EMPTY_DISCOVERY_RESULT: SourceControlDiscoveryResult = {
|
||||
@@ -195,7 +196,7 @@ function itemSummary({
|
||||
<span>
|
||||
{item.label} is not authenticated on this server. Sign in or configure credentials using
|
||||
the <code className="rounded bg-muted px-1 py-px text-[11px]">{item.executable}</code>{" "}
|
||||
tool on the server host to enable pull request features.
|
||||
tool on the server host to enable change request features.
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -513,6 +514,8 @@ export function SourceControlSettingsPanel() {
|
||||
onScan={handleScan}
|
||||
/>
|
||||
)}
|
||||
|
||||
{environmentId !== null ? <SourceControlWritingSettingsSection /> : null}
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
import { useRef } from "react";
|
||||
import type { SourceControlWritingStyleMode } from "@t3tools/contracts";
|
||||
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { resolveSourceControlWriterModelSelection } from "@t3tools/shared/serverSettings";
|
||||
|
||||
import { usePrimarySettings, useUpdatePrimarySettings } from "../../hooks/useSettings";
|
||||
import {
|
||||
applyProviderInstanceSettings,
|
||||
deriveProviderInstanceEntries,
|
||||
sortProviderInstanceEntries,
|
||||
} from "../../providerInstances";
|
||||
import {
|
||||
getCustomModelOptionsByInstance,
|
||||
resolveAppModelSelectionState,
|
||||
} from "../../modelSelection";
|
||||
import { primaryServerProvidersAtom } from "../../state/server";
|
||||
import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import { Switch } from "../ui/switch";
|
||||
import { Textarea } from "../ui/textarea";
|
||||
import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout";
|
||||
|
||||
const MODE_OPTIONS: Record<SourceControlWritingStyleMode, { label: string; description: string }> =
|
||||
{
|
||||
repo_conventions: {
|
||||
label: "Repository conventions",
|
||||
description: "In each project, matches recent change descriptions and change request titles.",
|
||||
},
|
||||
conventional_commits: {
|
||||
label: "Conventional Commits",
|
||||
description:
|
||||
"Uses Conventional Commit prefixes for change descriptions; change request titles and descriptions stay concise.",
|
||||
},
|
||||
custom: {
|
||||
label: "Custom instructions",
|
||||
description:
|
||||
"Applies your instructions to change descriptions and change request titles and descriptions in every project.",
|
||||
},
|
||||
};
|
||||
|
||||
export function SourceControlWritingSettingsSection() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const serverProviders = useAtomValue(primaryServerProvidersAtom);
|
||||
const customInstructionsRef = useRef<HTMLTextAreaElement>(null);
|
||||
const style = settings.sourceControlWritingStyle;
|
||||
const defaults = DEFAULT_UNIFIED_SETTINGS.sourceControlWritingStyle;
|
||||
const isSourceControlWritingStyleDirty =
|
||||
style.mode !== defaults.mode || style.customInstructions !== defaults.customInstructions;
|
||||
|
||||
const defaultModelSelection = resolveAppModelSelectionState(settings, serverProviders);
|
||||
const usesDedicatedModel = settings.sourceControlWriterModelSelection !== null;
|
||||
const resolvedSourceControlWriterSelection = resolveSourceControlWriterModelSelection(
|
||||
settings,
|
||||
serverProviders,
|
||||
);
|
||||
const activeSelection =
|
||||
resolvedSourceControlWriterSelection === settings.textGenerationModelSelection
|
||||
? defaultModelSelection
|
||||
: resolvedSourceControlWriterSelection;
|
||||
const instanceEntries = sortProviderInstanceEntries(
|
||||
applyProviderInstanceSettings(deriveProviderInstanceEntries(serverProviders), settings),
|
||||
);
|
||||
const modelOptionsByInstance = getCustomModelOptionsByInstance(
|
||||
settings,
|
||||
serverProviders,
|
||||
activeSelection.instanceId,
|
||||
activeSelection.model,
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsSection title="Text generation">
|
||||
<SettingsRow
|
||||
title="Source control writing style"
|
||||
description={MODE_OPTIONS[style.mode].description}
|
||||
resetAction={
|
||||
isSourceControlWritingStyleDirty ? (
|
||||
<SettingResetButton
|
||||
label="source control writing style"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: defaults.mode,
|
||||
customInstructions: defaults.customInstructions,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={style.mode}
|
||||
onValueChange={(value) => {
|
||||
const customInstructions = customInstructionsRef.current?.value.trim();
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
mode: value as SourceControlWritingStyleMode,
|
||||
...(customInstructions !== undefined ? { customInstructions } : {}),
|
||||
},
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-56" aria-label="Source control writing style">
|
||||
<SelectValue>{MODE_OPTIONS[style.mode].label}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{(Object.keys(MODE_OPTIONS) as SourceControlWritingStyleMode[]).map((mode) => (
|
||||
<SelectItem key={mode} hideIndicator value={mode}>
|
||||
{MODE_OPTIONS[mode].label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
>
|
||||
{style.mode === "custom" ? (
|
||||
<div className="mt-3 max-w-2xl pb-3.5">
|
||||
<Textarea
|
||||
key={style.customInstructions}
|
||||
ref={customInstructionsRef}
|
||||
defaultValue={style.customInstructions}
|
||||
onBlur={(event) => {
|
||||
const customInstructions = event.target.value.trim();
|
||||
if (customInstructions !== style.customInstructions) {
|
||||
updateSettings({ sourceControlWritingStyle: { customInstructions } });
|
||||
}
|
||||
}}
|
||||
rows={4}
|
||||
placeholder="Keep titles concise. Use short bullet points in descriptions."
|
||||
aria-label="Custom source control writing instructions"
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
title="Follow change request templates"
|
||||
description="Structures change request descriptions using the current repository's template when one is available."
|
||||
resetAction={
|
||||
style.followChangeRequestTemplates !== defaults.followChangeRequestTemplates ? (
|
||||
<SettingResetButton
|
||||
label="change request templates"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: defaults.followChangeRequestTemplates,
|
||||
},
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={style.followChangeRequestTemplates}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWritingStyle: {
|
||||
followChangeRequestTemplates: Boolean(checked),
|
||||
},
|
||||
})
|
||||
}
|
||||
aria-label="Follow change request templates"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Source control writer model"
|
||||
description="Optional model override for change descriptions, change request titles and descriptions, and branch or bookmark names. Off uses the global text generation model."
|
||||
control={
|
||||
<div className="flex flex-wrap items-center justify-end gap-2">
|
||||
{usesDedicatedModel ? (
|
||||
<ProviderModelPicker
|
||||
activeInstanceId={activeSelection.instanceId}
|
||||
model={activeSelection.model}
|
||||
lockedProvider={null}
|
||||
instanceEntries={instanceEntries}
|
||||
modelOptionsByInstance={modelOptionsByInstance}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
triggerAriaLabel="Source control writer model"
|
||||
onInstanceModelChange={(instanceId, model) => {
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: createModelSelection(instanceId, model),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<Switch
|
||||
checked={usesDedicatedModel}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({
|
||||
sourceControlWriterModelSelection: checked
|
||||
? createModelSelection(
|
||||
defaultModelSelection.instanceId,
|
||||
defaultModelSelection.model,
|
||||
defaultModelSelection.options,
|
||||
)
|
||||
: null,
|
||||
})
|
||||
}
|
||||
aria-label="Use a separate source control writer model"
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
@@ -113,12 +113,8 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
|
||||
<SidebarUpdatePill />
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="sm"
|
||||
className="h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground/80 hover:bg-sidebar-row-hover hover:text-sidebar-foreground"
|
||||
onClick={handleSettingsClick}
|
||||
>
|
||||
<SettingsIcon className="size-4.5 shrink-0" />
|
||||
<SidebarMenuButton onClick={handleSettingsClick}>
|
||||
<SettingsIcon />
|
||||
<span>Settings</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
|
||||
@@ -65,7 +65,7 @@ function CommandDialogPopup({
|
||||
<CommandDialogPrimitive.Popup
|
||||
className={cn(
|
||||
DIALOG_POPUP_CLASS,
|
||||
"pointer-events-auto max-h-105 max-w-xl text-foreground **:data-[slot=scroll-area-viewport]:data-has-overflow-y:pe-1",
|
||||
"pointer-events-auto max-h-105 max-w-xl text-foreground",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-dialog-popup"
|
||||
@@ -103,16 +103,16 @@ function CommandInput({
|
||||
wrapperClassName?: string | undefined;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("px-2.5 py-1.5", wrapperClassName)}>
|
||||
<div className={cn("px-1.25 py-1.5", wrapperClassName)}>
|
||||
<AutocompleteInput
|
||||
autoFocus
|
||||
className={cn(
|
||||
"border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-muted-foreground/80",
|
||||
"border-transparent! bg-transparent! shadow-none before:hidden has-focus-visible:ring-0 placeholder:text-muted-foreground/80 *:data-[slot=autocomplete-input]:ps-9! sm:*:data-[slot=autocomplete-input]:ps-8.5!",
|
||||
className,
|
||||
)}
|
||||
placeholder={placeholder}
|
||||
size="lg"
|
||||
startAddon={<SearchIcon />}
|
||||
startAddon={<SearchIcon className="translate-x-0.5 text-muted-foreground" />}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
@@ -198,7 +198,7 @@ function CommandShortcut({ className, ...props }: React.ComponentProps<"kbd">) {
|
||||
return (
|
||||
<kbd
|
||||
className={cn(
|
||||
"ms-auto font-medium font-sans text-muted-foreground text-xs tracking-widest",
|
||||
"ms-auto font-medium font-sans text-muted-foreground/70 text-xs tracking-widest",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-shortcut"
|
||||
@@ -211,7 +211,7 @@ function CommandFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"relative flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] bg-foreground/[0.025] px-5 py-3 font-medium text-sm text-muted-foreground [&_[data-slot=kbd-group]]:font-sans [&_[data-slot=kbd]]:bg-foreground/[0.08] [&_[data-slot=kbd]]:text-foreground [&_[data-slot=kbd]]:ring-0",
|
||||
"relative flex items-center justify-between gap-2 rounded-b-[calc(var(--radius-2xl)-1px)] bg-foreground/[0.025] px-4 py-2.5 font-medium text-sm text-muted-foreground [&_[data-slot=kbd-group]]:font-sans [&_[data-slot=kbd]]:bg-foreground/[0.08] [&_[data-slot=kbd]]:text-foreground [&_[data-slot=kbd]]:ring-0",
|
||||
className,
|
||||
)}
|
||||
data-slot="command-footer"
|
||||
|
||||
@@ -56,7 +56,7 @@ function ScrollBar({
|
||||
return (
|
||||
<ScrollAreaPrimitive.Scrollbar
|
||||
className={cn(
|
||||
"m-1 flex opacity-0 transition-opacity delay-300 data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:w-1.5 data-[orientation=horizontal]:flex-col data-hovering:opacity-100 data-scrolling:opacity-100 data-hovering:delay-0 data-scrolling:delay-0 data-hovering:duration-100 data-scrolling:duration-100",
|
||||
"flex opacity-0 transition-opacity delay-300 data-[orientation=horizontal]:mx-1 data-[orientation=horizontal]:mb-px data-[orientation=horizontal]:h-1.5 data-[orientation=vertical]:my-1 data-[orientation=vertical]:mr-px data-[orientation=vertical]:w-1.5 data-[orientation=horizontal]:flex-col data-hovering:opacity-100 data-scrolling:opacity-100 data-hovering:delay-0 data-scrolling:delay-0 data-hovering:duration-100 data-scrolling:duration-100",
|
||||
className,
|
||||
)}
|
||||
data-slot="scroll-area-scrollbar"
|
||||
@@ -64,7 +64,7 @@ function ScrollBar({
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.Thumb
|
||||
className="relative flex-1 rounded-full bg-foreground/20"
|
||||
className="relative flex-1 rounded-full bg-[var(--app-scrollbar-thumb)] transition-colors hover:bg-[var(--app-scrollbar-thumb-hover)]"
|
||||
data-slot="scroll-area-thumb"
|
||||
/>
|
||||
</ScrollAreaPrimitive.Scrollbar>
|
||||
|
||||
@@ -77,8 +77,10 @@ function SelectTrigger({
|
||||
size = "default",
|
||||
variant = "default",
|
||||
children,
|
||||
icon,
|
||||
...props
|
||||
}: SelectPrimitive.Trigger.Props & VariantProps<typeof selectTriggerVariants>) {
|
||||
}: SelectPrimitive.Trigger.Props &
|
||||
VariantProps<typeof selectTriggerVariants> & { icon?: React.ReactNode }) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
className={cn(selectTriggerVariants({ size, variant }), className)}
|
||||
@@ -87,7 +89,7 @@ function SelectTrigger({
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon data-slot="select-icon">
|
||||
<ChevronDownIcon className="-me-1 size-3 opacity-50" />
|
||||
{icon ?? <ChevronDownIcon className="-me-1 size-3 opacity-50" />}
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
|
||||
@@ -50,13 +50,35 @@ describe("sidebar interactive cursors", () => {
|
||||
expect(html).toContain("size-[var(--workspace-titlebar-control-size)]!");
|
||||
});
|
||||
|
||||
it("uses a pointer cursor for menu buttons by default", () => {
|
||||
it("uses shared geometry and icon constraints for menu buttons by default", () => {
|
||||
const html = renderSidebarButton();
|
||||
|
||||
expect(html).toContain('data-slot="sidebar-menu-button"');
|
||||
expect(html).toContain("h-8");
|
||||
expect(html).toContain("rounded-md");
|
||||
expect(html).toContain("px-2");
|
||||
expect(html).toContain("py-1.5");
|
||||
expect(html).toContain("]:size-4");
|
||||
expect(html).toContain("]:shrink-0");
|
||||
expect(html).toContain("cursor-pointer");
|
||||
});
|
||||
|
||||
it("applies the shared default treatment to icon-only menu buttons", () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<SidebarProvider>
|
||||
<SidebarMenuButton size="icon">
|
||||
<span>+</span>
|
||||
</SidebarMenuButton>
|
||||
</SidebarProvider>,
|
||||
);
|
||||
|
||||
expect(html).toContain("size-8");
|
||||
expect(html).toContain("justify-center");
|
||||
expect(html).toContain("p-0");
|
||||
expect(html).toContain("font-medium");
|
||||
expect(html).toContain("text-sidebar-muted-foreground/80");
|
||||
});
|
||||
|
||||
it("lets project drag handles override the default pointer cursor", () => {
|
||||
const html = renderSidebarButton("cursor-grab");
|
||||
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user