diff --git a/.gitattributes b/.gitattributes index 00b0e5eccb989..ffcc4445fe8a1 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,6 @@ # Batch files need CRLF for cmd.exe to parse them reliably. *.cmd text eol=crlf *.bat text eol=crlf +# GitHub's GraphQL schema and the operations graphqlgen writes from it. +packages/source-control-github/schema/** linguist-generated +**/*.graphql.ts linguist-generated diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c28a854c14373..b99c9ad7d050d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -57,6 +57,9 @@ jobs: - name: Check case-only module collisions run: vp run case:check + - name: Check generated GitHub GraphQL operations + run: vp run --filter @t3tools/source-control-github generate --check + - name: Check run: vp check diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 8e736a7d54105..6e9e584d7e431 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -42,5 +42,5 @@ "tailwindcss": "^4.0.0", "vite-plus": "catalog:" }, - "productName": "T3 Code (Alpha)" + "productName": "T3 Code (Beta)" } diff --git a/apps/desktop/scripts/electron-launcher.mjs b/apps/desktop/scripts/electron-launcher.mjs index b355650f841fe..ec6324576b6bb 100644 --- a/apps/desktop/scripts/electron-launcher.mjs +++ b/apps/desktop/scripts/electron-launcher.mjs @@ -15,7 +15,7 @@ const repoRoot = NodePath.resolve(desktopDir, "..", ".."); const devBundleIdSuffix = NodePath.basename(repoRoot) .toLowerCase() .replaceAll(/[^a-z0-9]+/g, ""); -const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)"; +const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Beta)"; const APP_BUNDLE_ID = isDevelopment ? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}` : "com.t3tools.t3code"; diff --git a/apps/desktop/src/app/DesktopAppIdentity.test.ts b/apps/desktop/src/app/DesktopAppIdentity.test.ts index cc0277d3ed104..10ab907965f2e 100644 --- a/apps/desktop/src/app/DesktopAppIdentity.test.ts +++ b/apps/desktop/src/app/DesktopAppIdentity.test.ts @@ -217,8 +217,8 @@ describe("DesktopAppIdentity", () => { const identity = yield* DesktopAppIdentity.DesktopAppIdentity; yield* identity.configure; - assert.deepEqual(calls.setName, ["T3 Code Alpha"]); - assert.equal(calls.setAboutPanelOptions[0]?.applicationName, "T3 Code (Alpha)"); + assert.deepEqual(calls.setName, ["T3 Code Beta"]); + assert.equal(calls.setAboutPanelOptions[0]?.applicationName, "T3 Code (Beta)"); assert.equal(calls.setAboutPanelOptions[0]?.applicationVersion, "1.2.3"); assert.equal(calls.setAboutPanelOptions[0]?.version, "0123456789ab"); // Packaged: the bundle's own icon stands, so a custom one the user @@ -238,7 +238,7 @@ describe("DesktopAppIdentity", () => { }); it.effect.each([ - { stage: "Alpha", environment: {} }, + { stage: "Beta", environment: {} }, { stage: "Nightly", environment: { appVersion: "0.0.43-nightly.20260929.2428" }, diff --git a/apps/desktop/src/app/DesktopEnvironment.ts b/apps/desktop/src/app/DesktopEnvironment.ts index 6a8bc8e0ea495..f697e0456db97 100644 --- a/apps/desktop/src/app/DesktopEnvironment.ts +++ b/apps/desktop/src/app/DesktopEnvironment.ts @@ -103,7 +103,7 @@ function resolveDesktopAppStageLabel(input: { return "Dev"; } - return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha"; + return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Beta"; } export function resolveDesktopAppBranding(input: { diff --git a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts index 29fa706698e01..dd15f879fd8ee 100644 --- a/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts +++ b/apps/desktop/src/app/DesktopPreReadyPlatform.test.ts @@ -175,7 +175,7 @@ describe("DesktopPreReadyPlatform", () => { const identity = yield* Effect.promise(() => portalIdentity); assert.equal(identity.desktopName, "com.t3tools.T3Code.desktop"); assert.include(identity.desktopEntry ?? "", 'Exec="/Applications/current.AppImage" %U'); - assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Alpha)"); + assert.include(identity.desktopEntry ?? "", "Name=T3 Code (Beta)"); assert.include(identity.desktopEntry ?? "", "MimeType=x-scheme-handler/t3code;"); assert.include( identity.desktopEntry ?? "", diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.11.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.11.tgz deleted file mode 100644 index c095f5d3324c3..0000000000000 Binary files a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.11.tgz and /dev/null differ diff --git a/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.12.tgz b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.12.tgz new file mode 100644 index 0000000000000..5e7e41b02a3fd Binary files /dev/null and b/apps/mobile/deps/react-native-enriched-markdown-1.2.0-t3.12.tgz differ diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift index 08b7e71239648..3289fe90363b3 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeControlsModule.swift @@ -1,3 +1,4 @@ +import AVFoundation import ExpoModulesCore import Security import UIKit @@ -97,6 +98,18 @@ public final class T3NativeControlsModule: Module { dismissVideoPresentation(identifier: identifier) } + // expo-video activates the session for inline playback but never deactivates + // it. Any other category or mode means another feature (recording) owns it. + @JS + @MainActor + func releaseVideoAudioSession() async { + // The fullscreen presentation releases the session in its own teardown. + guard videoPresentation == nil else { return } + let session = AVAudioSession.sharedInstance() + guard session.category == .playback, session.mode == .moviePlayback else { return } + try? session.setActive(false, options: [.notifyOthersOnDeactivation]) + } + @JS @MainActor func dismissFile(identifier: String) async { diff --git a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift index 74d2f1c7551d9..388e12cb668c6 100644 --- a/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift +++ b/apps/mobile/modules/t3-native-controls/ios/T3NativeVideoPresentation.swift @@ -152,15 +152,19 @@ final class T3NativeVideoPresentation: NSObject, AVPlayerViewControllerDelegate, if let backgroundObserver { NotificationCenter.default.removeObserver(backgroundObserver) } backgroundObserver = nil let audioSession = AVAudioSession.sharedInstance() + // Still what present() set, allowing the .mixWithOthers flip expo-video + // makes when the inline players pause under this preview. A recorder that + // claimed the session since owns it. if let previousAudioSession, audioSession.category == .playback, - audioSession.mode == .moviePlayback, audioSession.categoryOptions.isEmpty { - // AVPlayer owns activation. Deactivating the shared session here could - // stop another player or recorder that was active before this preview. + audioSession.mode == .moviePlayback, + audioSession.categoryOptions.isSubset(of: [.mixWithOthers]) { try? audioSession.setCategory( previousAudioSession.category, mode: previousAudioSession.mode, options: previousAudioSession.options ) + // Deactivating with notification lets interrupted apps resume. + try? audioSession.setActive(false, options: [.notifyOthersOnDeactivation]) } completion(playbackError) } diff --git a/apps/mobile/package.json b/apps/mobile/package.json index 16eccc7114424..34be386eec481 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -120,7 +120,7 @@ "react": "19.3.0", "react-dom": "19.3.0", "react-native": "0.88.0-rc.3", - "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.11.tgz", + "react-native-enriched-markdown": "file:deps/react-native-enriched-markdown-1.2.0-t3.12.tgz", "react-native-gesture-handler": "~3.2.1", "react-native-image-viewing": "^0.2.2", "react-native-keyboard-controller": "1.22.6", diff --git a/apps/mobile/src/components/AudioFilePreview.tsx b/apps/mobile/src/components/AudioFilePreview.tsx index cea4acfb46140..1e0c71ef0114b 100644 --- a/apps/mobile/src/components/AudioFilePreview.tsx +++ b/apps/mobile/src/components/AudioFilePreview.tsx @@ -1,7 +1,8 @@ import { useAudioPlayer, useAudioPlayerStatus } from "expo-audio"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { Pressable, View } from "react-native"; import { AppText as Text } from "./AppText"; +import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession"; function timestamp(seconds: number) { const value = Number.isFinite(seconds) ? Math.max(0, Math.floor(seconds)) : 0; @@ -12,6 +13,12 @@ export function AudioFilePreview(props: { uri: string; onRetry: () => void }) { const player = useAudioPlayer({ uri: props.uri }, { updateInterval: 500 }); const status = useAudioPlayerStatus(player); const [seekError, setSeekError] = useState(false); + // Video teardown deactivates the shared iOS session, which would stop this player. + useMediaAudioSessionHold(status.playing); + const fullscreenVideoOpen = useFullscreenVideoOpen(); + useEffect(() => { + if (fullscreenVideoOpen) player.pause(); + }, [fullscreenVideoOpen, player]); const seek = (seconds: number, play = false) => { setSeekError(false); void player diff --git a/apps/mobile/src/components/BrandMark.tsx b/apps/mobile/src/components/BrandMark.tsx index 1643f3f6fdeb2..da496d1d79600 100644 --- a/apps/mobile/src/components/BrandMark.tsx +++ b/apps/mobile/src/components/BrandMark.tsx @@ -7,7 +7,7 @@ import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets"; const appVariant = Constants.expoConfig?.extra?.appVariant; const DEFAULT_STAGE_LABEL = - appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha"; + appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Beta"; export function BrandMark(props: { readonly compact?: boolean; readonly stageLabel?: string }) { const compact = props.compact ?? false; diff --git a/apps/mobile/src/components/MediaVideoPlayer.tsx b/apps/mobile/src/components/MediaVideoPlayer.tsx index c35195cd3a5f3..c36bcd024a616 100644 --- a/apps/mobile/src/components/MediaVideoPlayer.tsx +++ b/apps/mobile/src/components/MediaVideoPlayer.tsx @@ -10,6 +10,7 @@ import { SymbolView } from "./AppSymbol"; import { VideoThumbnailImage } from "./VideoThumbnailImage"; import { useMediaActions } from "../state/mediaActions"; import { type MediaActionsSource } from "../lib/mediaActionsSource"; +import { useFullscreenVideoOpen, useMediaAudioSessionHold } from "../lib/videoAudioSession"; import { MediaActionsMenu } from "./MediaActionsMenu"; /** Loads only after Play or opening the viewer. Source replacement never starts playback itself. */ @@ -20,6 +21,8 @@ function LoadedMediaVideo(props: { readonly paused: boolean; }) { const focused = useIsFocused(); + const fullscreenVideoOpen = useFullscreenVideoOpen(); + const paused = props.paused || fullscreenVideoOpen; const active = useRef(focused && AppState.currentState === "active"); const fullscreen = useRef(false); const [attempt, setAttempt] = useState(0); @@ -30,6 +33,8 @@ function LoadedMediaVideo(props: { player.bufferOptions = { preferredForwardBufferDuration: 5 }; }); const { status } = useEvent(player, "statusChange", { status: player.status }); + const { isPlaying } = useEvent(player, "playingChange", { isPlaying: player.playing }); + useMediaAudioSessionHold(isPlaying); const loadSource = useEffectEvent(async (signal: AbortSignal) => { const uri = props.resolvePlaybackUri ? await props.resolvePlaybackUri() : props.uri; if (signal.aborted) return; @@ -40,16 +45,16 @@ function LoadedMediaVideo(props: { }); useEffect(() => { - active.current = focused && !props.paused && AppState.currentState === "active"; - if (!focused || props.paused || (!active.current && !fullscreen.current)) player.pause(); + active.current = focused && !paused && AppState.currentState === "active"; + if (!focused || paused || (!active.current && !fullscreen.current)) player.pause(); // Native background handling distinguishes Android's fullscreen activity // from leaving the app; React Native reports both as background. const subscription = AppState.addEventListener("change", (state) => { - active.current = focused && !props.paused && state === "active"; + active.current = focused && !paused && state === "active"; if (state === "inactive" || (state === "background" && !fullscreen.current)) player.pause(); }); return () => subscription.remove(); - }, [focused, player, props.paused]); + }, [focused, player, paused]); useEffect(() => { const controller = new AbortController(); diff --git a/apps/mobile/src/components/VideoPreviewModal.ios.tsx b/apps/mobile/src/components/VideoPreviewModal.ios.tsx index ae69e0ead89a9..4cae4d30db440 100644 --- a/apps/mobile/src/components/VideoPreviewModal.ios.tsx +++ b/apps/mobile/src/components/VideoPreviewModal.ios.tsx @@ -4,6 +4,7 @@ import { useEffect, useEffectEvent, useId, useState } from "react"; import { Alert, Keyboard } from "react-native"; import { loadLocalAttachmentPreview } from "../lib/localAttachmentPreview"; +import { fullscreenVideoClosed, fullscreenVideoOpened } from "../lib/videoAudioSession"; import { mediaVideoPreviewUri, type VideoPreviewSource } from "../lib/videoPreviewSource"; import { useAssetUrlState, useRefreshAssetUrl } from "../state/assets"; import { usePreparedConnection } from "../state/session"; @@ -51,6 +52,10 @@ function NativeVideoPreview(props: { : null; useEffect(() => Keyboard.dismiss(), []); + useEffect(() => { + fullscreenVideoOpened(); + return () => fullscreenVideoClosed(); + }, []); useEffect(() => { if (playbackUrl === null && resolvedUrl !== null) setPlaybackUrl(resolvedUrl); }, [playbackUrl, resolvedUrl]); diff --git a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx index e3e8d3d0eb120..d6d55ef563b8e 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestsScreen.tsx @@ -43,7 +43,7 @@ import { useAndroidWorkspaceSelection } from "../workspace/useAndroidWorkspaceSe function PullRequestScrollView(props: ScrollViewProps) { const insets = useSafeAreaInsets(); return ( - + (null).pipe( + Atom.withLabel("mobile-thread-turn-subagents:empty"), +); + +export function useThreadTurnSubagents(target: AgentsTarget | null): ThreadTurnSubagents | null { + return useAtomValue( + target === null + ? EMPTY_TURN_SUBAGENTS_ATOM + : environmentThreadDetails.turnSubagentsAtom(target), + ); } export function ThreadAgentsSheet({ route }: StaticScreenProps) { diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index fe8328df83cfd..b0df9df951a23 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -30,6 +30,7 @@ import type { ProviderInteractionMode, RuntimeMode, RuntimeRequestId, + ScopedThreadRef, ServerConfig as T3ServerConfig, ThreadId, UsageLimitsReport, @@ -162,6 +163,11 @@ export interface ThreadDetailScreenProps { readonly setupWorkingStartedAt?: string | null; readonly canOperateThread: boolean; readonly selectedThread: EnvironmentThreadShell; + /** + * Read thread details through this, not `selectedThread.id`: it stays null until + * a queued creation reaches the server; see `useThreadSelection`. + */ + readonly selectedThreadDetailRef: ScopedThreadRef | null; readonly contentPresentation: ThreadContentPresentation; readonly screenTone: StatusTone; readonly connectionError: string | null; @@ -340,10 +346,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread const usesNativeWorkspaceColumns = useNativeWorkspaceColumnsSupported(); const navigation = useNavigation(); const { session: voiceInputSession } = useGlobalVoiceInput(); - const reportedModelSelection = useThreadReportedModelSelection({ - environmentId: props.environmentId, - threadId: props.selectedThread.id, - }); + const reportedModelSelection = useThreadReportedModelSelection(props.selectedThreadDetailRef); const deviceState = useEnvironmentQuery( deviceEnvironment.state({ environmentId: props.environmentId, input: {} }), ); @@ -421,14 +424,8 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread threadId: props.selectedThread.id, }); const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null; - const queuedCount = useThreadQueuedCount({ - environmentId: props.environmentId, - threadId: props.selectedThread.id, - }); - const turnSubagents = useThreadTurnSubagents({ - environmentId: props.environmentId, - threadId: props.selectedThread.id, - }); + const queuedCount = useThreadQueuedCount(props.selectedThreadDetailRef); + const turnSubagents = useThreadTurnSubagents(props.selectedThreadDetailRef); const agentsSegment = resolveSubagentPillSegment(turnSubagents); const composerEditorRef = useRef(null); // A provider-native subagent shows status instead of a composer. diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index e8d81a20a8bc5..441b1bfe3c695 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -1,6 +1,7 @@ import { type StaticScreenProps, useNavigation } from "@react-navigation/native"; import { useAtomValue } from "@effect/atom-react"; import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; import { Image } from "expo-image"; import * as Haptics from "expo-haptics"; import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; @@ -40,6 +41,9 @@ import { threadDragGapOffset } from "./threadDragGap"; const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version); const REMOVE_ACTION_WIDTH = 76; const THUMBNAIL_LIMIT = 3; +const EMPTY_QUEUED_COUNT_ATOM = Atom.make(0).pipe( + Atom.withLabel("mobile-thread-queue-count:empty"), +); type QueueTarget = { readonly environmentId: EnvironmentId; readonly threadId: ThreadId }; type QueueAction = "steer" | "edit" | "up" | "down" | "remove"; @@ -49,8 +53,10 @@ export function useThreadQueueWorkflow(target: QueueTarget) { return useAtomValue(environmentThreadDetails.queueWorkflowAtom(target)); } -export function useThreadQueuedCount(target: QueueTarget) { - return useAtomValue(environmentThreadDetails.queuedCountAtom(target)); +export function useThreadQueuedCount(target: QueueTarget | null) { + return useAtomValue( + target === null ? EMPTY_QUEUED_COUNT_ATOM : environmentThreadDetails.queuedCountAtom(target), + ); } export function ThreadQueueSheet({ route }: StaticScreenProps) { diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 63e4123961e1a..8ca56a3fd6dc5 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -278,6 +278,7 @@ function ThreadRouteContent( const { selectedThread, selectedThreadCreation, + selectedThreadDetailRef, selectedThreadProject, selectedEnvironmentConnection, } = useThreadSelection(); @@ -996,6 +997,7 @@ function ThreadRouteContent( { expect(context.records).toEqual([terminal, review, pr]); }); }); + +describe("threadComposerContext", () => { + it("mints a schema-valid, stable id for agent-spawned thread ids", () => { + const environmentId = EnvironmentId.make("env-1"); + const ref = { + environmentId, + threadId: ThreadId.make(`thread:mcp:${encodeURIComponent("3f2b:delegate")}:review:0`), + }; + const contextId = threadComposerContext(ref, "Review").contextId; + + expect(() => ComposerContextId.make(contextId)).not.toThrow(); + expect(threadComposerContext(ref, "Renamed").contextId).toBe(contextId); + expect( + threadComposerContext({ environmentId, threadId: ThreadId.make("abc-123") }, "t").contextId, + ).toBe("thread_abc-123"); + }); +}); diff --git a/apps/mobile/src/lib/composerContext.ts b/apps/mobile/src/lib/composerContext.ts index 45b033dc9488f..16a790d65e4c8 100644 --- a/apps/mobile/src/lib/composerContext.ts +++ b/apps/mobile/src/lib/composerContext.ts @@ -20,6 +20,7 @@ import { isImageReferencesOnly, replaceComposerContextReferences, sanitizeComposerContextLabel, + toKindScopedComposerContextId, } from "@t3tools/shared/composerContextReferences"; import { collectComposerInlineTokens, @@ -110,7 +111,7 @@ export function threadComposerContext(ref: ScopedThreadRef, title: string): Thre return { version: 1, kind: "thread", - contextId: ComposerContextId.make(`thread_${ref.threadId}`), + contextId: toKindScopedComposerContextId("thread", ref.threadId), label, environmentId: ref.environmentId, threadId: ref.threadId, diff --git a/apps/mobile/src/lib/mobileBranding.ts b/apps/mobile/src/lib/mobileBranding.ts index 9fd6020831a11..c00dd9770275e 100644 --- a/apps/mobile/src/lib/mobileBranding.ts +++ b/apps/mobile/src/lib/mobileBranding.ts @@ -1,7 +1,7 @@ -export type MobileStageLabel = "Alpha" | "Dev" | "Nightly"; +export type MobileStageLabel = "Beta" | "Dev" | "Nightly"; export function resolveMobileStageLabel(appVariant: unknown): MobileStageLabel { if (appVariant === "development") return "Dev"; if (appVariant === "preview") return "Nightly"; - return "Alpha"; + return "Beta"; } diff --git a/apps/mobile/src/lib/videoAudioSession.test.ts b/apps/mobile/src/lib/videoAudioSession.test.ts new file mode 100644 index 0000000000000..3deb938efe5f9 --- /dev/null +++ b/apps/mobile/src/lib/videoAudioSession.test.ts @@ -0,0 +1,54 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +const mocks = vi.hoisted(() => ({ + platform: { OS: "ios" as "ios" | "android" }, + release: vi.fn(async (): Promise => {}), +})); +vi.mock("react-native", () => ({ Platform: mocks.platform })); +vi.mock("expo", () => ({ + requireOptionalNativeModule: () => ({ releaseVideoAudioSession: mocks.release }), +})); + +let session: typeof import("./videoAudioSession"); + +beforeEach(async () => { + vi.resetModules(); + vi.useFakeTimers(); + mocks.platform.OS = "ios"; + mocks.release.mockClear().mockResolvedValue(undefined); + session = await import("./videoAudioSession"); +}); + +afterEach(() => vi.useRealTimers()); + +describe("video audio session", () => { + it("releases once, after the last playing player stops, unless playback restarts first", () => { + session.mediaPlaybackStarted(); + session.mediaPlaybackStarted(); + session.mediaPlaybackStopped(); + vi.advanceTimersByTime(1_000); + expect(mocks.release).not.toHaveBeenCalled(); + + // A player starting inside the deferral window keeps the session. + session.mediaPlaybackStopped(); + session.mediaPlaybackStarted(); + vi.advanceTimersByTime(1_000); + expect(mocks.release).not.toHaveBeenCalled(); + + session.mediaPlaybackStopped(); + vi.advanceTimersByTime(1_000); + expect(mocks.release).toHaveBeenCalledTimes(1); + }); + + it("stays fullscreen until every overlapping presentation closes", () => { + const listener = vi.fn(); + session.subscribeFullscreenVideo(listener); + session.fullscreenVideoOpened(); + session.fullscreenVideoOpened(); + session.fullscreenVideoClosed(); + expect(session.isFullscreenVideoOpen()).toBe(true); + session.fullscreenVideoClosed(); + expect(session.isFullscreenVideoOpen()).toBe(false); + expect(listener).toHaveBeenCalledTimes(4); + }); +}); diff --git a/apps/mobile/src/lib/videoAudioSession.ts b/apps/mobile/src/lib/videoAudioSession.ts new file mode 100644 index 0000000000000..a09299531ec7d --- /dev/null +++ b/apps/mobile/src/lib/videoAudioSession.ts @@ -0,0 +1,74 @@ +import { requireOptionalNativeModule } from "expo"; +import { useEffect, useSyncExternalStore } from "react"; +import { Platform } from "react-native"; + +const nativeControls = requireOptionalNativeModule<{ + releaseVideoAudioSession(): Promise; +}>("T3NativeControls"); + +// Players report not playing during seeks and buffering stalls, and another +// player may start right after one stops. Both keep the session. +const RELEASE_DELAY_MS = 1_000; + +let playingCount = 0; +let releaseTimer: ReturnType | undefined; + +/** Pairs with `mediaPlaybackStopped` for each inline video or audio player holding the session. */ +export function mediaPlaybackStarted(): void { + playingCount += 1; +} + +/** + * expo-video activates the iOS playback session but never deactivates it, so + * interrupted apps (Spotify, Podcasts) are never told they may resume. The + * last player to stop releases it. In-app audio previews count too, since + * deactivating stops them. + */ +export function mediaPlaybackStopped(): void { + playingCount -= 1; + if (playingCount > 0 || Platform.OS !== "ios") return; + clearTimeout(releaseTimer); + releaseTimer = setTimeout(() => { + if (playingCount > 0) return; + void nativeControls?.releaseVideoAudioSession().catch(() => undefined); + }, RELEASE_DELAY_MS); +} + +let fullscreenCount = 0; +const fullscreenListeners = new Set<() => void>(); + +/** Pairs with `fullscreenVideoClosed` while the native fullscreen player is open. */ +export function fullscreenVideoOpened(): void { + fullscreenCount += 1; + for (const listener of fullscreenListeners) listener(); +} + +export function fullscreenVideoClosed(): void { + fullscreenCount -= 1; + for (const listener of fullscreenListeners) listener(); +} + +export function subscribeFullscreenVideo(listener: () => void): () => void { + fullscreenListeners.add(listener); + return () => { + fullscreenListeners.delete(listener); + }; +} + +export function isFullscreenVideoOpen(): boolean { + return fullscreenCount > 0; +} + +/** In-app players pause while the iOS fullscreen player owns playback and the session. */ +export function useFullscreenVideoOpen(): boolean { + return useSyncExternalStore(subscribeFullscreenVideo, isFullscreenVideoOpen); +} + +/** Holds the session for as long as `active`, releasing it with the last holder. */ +export function useMediaAudioSessionHold(active: boolean): void { + useEffect(() => { + if (!active) return; + mediaPlaybackStarted(); + return () => mediaPlaybackStopped(); + }, [active]); +} diff --git a/apps/mobile/src/state/entities.ts b/apps/mobile/src/state/entities.ts index b8e42b0cb99ec..31b19d8574a6d 100644 --- a/apps/mobile/src/state/entities.ts +++ b/apps/mobile/src/state/entities.ts @@ -31,6 +31,9 @@ const EMPTY_THREAD_SHELL_ATOM = Atom.make(null).p const EMPTY_SERVER_CONFIG_ATOM = Atom.make(null).pipe( Atom.withLabel("mobile-server-config:empty"), ); +const EMPTY_THREAD_ATOM = Atom.make(null).pipe( + Atom.withLabel("mobile-thread:empty"), +); const EMPTY_THREAD_TITLES: ReadonlyMap = new Map(); const EMPTY_THREAD_TITLES_ATOM = Atom.make(EMPTY_THREAD_TITLES).pipe( Atom.withLabel("mobile-thread-titles:empty"), @@ -133,6 +136,9 @@ export function useServerConfigs(): ReadonlyMap { const selectReportedModelSelection = (thread: EnvironmentThread | null) => thread === null ? null : deriveReportedModelSelection(thread.projection); -export function useThreadReportedModelSelection(ref: ScopedThreadRef) { - return useAtomValue(environmentThreadDetails.threadAtom(ref), selectReportedModelSelection); +export function useThreadReportedModelSelection(ref: ScopedThreadRef | null) { + return useAtomValue( + ref === null ? EMPTY_THREAD_ATOM : environmentThreadDetails.threadAtom(ref), + selectReportedModelSelection, + ); } diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 623eff1b0a5e6..10ef09b7b77a5 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -184,6 +184,7 @@ export function useThreadComposerState() { const { selectedThread: selectedThreadShell, selectedThreadCreation, + selectedThreadDetailRef, selectedEnvironmentRuntime, } = useThreadSelection(); const selectedThreadProjection = useSelectedThreadProjection(); @@ -311,12 +312,9 @@ export function useThreadComposerState() { // Steering needs a live provider turn the adapter can interrupt; the queue // workflow already derives that from the session's capabilities. const queueWorkflow = useAtomValue( - selectedThreadShell === null + selectedThreadDetailRef === null ? EMPTY_QUEUE_WORKFLOW_ATOM - : environmentThreadDetails.queueWorkflowAtom({ - environmentId: selectedThreadShell.environmentId, - threadId: selectedThreadShell.id, - }), + : environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef), ); const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true; const queuedRunEdit = useQueuedRunEdit(selectedThreadKey); diff --git a/apps/mobile/src/state/use-thread-selection.ts b/apps/mobile/src/state/use-thread-selection.ts index 3624caebb0767..51b88c748e4a2 100644 --- a/apps/mobile/src/state/use-thread-selection.ts +++ b/apps/mobile/src/state/use-thread-selection.ts @@ -158,7 +158,8 @@ function useResolvedThreadSelection(params: ThreadSelectionRouteParams | undefin return message === null ? null : { message, outcome }; }, [creationOutcome, queuedMessagesByThreadKey, selectedThreadKey]); // Until the creation is delivered the server has no thread to subscribe - // to; subscribing anyway would retry "not found" for the whole setup. + // to. Every detail reader must use this ref, not the route id: an earlier + // read gets a definitive not-found, which the thread state keeps as deleted. const selectedThreadDetailRef = selectedThreadShell !== null || pendingCreation === null || diff --git a/apps/server/package.json b/apps/server/package.json index 348eb5c8f739a..41d28277bf988 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -65,7 +65,7 @@ "proper-lockfile": "4.1.2", "stream-chain": "^4.2.5", "stream-json": "3.6.0", - "undici": "7.29.1", + "undici": "catalog:", "yaml": "catalog:", "yauzl": "^3.4.0" }, diff --git a/apps/server/scripts/measure-pr-preview.ts b/apps/server/scripts/measure-pr-preview.ts index 8fca30c91486f..c6b2795989546 100644 --- a/apps/server/scripts/measure-pr-preview.ts +++ b/apps/server/scripts/measure-pr-preview.ts @@ -1,23 +1,21 @@ // Run with: node apps/server/scripts/measure-pr-preview.ts owner/repo 123 456 // Numbers form a session with shared repository-permission caches. Browser and // service caches are excluded. Uses real GitHub reads, without a server or database. -// Each GraphQL read asks for `rateLimit` here, so its cost is read off its own answer. +// Requests are counted at the HTTP client. A GraphQL request's cost is how far it moved GitHub's +// `x-ratelimit-used` for the `graphql` resource, which is approximate when anything else spends +// the same token's quota while this runs. import * as NodeServices from "@effect/platform-node/NodeServices"; import * as Effect from "effect/Effect"; import * as Console from "effect/Console"; import * as Layer from "effect/Layer"; -import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { FetchHttpClient } from "effect/http"; +import { FetchHttpClient, HttpClient } from "effect/http"; import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; -import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; import * as ServerConfig from "../src/config.ts"; import * as ServerSettings from "../src/serverSettings.ts"; -import * as GitHubQuota from "@t3tools/source-control-github/server/GitHubQuota"; -import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as ServerSourceControlHost from "../src/sourceControl/ServerSourceControlHost.ts"; import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts"; import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts"; @@ -31,21 +29,50 @@ if (!repository || numbers.length === 0 || numbers.some((number) => !/^\d+$/.tes type Read = { graphqlRequests: number; restRequests: number; cost: number }; const reads: Read[] = []; -const decodeCost = Schema.decodeUnknownOption( + +/** The `graphql` quota's use so far, and the window it counts in. */ +let graphqlUsed: { used: number; reset: string } | null = null; +const decodeRateLimit = Schema.decodeUnknownSync( Schema.fromJsonString( Schema.Struct({ - data: Schema.Struct({ rateLimit: Schema.Struct({ cost: Schema.Number }) }), + resources: Schema.Struct({ + graphql: Schema.Struct({ used: Schema.Number, reset: Schema.Number }), + }), }), ), ); -/** The query with GitHub's own count of what it cost, for a read rather than a mutation. */ -function withRateLimit(query: string): string { - const end = query.lastIndexOf("}"); - return query.trimStart().startsWith("mutation") || end === -1 - ? query - : `${query.slice(0, end)}\n rateLimit { cost }\n${query.slice(end)}`; + +/** + * What one GraphQL answer spent: how far it moved `used` past the highest value seen, so requests + * answered out of order still add up to the window's total. A new window starts from zero. + */ +function graphqlCost(headers: Readonly>): number { + const used = Number(headers["x-ratelimit-used"]); + const reset = headers["x-ratelimit-reset"] ?? ""; + if (headers["x-ratelimit-resource"] !== "graphql" || !Number.isFinite(used)) return 0; + const previous = graphqlUsed?.reset === reset ? graphqlUsed.used : 0; + graphqlUsed = { used: Math.max(previous, used), reset }; + return Math.max(0, used - previous); } +/** The HTTP client the GitHub transports send through, recording each request as it is answered. */ +const measuredHttp = Layer.effect( + HttpClient.HttpClient, + Effect.gen(function* () { + const client = yield* HttpClient.HttpClient; + return HttpClient.tap(client, (response) => + Effect.sync(() => { + const graphql = new URL(response.request.url).pathname.endsWith("/graphql"); + reads.push({ + graphqlRequests: graphql ? 1 : 0, + restRequests: graphql ? 0 : 1, + cost: graphql ? graphqlCost(response.headers) : 0, + }); + }), + ); + }), +).pipe(Layer.provide(FetchHttpClient.layer)); + // The server's host port over default settings: gh's own account choice, no saved token. const sourceControlHost = ServerSourceControlHost.layer.pipe( Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))), @@ -57,46 +84,9 @@ const sourceControlHost = ServerSourceControlHost.layer.pipe( Layer.provideMerge(NodeServices.layer), ); -const measuredApi = Layer.effect( - GitHubApi.GitHubApi, - Effect.gen(function* () { - const api = yield* GitHubApi.make; - return GitHubApi.GitHubApi.of({ - ...api, - graphql: (input) => - api.graphql({ ...input, query: withRateLimit(input.query) }).pipe( - Effect.tap((body) => - Effect.sync(() => - reads.push({ - graphqlRequests: 1, - restRequests: 0, - cost: Option.match(decodeCost(body), { - onNone: () => 0, - onSome: (decoded) => decoded.data.rateLimit.cost, - }), - }), - ), - ), - ), - rest: (input) => - api - .rest(input) - .pipe( - Effect.tap(() => - Effect.sync(() => reads.push({ graphqlRequests: 0, restRequests: 1, cost: 0 })), - ), - ), - }); - }), -).pipe( - Layer.provide(GitHubCredentials.layer), - Layer.provide(GitHubQuota.layer), - Layer.provide(SourceControlRateLimit.layer), - Layer.provide(FetchHttpClient.layer), -); - const services = GitHubPullRequestApi.layer.pipe( - Layer.provideMerge(measuredApi), + Layer.provideMerge(GitHubRest.layerWithDependencies), + Layer.provideMerge(measuredHttp), Layer.provideMerge(sourceControlHost), ); @@ -108,6 +98,13 @@ for (const mode of ["detail", "preview"] as const) { Effect.scoped( Effect.gen(function* () { const provider = yield* GitHubPullRequestProvider.make; + // Where the `graphql` quota stands before the first read. `rate_limit` is free. + const api = yield* GitHubRest.GitHubRest; + const limits = decodeRateLimit( + (yield* api.rest({ host: "github.com", operation: "rateLimit", path: "rate_limit" })) + .body, + ).resources.graphql; + graphqlUsed = { used: limits.used, reset: String(limits.reset) }; return yield* Effect.forEach(numbers.map(Number), (number) => Effect.gen(function* () { const input = { cwd: process.cwd(), repository, host: "github.com", number }; diff --git a/apps/server/scripts/runtimeDependencies.test.ts b/apps/server/scripts/runtimeDependencies.test.ts index 920b29e34805e..bf81d42f743df 100644 --- a/apps/server/scripts/runtimeDependencies.test.ts +++ b/apps/server/scripts/runtimeDependencies.test.ts @@ -91,10 +91,10 @@ it("fails when pnpm-lock.yaml is missing a package in the closure", () => { ); }); -// The bundle inlines e2b, but its `import("undici")` resolves from the runtime's node_modules. -// With only Cursor's undici 5 there, HTTP/2 never ended a body-less DELETE, so E2B refused -// every sandbox kill and snapshot delete after a 10 s read timeout. -it("installs the undici major the bundled E2B SDK was built against", () => { +// The bundle inlines e2b, but its `import("undici8")` and `import("undici")` resolve from the +// runtime's node_modules. With only Cursor's undici 5 there, HTTP/2 never ended a body-less +// DELETE, so E2B refused every sandbox kill and snapshot delete after a 10 s read timeout. +it("installs an undici major the bundled E2B SDK was built against", () => { const { dependencies, overrides } = resolveRuntimeDependencies( Schema.decodeUnknownSync(fromYaml(PnpmLock))( NodeFS.readFileSync(new URL("../../../pnpm-lock.yaml", import.meta.url), "utf8"), @@ -103,8 +103,8 @@ it("installs the undici major the bundled E2B SDK was built against", () => { ); const major = (version: string | undefined) => version?.replace(/^\D*/, "").split(".")[0]; - assert.deepStrictEqual( - { installed: major(dependencies.undici ?? overrides.undici) }, - { installed: major(e2bPackage.dependencies.undici) }, + const supported = [e2bPackage.dependencies.undici, e2bPackage.optionalDependencies.undici8].map( + (range) => major(range?.replace(/^npm:undici@/, "")), ); + assert.include(supported, major(dependencies.undici ?? overrides.undici)); }); diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index e32f41372528f..bf0f4431807ef 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -1029,6 +1029,34 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("signs the same HTML page URL within an expiry window", () => + Effect.gen(function* () { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const attachmentId = "thread-1-00000000-0000-4000-8000-000000000001-html"; + yield* fileSystem.makeDirectory(config.attachmentsDir, { recursive: true }); + yield* fileSystem.writeFileString( + path.join(config.attachmentsDir, `${attachmentId}.html`), + "

render

", + ); + const bucketMs = 30 * 60 * 1000; + const issue = issueAssetUrl({ + resource: { _tag: "attachment", attachmentId, disposition: "inline" }, + }); + yield* TestClock.setTime(bucketMs + 1); + const first = yield* issue; + yield* TestClock.adjust("20 minutes"); + const second = yield* issue; + yield* TestClock.adjust("10 minutes"); + const next = yield* issue; + + expect(second.relativeUrl).toBe(first.relativeUrl); + expect(first.expiresAt).toBe(4 * bucketMs); + expect(next.expiresAt).toBe(5 * bucketMs); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("serves video attachments inline", () => Effect.gen(function* () { const config = yield* ServerConfig.ServerConfig; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 6b736c68f74ef..4c30f10c3b3d1 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -71,6 +71,7 @@ export const ASSET_ROUTE_PREFIX = "/api/assets"; const SIGNING_SECRET_NAME = "asset-access-signing-key"; const ASSET_TOKEN_TTL_MS = 60 * 60 * 1000; const PROJECT_FAVICON_TOKEN_BUCKET_MS = 30 * 60 * 1000; +const HTML_ATTACHMENT_TOKEN_BUCKET_MS = 30 * 60 * 1000; const PROJECT_FAVICON_VERSION_PREFIX = "v"; // Clients draw project icons from a 96px thumbnail at most. const PROJECT_FAVICON_ICNS_MIN_SIZE = 96; @@ -825,6 +826,14 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i PROJECT_FAVICON_TOKEN_BUCKET_MS; claims = { ...claims, expiresAt }; } + if (claims.kind === "attachment" && claims.mimeType === "text/html") { + // HTML pages never change, so mints in the same window sign the same URL and a reload + // can answer it from the browser cache. Images keep a new URL per mint, since their + // load-error retries rely on one. + expiresAt = + Math.ceil(expiresAt / HTML_ATTACHMENT_TOKEN_BUCKET_MS) * HTML_ATTACHMENT_TOKEN_BUCKET_MS; + claims = { ...claims, expiresAt }; + } const encodedPayload = base64UrlEncode(encodeAssetClaims(claims)); const token = `${encodedPayload}.${signPayload(encodedPayload, signingSecret)}`; return { diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts index 76035ded632b6..0a90cca56507e 100644 --- a/apps/server/src/binCli.ts +++ b/apps/server/src/binCli.ts @@ -14,6 +14,7 @@ import { browserCommand } from "./cli/browser.ts"; import { connectCommand } from "./cli/connect.ts"; import { pairCommand } from "./cli/pair.ts"; import { hasCloudPublicConfig } from "./cloud/publicConfig.ts"; +import { keepOutboundFetchOnHttp1 } from "./outboundHttp.ts"; import { sharedServerCommandFlags } from "./cli/config.ts"; import { projectCommand } from "./cli/project.ts"; import { runDefaultServerCommand, serveCommand, startCommand } from "./cli/server.ts"; @@ -92,6 +93,7 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) => export const cli = makeCli(); export function runCli() { + keepOutboundFetchOnHttp1(); Command.run(cli, { version: packageJson.version }).pipe( Effect.scoped, Effect.provide(layerCliRuntime), diff --git a/apps/server/src/htmlRender/HtmlRender.test.ts b/apps/server/src/htmlRender/HtmlRender.test.ts index aab68c7b18777..7ab5bda2e1184 100644 --- a/apps/server/src/htmlRender/HtmlRender.test.ts +++ b/apps/server/src/htmlRender/HtmlRender.test.ts @@ -391,7 +391,7 @@ describe("HtmlRender", () => { // Like a D3 chart, the page sizes itself from the width once, at load. const reference = yield* htmlRender.publish({ threadId: ThreadId.make("thread-html-measure"), - html: '
', + html: '
', title: "Chart", height: 600, }); @@ -399,6 +399,8 @@ describe("HtmlRender", () => { expect(reference.heights).toEqual( HTML_RENDER_MEASURE_WIDTHS.map((width) => [width, Math.ceil(width / 2)]), ); + // The chart as the column-width load laid it out, in 4px units. + expect(reference.outline).toBe("m0,0,182,91,1"); }).pipe(Effect.provide(layerHtmlRender(executable))); }), 30_000, diff --git a/apps/server/src/htmlRender/HtmlRender.ts b/apps/server/src/htmlRender/HtmlRender.ts index 47c7238fb4769..bf982a3e9ce65 100644 --- a/apps/server/src/htmlRender/HtmlRender.ts +++ b/apps/server/src/htmlRender/HtmlRender.ts @@ -372,7 +372,7 @@ const make = Effect.gen(function* () { Effect.gen(function* () { const executable = yield* previewBrowser.installed; if (Option.isNone(executable)) return undefined; - const heights = yield* launching(executable.value, (noSandbox) => + const { heights, outline } = yield* launching(executable.value, (noSandbox) => HeadlessChrome.measureHtmlHeights({ executable: executable.value, noSandbox, @@ -391,7 +391,7 @@ const make = Effect.gen(function* () { ), }), ); - return heights.toSorted(([left], [right]) => left - right); + return { heights: heights.toSorted(([left], [right]) => left - right), outline }; }).pipe( Effect.catch((cause) => Effect.logWarning("Could not measure an HTML render; publishing it without heights.", { @@ -432,7 +432,7 @@ const make = Effect.gen(function* () { if (attachmentId === null || filePath === null) { return yield* new HtmlRenderStoreError({ cause: new Error("Invalid thread id.") }); } - const heights = yield* fileSystem.writeFileString(filePath, html).pipe( + const measured = yield* fileSystem.writeFileString(filePath, html).pipe( Effect.mapError((cause) => new HtmlRenderStoreError({ cause })), Effect.andThen(measure(html)), // Only the returned reference lets thread deletion find the page, so a @@ -443,7 +443,8 @@ const make = Effect.gen(function* () { attachmentId, title: input.title.trim().slice(0, HTML_RENDER_MAX_TITLE_LENGTH) || "HTML", height: clampHtmlRenderHeight(input.height), - ...(heights === undefined ? {} : { heights }), + ...(measured === undefined ? {} : { heights: measured.heights }), + ...(measured?.outline === undefined ? {} : { outline: measured.outline }), } satisfies HtmlRenderReference; }); diff --git a/apps/server/src/htmlRender/headlessChrome.ts b/apps/server/src/htmlRender/headlessChrome.ts index ec4aa57515fc0..60a1ef756cf97 100644 --- a/apps/server/src/htmlRender/headlessChrome.ts +++ b/apps/server/src/htmlRender/headlessChrome.ts @@ -9,6 +9,11 @@ import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { + encodeHtmlRenderOutline, + HTML_RENDER_COLUMN_WIDTH, + HTML_RENDER_OUTLINE_MAX_BOXES, +} from "@t3tools/shared/htmlRender"; import { publicProxy } from "./publicProxy.ts"; @@ -157,6 +162,90 @@ const SETTLE_EXPRESSION = const MEASURE_EXPRESSION = "(() => { const root = document.documentElement; return root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height; })()"; +// The page's main blocks in document order, for a client's loading skeleton: +// media and solid shapes, text with its line count, and tables with their row +// count. Boxes that only wrap other blocks are walked through, not drawn. +// Past the detail budget, remaining blocks are kept whole, and once the outline +// is full, one block of text lines stands in for the rest of the page, so the +// skeleton still reaches the bottom. +const OUTLINE_MAX_VISITS = 2_000; +const OUTLINE_EXPRESSION = `(() => { + const boxes = [], detail = ${HTML_RENDER_OUTLINE_MAX_BOXES - 12}, max = ${HTML_RENDER_OUTLINE_MAX_BOXES}; + const media = "canvas,svg,img,video,picture,iframe,object,embed,input,select,textarea,button"; + const pageBackground = getComputedStyle(document.documentElement).backgroundColor; + const filled = (s) => (s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== pageBackground) || s.backgroundImage !== "none" || parseFloat(s.borderTopWidth) + parseFloat(s.borderBottomWidth) + parseFloat(s.borderLeftWidth) > 0; + const add = (kind, r, lines) => boxes.push([kind, r.left + scrollX, r.top + scrollY, r.width, r.height, lines]); + const lineCount = (s, r) => Math.max(1, Math.round(r.height / (parseFloat(s.lineHeight) || parseFloat(s.fontSize) * 1.5 || 20))); + // Text's own extent, so a short heading in a wide block stays short. + const addText = (el, s, r) => { + const range = document.createRange(); + range.selectNodeContents(el); + const t = range.getBoundingClientRect(); + const box = t.width >= 2 && t.height >= 2 ? t : r; + add("text", box, lineCount(s, box)); + }; + // Visits are capped too, so a huge generated DOM costs no more than a page. + let full = false, visits = 0; + // Whether an element holds text of its own, looking at its first few children only. + const hasOwnText = (el) => { + let n = el.firstChild; + for (let i = 0; n && i < 64; n = n.nextSibling, i++) if (n.nodeType === 3 && n.data.trim() !== "") return true; + return false; + }; + const walk = (parent, ps) => { + for (const el of parent.childNodes) { + // The last slot is kept for whatever the outline has no room left for. + if (boxes.length >= max - 1 || ++visits > ${OUTLINE_MAX_VISITS}) { full = true; return; } + // Bare text only reaches here under body or a display: contents element. + if (el.nodeType === 3) { + if (el.data.trim() === "") continue; + const range = document.createRange(); + range.selectNodeContents(el); + const t = range.getBoundingClientRect(); + if (t.width >= 2 && t.height >= 2) add("text", t, lineCount(ps, t)); + continue; + } + if (el.nodeType !== 1) continue; + const s = getComputedStyle(el); + if (s.display === "none" || s.visibility === "hidden" || s.opacity === "0") continue; + if (s.display === "contents") { walk(el, s); continue; } + const r = el.getBoundingClientRect(); + // A zero-size box can still show positioned children, unless it clips them. + if (r.width < 2 || r.height < 2) { if (s.overflow === "visible") walk(el, s); continue; } + const tag = el.localName; + if (el.matches(media)) { add("media", r, 1); continue; } + if (tag === "table") { add("table", r, el.rows.length); continue; } + const text = hasOwnText(el); + if (boxes.length >= detail) { if (el.querySelector(media) || (!text && !el.firstElementChild)) add("media", r, 1); else addText(el, s, r); continue; } + if (text) { addText(el, s, r); continue; } + if (el.children.length === 0) { if (filled(s)) add("media", r, 1); continue; } + walk(el, s); + } + }; + walk(document.body, getComputedStyle(document.body)); + if (full) { + const top = Math.max(0, ...boxes.map((b) => b[2] + b[4])); + const root = document.documentElement; + const rest = (root.scrollHeight > root.clientHeight ? root.scrollHeight : root.getBoundingClientRect().height) - top; + if (rest >= 8) boxes.push(["text", 0, top, document.documentElement.clientWidth, rest, Math.max(1, Math.round(rest / 28))]); + } + return boxes; +})()`; +const Outlined = Schema.Struct({ + result: Schema.Struct({ + value: Schema.Array( + Schema.Tuple([ + Schema.Literals(["text", "media", "table"]), + Schema.Finite, + Schema.Finite, + Schema.Finite, + Schema.Finite, + Schema.Finite, + ]), + ), + }), +}); + const Ignored = Schema.Unknown; const Navigation = Schema.Struct({ errorText: Schema.optional(Schema.String) }); const Measured = Schema.Struct({ result: Schema.Struct({ value: Schema.Finite }) }); @@ -511,7 +600,28 @@ const launchBrowser = Effect.fnUntraced(function* (input: { Effect.ignore, ); - return { load, screenshot, consoleMessages, close }; + /** The loaded page's outline, encoded for an `HtmlRenderReference`. */ + const outline = send( + "Runtime.evaluate", + { expression: OUTLINE_EXPRESSION, returnByValue: true }, + Outlined, + sessionId, + ).pipe( + Effect.map(({ result }) => + encodeHtmlRenderOutline( + result.value.map(([kind, x, y, boxWidth, height, lines]) => ({ + kind, + x, + y, + width: boxWidth, + height, + lines, + })), + ), + ), + ); + + return { load, outline, screenshot, consoleMessages, close }; }); return { openPage }; @@ -568,7 +678,8 @@ export const captureHtmlScreenshot = Effect.fn("headlessChrome.captureHtmlScreen /** * Content heights of the page at each width, each from a fresh load, since * pages often lay themselves out from the width once at load. One browser, - * a few widths at a time. + * a few widths at a time. The load at the column width also reads the page's + * outline; an outline that cannot be read is left out. */ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights")(function* (input: { readonly executable: string; @@ -585,15 +696,27 @@ export const measureHtmlHeights = Effect.fn("headlessChrome.measureHtmlHeights") profileDirectory: path.join(directory, "profile"), }); const body = pageBody(input.html); - return yield* Effect.forEach( + let outline: string | undefined; + const heights = yield* Effect.forEach( input.widths, (width) => browser.openPage(width).pipe( Effect.flatMap((page) => - page.load(body, input.urlFragment).pipe(Effect.ensuring(page.close)), + page.load(body, input.urlFragment).pipe( + Effect.tap(() => + width === HTML_RENDER_COLUMN_WIDTH + ? page.outline.pipe( + Effect.tap((value) => Effect.sync(() => (outline = value))), + Effect.ignore, + ) + : Effect.void, + ), + Effect.ensuring(page.close), + ), ), Effect.map((height) => [width, height] as const), ), { concurrency: MEASURE_CONCURRENCY }, ); + return { heights, outline }; }, Effect.scoped); diff --git a/apps/server/src/mcp/toolkits/html/tools.ts b/apps/server/src/mcp/toolkits/html/tools.ts index c92e2e466f02e..bdd4513ec2ecd 100644 --- a/apps/server/src/mcp/toolkits/html/tools.ts +++ b/apps/server/src/mcp/toolkits/html/tools.ts @@ -89,6 +89,7 @@ const HtmlRenderTool = Tool.make(HTML_RENDER_TOOL_NAME, { title: Schema.String, height: Schema.Number, heights: Schema.optional(Schema.Array(Schema.Tuple([Schema.Int, Schema.Int]))), + outline: Schema.optional(Schema.String), }), message: Schema.String, }), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index f781c1fadd071..7a9f37c6286f0 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -1772,7 +1772,7 @@ it.effect("ProviderSessionManagerV2 releases sessions in parallel on server shut }), ); -it.effect("ProviderSessionManagerV2 closes event subscriptions normally on server shutdown", () => +it.effect("ProviderSessionManagerV2 interrupts event subscriptions on server shutdown", () => Effect.gen(function* () { const state = yield* Ref.make(emptyState); const effect = Effect.gen(function* () { @@ -1807,7 +1807,10 @@ it.effect("ProviderSessionManagerV2 closes event subscriptions normally on serve yield* manager.shutdown; - assert.isEmpty(yield* bufferedSubscription.events.pipe(Stream.runCollect)); + // Buffered events are dropped and the consumer sees an interruption, not + // a clean end, so it leaves run settlement to restart recovery. + const exit = yield* bufferedSubscription.events.pipe(Stream.runCollect, Effect.exit); + assert.isTrue(Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)); }); yield* effect.pipe(Effect.provide(layerTest({ state, idleTimeoutMs: 60_000 }))); diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.ts index 107f2eef21737..89953dee46474 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.ts @@ -593,12 +593,15 @@ export const layerWithOptions = ( ); }); - const closeSubscribers = (entry: LiveSessionEntry) => + // Server shutdown interrupts subscribers rather than ending them: a + // cleanly ended stream without a terminal fails its run, while an + // interrupted one leaves run settlement to restart recovery. + const interruptSubscribers = (entry: LiveSessionEntry) => Effect.gen(function* () { const subscribers = yield* Ref.getAndSet(entry.eventSubscribers, new Map()); yield* Effect.forEach( subscribers.values(), - (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.end(queue))), + (queue) => Queue.clear(queue).pipe(Effect.andThen(Queue.interrupt(queue))), { discard: true }, ); }); @@ -1087,7 +1090,7 @@ export const layerWithOptions = ( if (input.gracefulSubscribers === true) { yield* endSubscribers(entry); } else if (input.reason === "server_shutdown") { - yield* closeSubscribers(entry); + yield* interruptSubscribers(entry); } else { yield* failSubscribers( entry, @@ -2109,15 +2112,17 @@ export const layerWithOptions = ( }).pipe(logReleaseFailure(entry.runtime.providerSessionId)); return; } - const cause = Exit.isFailure(exit) - ? exit.cause - : Cause.fail( - new ProviderAdapter.ProviderAdapterEventStreamError({ - driver: entry.runtime.driver, - providerSessionId: entry.runtime.providerSessionId, - cause: "Provider event stream ended unexpectedly.", - }), - ); + // Subscribers read an interrupt as server shutdown, so keep it for that. + const cause = + Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause) + ? exit.cause + : Cause.fail( + new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: entry.runtime.driver, + providerSessionId: entry.runtime.providerSessionId, + cause: "Provider event stream ended unexpectedly.", + }), + ); yield* publishToSubscribers(entry.eventSubscribers, { type: "failure", cause, diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index d877922a644a6..592886e0b946c 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -3742,9 +3742,11 @@ it.effect("does not refresh pull requests for auxiliary or stale provider termin { ...ids, rootProviderTurnId: ProviderTurnId.make("turn:previous") }, "interrupted", ), + rootTerminalEvent(ids, "cancelled"), ]), }); - assert.deepEqual(observed, []); + // Only the root terminal settles the run and refreshes pull requests. + assert.deepEqual(observed, ["run:cancelled", "pull-requests-refreshed"]); }), ); @@ -3772,6 +3774,58 @@ it.effect("refreshes pull requests after a provider stream exits with an error", }), ); +it.effect("fails the run when its event stream ends without a root terminal", () => + Effect.gen(function* () { + const { observed, finalEvents } = yield* captureRootRunTermination({ + key: "stream-end-without-terminal", + shouldFinalizeRun: () => Effect.succeed(true), + events: () => Stream.empty, + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.equal( + finalEvents.find((event) => event.type === "provider-thread.updated")?.payload.status, + "idle", + ); + }), +); + +it.effect("leaves the run to restart recovery when shutdown interrupts its event stream", () => + Effect.gen(function* () { + const { written, observed } = yield* captureRootRunTermination({ + key: "stream-end:shutdown", + shouldFinalizeRun: () => Effect.succeed(true), + events: () => Stream.failCause(Cause.interrupt()), + }); + assert.deepEqual(written, []); + assert.deepEqual(observed, []); + }), +); + +it.effect("does not start a turn whose run settled during the app context read", () => + Effect.gen(function* () { + const contextReadStarted = yield* Deferred.make(); + const runFailed = yield* Deferred.make(); + const current = yield* Ref.make(true); + const providerCalls = yield* Ref.make(0); + const { observed } = yield* captureRootRunTermination({ + key: "stream-end:context-read", + shouldStartProviderTurn: () => Ref.get(current), + shouldFinalizeRun: () => Ref.get(current), + events: () => Stream.unwrap(Deferred.await(contextReadStarted).pipe(Effect.as(Stream.empty))), + appContext: Deferred.succeed(contextReadStarted, undefined).pipe( + Effect.andThen(Deferred.await(runFailed)), + Effect.as([]), + ), + refreshAfterTurn: Ref.set(current, false).pipe( + Effect.andThen(Deferred.succeed(runFailed, undefined)), + ), + startTurn: () => Ref.update(providerCalls, (count) => count + 1), + }); + assert.deepEqual(observed, ["run:failed", "pull-requests-refreshed"]); + assert.equal(yield* Ref.get(providerCalls), 0); + }), +); + it.effect("refreshes pull requests only once when startup failure closes its event stream", () => Effect.gen(function* () { const ingestionStarted = yield* Deferred.make(); @@ -3828,6 +3882,8 @@ function captureRootRunTermination(input: { >; readonly startTurn?: ProviderAdapter.ProviderAdapterV2SessionRuntime["startTurn"]; readonly refreshAfterTurn?: Effect.Effect; + readonly shouldStartProviderTurn?: RunExecutionService.RunExecutionServiceV2StartRootRunInput["shouldStartProviderTurn"]; + readonly appContext?: ReturnType; }) { return Effect.gen(function* () { const ids = backgroundScenarioIds(input.key); @@ -3840,6 +3896,7 @@ function captureRootRunTermination(input: { status: "running", }); const writtenItems = yield* Ref.make>([]); + const finalEvents = yield* Ref.make>([]); const observed = yield* Ref.make>([]); const submittedEffects = yield* Ref.make>([]); const committedEffects = yield* Ref.make>([]); @@ -3848,6 +3905,7 @@ function captureRootRunTermination(input: { Ref.update(writtenItems, (current) => [...current, payload]); const captureFinalEvents = (events: ReadonlyArray) => Effect.gen(function* () { + yield* Ref.update(finalEvents, (current) => [...current, ...events]); for (const event of events) { if (event.type === "turn-item.updated") { yield* captureTurnItem(event.payload); @@ -3860,7 +3918,9 @@ function captureRootRunTermination(input: { const layerTest = RunExecutionService.layer.pipe( Layer.provide( Layer.mergeAll( - McpAppModelContext.layerEmpty, + Layer.mock(McpAppModelContext.McpAppModelContext)({ + forThread: () => input.appContext ?? Effect.succeed([]), + }), Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }), Layer.mock(EventSink.EventSinkV2)({ write: (payload) => @@ -3970,6 +4030,9 @@ function captureRootRunTermination(input: { attemptId: ids.attemptId, providerTurnOrdinal: 1, shouldFinalizeRun: input.shouldFinalizeRun, + ...(input.shouldStartProviderTurn === undefined + ? {} + : { shouldStartProviderTurn: input.shouldStartProviderTurn }), ...(input.hasUnpairedRunInterruptRequest === undefined ? {} : { @@ -4000,6 +4063,7 @@ function captureRootRunTermination(input: { yield* Deferred.await(ingestionDone); return { written: yield* Ref.get(writtenItems), + finalEvents: yield* Ref.get(finalEvents), observed: yield* Ref.get(observed), submittedEffects: yield* Ref.get(submittedEffects), committedEffects: yield* Ref.get(committedEffects), diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index 5b879fa27bda3..8b29e3acf8891 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -1313,83 +1313,85 @@ export const layer: Layer.Layer< Effect.gen(function* () { const terminal = yield* Ref.get(terminalEvent); if (terminal === null) { - return; + // A session release interrupts or fails the stream; a clean + // end without a terminal means the run would never settle. + return yield* new RunExecutionIngestError({ + runId: input.run.id, + cause: new ProviderAdapter.ProviderAdapterEventStreamError({ + driver: input.providerThread.driver, + providerSessionId: input.providerSessionId, + cause: "Provider event stream ended without a root terminal.", + }), + }); } yield* finalizeRootRun(terminal); }), ), - Effect.catchCause((cause) => - Ref.get(rootRunFinalized).pipe( - Effect.flatMap((finalized) => - Effect.logWarning("orchestration V2 provider event ingestion failed", { - runId: input.run.id, - cause, - }).pipe( - Effect.andThen( - finalized - ? Effect.void - : Ref.get(latestProviderThread).pipe( - Effect.flatMap((providerThread) => - Ref.get(latestTurnItemOrdinal).pipe( - Effect.flatMap((latestItemOrdinal) => - Ref.get(openRunOwnedSubagents).pipe( - Effect.flatMap((openSubagents) => - writeFinalRunEvents({ - run: input.run, - rootNode: input.rootNode, - checkpointScope: input.checkpointScope, - providerThread, - attempt: input.attempt, - // The failure may be the ownership - // read itself, so check in the write. - writeIfRunCurrent: { - activeAttemptId: input.attempt.id, - expectedStatus: "running", - }, - openRunOwnedSubagents: openSubagents, - terminal: makeFailedTerminalEvent( - makeProviderFailure({ - cause: Cause.squash(cause), - class: "unknown", - }), - latestItemOrdinal + 1, - ), - failureItemPersisted: false, - refreshAfterTurn, - }), + // Server shutdown interrupts the subscription and leaves the run to + // restart recovery; every other failure fails the run. + Effect.catchCauseIf( + (cause) => !Cause.hasInterruptsOnly(cause), + (cause) => + Ref.get(rootRunFinalized).pipe( + Effect.flatMap((finalized) => + Effect.logWarning("orchestration V2 provider event ingestion failed", { + runId: input.run.id, + cause, + }).pipe( + Effect.andThen( + finalized + ? Effect.void + : Ref.get(latestProviderThread).pipe( + Effect.flatMap((providerThread) => + Ref.get(latestTurnItemOrdinal).pipe( + Effect.flatMap((latestItemOrdinal) => + Ref.get(openRunOwnedSubagents).pipe( + Effect.flatMap((openSubagents) => + writeFinalRunEvents({ + run: input.run, + rootNode: input.rootNode, + checkpointScope: input.checkpointScope, + providerThread, + attempt: input.attempt, + // The failure may be the ownership + // read itself, so check in the write. + writeIfRunCurrent: { + activeAttemptId: input.attempt.id, + expectedStatus: "running", + }, + openRunOwnedSubagents: openSubagents, + terminal: makeFailedTerminalEvent( + makeProviderFailure({ + cause: Cause.squash(cause), + class: "unknown", + }), + latestItemOrdinal + 1, + ), + failureItemPersisted: false, + refreshAfterTurn, + }), + ), ), ), ), ), ), - ), - ), - Effect.mapError( - (writeCause) => - new RunExecutionIngestError({ - runId: input.run.id, - cause: { ingest: cause, write: writeCause }, - }), + ), + Effect.mapError( + (writeCause) => + new RunExecutionIngestError({ + runId: input.run.id, + cause: { ingest: cause, write: writeCause }, + }), + ), ), ), ), - ), ), Effect.ensuring(eventSubscription.close), Effect.forkDetach, ); - // A failed read fails the start below, so the run is recorded as - // failed instead of staying active with no provider turn. - const shouldStart = - input.shouldStartProviderTurn === undefined - ? Exit.succeed(true) - : yield* Effect.exit(input.shouldStartProviderTurn()); - if (Exit.isSuccess(shouldStart) && !shouldStart.value) { - yield* Fiber.interrupt(providerEventFiber); - 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. @@ -1433,6 +1435,17 @@ export const layer: Layer.Layer< runtimePolicy: input.runtimePolicy, ...(appContext.length === 0 ? {} : { appContext }), }; + // Check after the context read: ingestion can settle the run while + // it awaits. A failed ownership read fails the start below. + const shouldStart = + input.shouldStartProviderTurn === undefined + ? Exit.succeed(true) + : yield* Effect.exit(input.shouldStartProviderTurn()); + if (Exit.isSuccess(shouldStart) && !shouldStart.value) { + yield* Fiber.interrupt(providerEventFiber); + return; + } + const compact = input.message.attachments.length === 0 && input.message.text.trim().toLowerCase() === "/compact"; diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts index e68fa3bef7cdb..da11d9046b891 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts @@ -128,6 +128,8 @@ import { skillInvocationInput } from "./skill_invocation/input.ts"; import { assertSimpleOutput } from "./simple/codex_output.ts"; import { assertPiSimpleOutput } from "./simple/pi_output.ts"; import { simpleInput } from "./simple/input.ts"; +import { malformedSessionUpdateInput } from "./malformed_session_update/input.ts"; +import { assertMalformedSessionUpdateOutput } from "./malformed_session_update/output.ts"; import { assertSubagentOutput } from "./subagent/codex_output.ts"; import { assertClaudeSubagentOutput } from "./subagent/claude_output.ts"; import { subagentInput } from "./subagent/input.ts"; @@ -594,6 +596,21 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray item.type), + "error", + ); + assertAssistantTextIncludes(projection, "malformed update fixture ok"); +} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/malformed_session_update/registry_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/malformed_session_update/registry_transcript.ndjson new file mode 100644 index 0000000000000..3d21491ad20d4 --- /dev/null +++ b/apps/server/src/orchestration-v2/testkit/fixtures/malformed_session_update/registry_transcript.ndjson @@ -0,0 +1,14 @@ +{"type":"transcript_start","provider":"acpRegistry","protocol":"acp.ndjson-jsonrpc","version":"1","scenario":"malformed_session_update","metadata":{"generatedBy":"protocol-semantic-fixture","nativeSessionId":"grok-replay-session-1"}} +{"type":"expect_outbound","label":"initialize","frame":{"kind":"request","method":"initialize","params":{"protocolVersion":2,"info":"","capabilities":"","clientCapabilities":"","clientInfo":""}}} +{"type":"emit_inbound","label":"initialized","frame":{"kind":"response","method":"initialize","result":{"protocolVersion":1,"agentCapabilities":{"loadSession":true,"mcpCapabilities":{"http":true,"sse":true},"promptCapabilities":{"audio":false,"embeddedContext":true,"image":false}},"authMethods":[{"id":"replay","name":"Replay"}],"agentInfo":{"name":"grok-replay","version":"1"}}}} +{"type":"expect_outbound","label":"session.new","frame":{"kind":"request","method":"session/new","params":{"cwd":"","mcpServers":""}}} +{"type":"emit_inbound","label":"session.created","frame":{"kind":"response","method":"session/new","result":{"sessionId":"grok-replay-session-1","models":{"currentModelId":"grok-build","availableModels":[{"modelId":"grok-build","name":"Grok Build"},{"modelId":"grok-composer-2.5-fast","name":"Grok Composer 2.5 Fast"}]}}}} +{"type":"expect_outbound","label":"session.prompt","frame":{"kind":"request","method":"session/prompt","params":{"sessionId":"grok-replay-session-1","prompt":[{"type":"text","text":"\n\n\n\n\nRespond with the following text: malformed update fixture ok\n"}]}}} +{"type":"emit_inbound","label":"reasoning.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"I should "}}}}} +{"type":"emit_inbound","label":"reasoning.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_thought_chunk","content":{"type":"text","text":"answer exactly."}}}}} +{"type":"emit_inbound","label":"usage.malformed","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"usage_update","cost":{"amount":0.01,"currency":"USD"}}}}} +{"type":"emit_inbound","label":"assistant.1","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"malformed update "}}}}} +{"type":"emit_inbound","label":"assistant.2","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"fixture ok"}}}}} +{"type":"emit_inbound","label":"usage.valid","frame":{"kind":"notification","method":"session/update","params":{"sessionId":"grok-replay-session-1","update":{"sessionUpdate":"usage_update","used":1200,"size":200000}}}} +{"type":"emit_inbound","label":"prompt.completed","frame":{"kind":"response","method":"session/prompt","result":{"stopReason":"end_turn"}}} +{"type":"runtime_exit","status":"success"} diff --git a/apps/server/src/outboundHttp.test.ts b/apps/server/src/outboundHttp.test.ts new file mode 100644 index 0000000000000..a7863824323ea --- /dev/null +++ b/apps/server/src/outboundHttp.test.ts @@ -0,0 +1,97 @@ +// @effect-diagnostics nodeBuiltinImport:off - the test runs a real TLS h2 server to see which protocol fetch negotiates. +import * as NodeHttp2 from "node:http2"; +import * as NodeNet from "node:net"; +import * as NodeTls from "node:tls"; + +import { it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient } from "effect/http"; +import * as Undici from "undici"; +import { afterAll, afterEach, beforeAll, describe, expect } from "vite-plus/test"; + +import { builtinFetchUsesHttp2, installHttp1FetchDispatcher } from "./outboundHttp.ts"; + +// Test-only self-signed P-256 certificate for 127.0.0.1, valid until 2126; not a +// secret. Node cannot mint X.509 certificates without a library, and a local +// server only offers h2 over ALPN, which needs TLS. +const TEST_KEY = `-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg3EwCztQysKTvzdcR +g0LWq+axzUd4tHi9PyMdqh7PlGShRANCAARfQpoLgv/tOsHWCLriDza7Ruaey2b7 +mR/nS6mLu6W7+agkEqDm0mE3F/ngpPjL4Jj0IGadeMcKNKFRSBgiLdfn +-----END PRIVATE KEY----- +`; +const TEST_CERT = `-----BEGIN CERTIFICATE----- +MIIBsDCCAVagAwIBAgIUWbn2Wt5kTxii1UU57NJMt/wTaUgwCgYIKoZIzj0EAwIw +JDEiMCAGA1UEAwwZdDNjb2RlIG91dGJvdW5kIGh0dHAgdGVzdDAgFw0yNjEwMTEy +MjQyMzZaGA8yMTI2MDkxNzIyNDIzNlowJDEiMCAGA1UEAwwZdDNjb2RlIG91dGJv +dW5kIGh0dHAgdGVzdDBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABF9CmguC/+06 +wdYIuuIPNrtG5p7LZvuZH+dLqYu7pbv5qCQSoObSYTcX+eCk+MvgmPQgZp14xwo0 +oVFIGCIt1+ejZDBiMB0GA1UdDgQWBBSsekAc30Q/zdIE/tvVDQKJL5oiCDAfBgNV +HSMEGDAWgBSsekAc30Q/zdIE/tvVDQKJL5oiCDAPBgNVHRMBAf8EBTADAQH/MA8G +A1UdEQQIMAaHBH8AAAEwCgYIKoZIzj0EAwIDSAAwRQIgebUrkyP56242EJB7nCV7 +A+Ke/q0rNPya3fjQa9O5B+kCIQC1SfmdNaFcNJ4JINlus4FfrRnfKiADS2MIJR9f +99BN0A== +-----END CERTIFICATE----- +`; + +// An h2-capable origin, like api.github.com, that answers with the HTTP +// version the client negotiated. +const server = NodeHttp2.createSecureServer( + { allowHTTP1: true, key: TEST_KEY, cert: TEST_CERT }, + (request, response) => response.end(request.httpVersion), +); +let origin = ""; +const defaultCaCertificates = NodeTls.getCACertificates("default"); +const defaultDispatcher = Undici.getGlobalDispatcher(); + +beforeAll(async () => { + NodeTls.setDefaultCACertificates([...defaultCaCertificates, TEST_CERT]); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + origin = `https://127.0.0.1:${(server.address() as NodeNet.AddressInfo).port}/`; +}); + +afterEach(() => { + Undici.setGlobalDispatcher(defaultDispatcher); +}); + +afterAll(async () => { + NodeTls.setDefaultCACertificates(defaultCaCertificates); + await new Promise((resolve) => server.close(() => resolve())); +}); + +const versionViaGlobalDispatcher = async () => (await Undici.request(origin)).body.text(); + +// Node's built-in fetch, the path the server's own requests take. +const versionViaBuiltinFetch = () => + HttpClient.get(origin).pipe( + Effect.flatMap((response) => response.text), + Effect.provide(FetchHttpClient.layer), + ); + +describe("installHttp1FetchDispatcher", () => { + it("makes the global dispatcher negotiate HTTP/1.1 and keeps the env proxy agent", async () => { + // undici 8's default agent, the one Node 26's fetch uses. + Undici.setGlobalDispatcher(new Undici.Agent()); + expect(await versionViaGlobalDispatcher()).toBe("2.0"); + + installHttp1FetchDispatcher(); + expect(await versionViaGlobalDispatcher()).toBe("1.1"); + + // Node installs this agent for --use-env-proxy; replacing it would drop the proxy. + Undici.setGlobalDispatcher(new Undici.EnvHttpProxyAgent()); + installHttp1FetchDispatcher(); + expect(Undici.getGlobalDispatcher()).toBeInstanceOf(Undici.EnvHttpProxyAgent); + }); + + // Only a runtime that bundles undici 8 (Node 26+) offers h2 through the + // built-in fetch, so only there can this prove fetch reads the new dispatcher. + it.effect.runIf(builtinFetchUsesHttp2(process.versions.undici))( + "moves the built-in fetch off HTTP/2", + () => + Effect.gen(function* () { + expect(yield* versionViaBuiltinFetch()).toBe("2.0"); + installHttp1FetchDispatcher(); + expect(yield* versionViaBuiltinFetch()).toBe("1.1"); + }), + ); +}); diff --git a/apps/server/src/outboundHttp.ts b/apps/server/src/outboundHttp.ts new file mode 100644 index 0000000000000..d021c1abac3a0 --- /dev/null +++ b/apps/server/src/outboundHttp.ts @@ -0,0 +1,54 @@ +import * as NodeModule from "node:module"; + +import type * as Undici from "undici"; + +// undici stays external to the CLI bundle (scripts/lib/cli-external-packages.ts). +// Inside a Node single-executable only `require` can load it from disk. +const requireUndici = NodeModule.createRequire(import.meta.url); + +/** + * True when the runtime's built-in `fetch` negotiates HTTP/2 by default. + * Node 26 bundles undici 8, which offers h2 over ALPN to every HTTPS origin. + * Node 22/24 (and Electron) bundle undici 6/7, whose fetch stays on HTTP/1.1. + */ +export const builtinFetchUsesHttp2 = (bundledUndiciVersion: string | undefined) => + Number.parseInt(bundledUndiciVersion ?? "", 10) >= 8; + +/** + * Replaces the process-wide fetch dispatcher with one that only speaks HTTP/1.1. + * + * Node's built-in fetch reads its dispatcher from the + * `Symbol.for("undici.globalDispatcher.1"/".2")` globals, and the npm package's + * `setGlobalDispatcher` writes both. This covers requests using the default + * fetch dispatcher, including Effect's `FetchHttpClient`; `node:http` callers + * (e.g. `cli/sshHelper.ts`) are unaffected and already speak HTTP/1.1. + * + * Node's `--use-env-proxy` / `NODE_USE_ENV_PROXY` installs an + * `EnvHttpProxyAgent` at startup; that choice is kept so proxies still apply. + */ +export function installHttp1FetchDispatcher(): void { + const undici = requireUndici("undici") as typeof Undici; + // Node's agent comes from its internal undici copy, so `instanceof` against the npm class is false. + const usesEnvProxy = undici.getGlobalDispatcher().constructor.name === "EnvHttpProxyAgent"; + undici.setGlobalDispatcher( + usesEnvProxy + ? new undici.EnvHttpProxyAgent({ + allowH2: false, + // The connection to an HTTPS proxy is built here, not from `allowH2`. ProxyAgent's + // `connect` option is dropped on purpose: its connector has h2 fixed on. + clientFactory: (origin) => new undici.Pool(origin, { allowH2: false }), + }) + : new undici.Agent({ allowH2: false }), + ); +} + +/** + * Keeps outbound fetch on HTTP/1.1. An undici HTTP/2 session that hits its + * idle timeout can emit `'error'` on a stream with no listener, which Node + * turns into an uncaught exception that exits the server + * (https://github.com/nodejs/undici/issues/5936). Runtimes whose fetch never + * negotiates h2 are left untouched. + */ +export function keepOutboundFetchOnHttp1(): void { + if (builtinFetchUsesHttp2(process.versions.undici)) installHttp1FetchDispatcher(); +} diff --git a/apps/server/src/preview/PortScanner.test.ts b/apps/server/src/preview/PortScanner.test.ts index 8aae21d8cf71b..3e2495a072a7a 100644 --- a/apps/server/src/preview/PortScanner.test.ts +++ b/apps/server/src/preview/PortScanner.test.ts @@ -8,6 +8,7 @@ import { } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as Cause from "effect/Cause"; +import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as Clock from "effect/Clock"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; @@ -789,3 +790,136 @@ effectIt.effect("does not swallow process probe interruption", () => } }), ); + +effectIt.effect( + "parses Windows netstat listeners, names them via tasklist with retry, and skips spawns when idle", + () => { + const spawnedArgs: Array> = []; + let tasklistCalls = 0; + const fetchFn = (() => + Promise.resolve( + new Response("hello", { headers: { "content-type": "text/html" } }), + )) as typeof globalThis.fetch; + const layer = PortScanner.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerNoProc, + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => { + spawnedArgs.push(input.args); + const isIpv6 = input.args.includes("tcpv6"); + const isTasklist = input.command === "tasklist.exe"; + // The first lookup fails, so it must not be cached as "no name". + const failTasklist = isTasklist && tasklistCalls++ === 0; + return Effect.succeed({ + stdout: isTasklist + ? '"node.exe","1234","Console","1","93,164 K"\r\n' + : isIpv6 + ? " TCP [::1]:43123 [::]:0 ABHÖREN 1234\r\n TCP [::1]:43123 [::1]:52000 HERGESTELLT 1234\r\n" + : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n TCP 127.0.0.1:5173 127.0.0.1:60123 ESTABLISHED 9999\r\n", + stderr: "", + code: failTasklist ? ChildProcessSpawner.ExitCode(1) : null, + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }); + }, + }), + Layer.succeed(HostProcess.Platform, "win32"), + FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + expect(yield* scanner.scan()).toEqual([]); + expect(spawnedArgs).toHaveLength(0); + + yield* scanner.registerTerminalProcesses({ + threadId: "scanner-thread", + terminalId: "scanner-terminal", + processIds: [1234], + }); + const summarize = ( + servers: ReadonlyArray<{ + readonly port: number; + readonly pid: number | null; + readonly processName: string | null; + }>, + ) => + servers.map((entry) => ({ + port: entry.port, + pid: entry.pid, + processName: entry.processName, + })); + expect(summarize(yield* scanner.scan())).toEqual([ + { port: 5173, pid: 1234, processName: null }, + { port: 43123, pid: 1234, processName: null }, + ]); + expect(spawnedArgs).toEqual([ + ["-ano", "-p", "tcp"], + ["-ano", "-p", "tcpv6"], + ["/FO", "CSV", "/NH", "/FI", "PID eq 1234"], + ]); + + // The failed lookup retries; the result is then cached, so later polls spawn only netstat. + expect(summarize(yield* scanner.scan())).toEqual([ + { port: 5173, pid: 1234, processName: "node" }, + { port: 43123, pid: 1234, processName: "node" }, + ]); + yield* scanner.scan(); + expect(tasklistCalls).toBe(2); + + // Cached names expire, since Windows may hand the PID to another process. + yield* TestClock.adjust(Duration.seconds(61)); + yield* scanner.scan(); + expect(tasklistCalls).toBe(3); + }).pipe(Effect.provide(layer)); + }, +); + +effectIt.effect("ignores a partial Windows netstat snapshot when one query exits nonzero", () => { + const fetchFn = (() => + Promise.resolve( + new Response("hello", { headers: { "content-type": "text/html" } }), + )) as typeof globalThis.fetch; + const layer = PortScanner.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerNoProc, + Layer.succeed(ProcessRunner.ProcessRunner, { + run: (input) => { + const isIpv6 = input.args.includes("tcpv6"); + return Effect.succeed({ + stdout: isIpv6 + ? "" + : " TCP 127.0.0.1:5173 0.0.0.0:0 LISTENING 1234\r\n", + stderr: "", + code: isIpv6 ? ChildProcessSpawner.ExitCode(1) : null, + timedOut: false, + stdoutTruncated: false, + stderrTruncated: false, + stdoutInvalidUtf8: false, + stderrInvalidUtf8: false, + }); + }, + }), + Layer.succeed(HostProcess.Platform, "win32"), + FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetchFn))), + ), + ), + ); + + return Effect.gen(function* () { + const scanner = yield* PortScanner.PortDiscovery; + yield* scanner.registerTerminalProcesses({ + threadId: "scanner-thread", + terminalId: "scanner-terminal", + processIds: [1234], + }); + expect(yield* scanner.scan()).toEqual([]); + }).pipe(Effect.provide(layer)); +}); diff --git a/apps/server/src/preview/PortScanner.ts b/apps/server/src/preview/PortScanner.ts index 7a59079ea9f47..84a80ff965114 100644 --- a/apps/server/src/preview/PortScanner.ts +++ b/apps/server/src/preview/PortScanner.ts @@ -77,8 +77,13 @@ const PROC_FD_WALK_LIMIT = 50_000; /** Scans that retry the fd walk for a listening socket whose owner was not found. */ const SOCKET_OWNER_ATTEMPTS = 3; const WINDOWS_LISTENER_TIMEOUT_MS = 5_000; +/** `netstat -ano` lists every connection, not just listeners; ~80 bytes per row, sized for ~200k rows. */ +const WINDOWS_NETSTAT_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; const WEB_PROBE_TIMEOUT = Duration.seconds(1); const WEB_PROBE_CACHE_TTL_MS = Duration.toMillis(Duration.seconds(15)); +/** Bounds how long a cached Windows image name can outlive its process if Windows reuses the PID. */ +const WINDOWS_PROCESS_NAME_TTL_MS = Duration.toMillis(Duration.seconds(60)); +const WINDOWS_PROCESS_NAME_CONCURRENCY = 4; const WEB_PROBE_CONCURRENCY = 16; const NAVIGATION_REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); @@ -249,19 +254,78 @@ const parsePortFromLsofName = (name: string): number | null => { return port; }; +const parseWindowsListenerLine = ( + line: string, +): { + readonly host: string; + readonly port: number; + readonly pid: number | null; + readonly processName: string | null; +} | null => { + const trimmed = line.trim(); + if (trimmed.length === 0) return null; + + if (trimmed.includes("|")) { + const [hostRaw, portRaw, pidRaw, processNameRaw] = trimmed.split("|", 4); + const host = hostRaw?.trim() ?? ""; + if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null; + const port = Number(portRaw); + const pid = Number(pidRaw); + if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null; + return { + host, + port, + pid: Number.isInteger(pid) && pid > 0 ? pid : null, + processName: processNameRaw?.trim() || null, + }; + } + + // `netstat.exe -ano -p tcp` / `tcpv6`: + // TCP 127.0.0.1:3773 0.0.0.0:0 LISTENING 34280 + // TCP [::1]:35783 [::]:0 LISTENING 22876 + // Foreign port `:0` identifies a listening TCP socket regardless of Windows locale. + const fields = trimmed.split(/\s+/); + if (fields.length < 4 || fields[0]?.toUpperCase() !== "TCP") return null; + const localEndpoint = fields[1] ?? ""; + const foreignEndpoint = fields[2] ?? ""; + if (!foreignEndpoint.endsWith(":0")) return null; + const lastColon = localEndpoint.lastIndexOf(":"); + if (lastColon <= 0) return null; + const host = localEndpoint.slice(0, lastColon); + if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") return null; + const port = Number(localEndpoint.slice(lastColon + 1)); + if (!Number.isInteger(port) || port <= 0 || port >= 65536) return null; + const pid = Number(fields.at(-1)); + return { + host, + port, + pid: Number.isInteger(pid) && pid > 0 ? pid : null, + processName: null, + }; +}; + +/** `ProcessRunner` reports a nonzero exit as a result, not a failure. */ +const exitedWithError = (result: ProcessRunner.ProcessRunOutput): boolean => + result.code !== null && result.code !== 0; + +/** Reads the image name from `tasklist.exe /FO CSV /NH /FI "PID eq "` output. */ +const parseTasklistProcessName = (raw: string, pid: number): string | null => { + for (const line of raw.split(/\r?\n/g)) { + const match = /^"([^"]*)","(\d+)"/.exec(line.trim()); + if (match && Number(match[2]) === pid) return match[1]!.replace(/\.exe$/i, "") || null; + } + return null; +}; + const parseWindowsListenerOutput = ( raw: string, terminalByProcessId: ReadonlyMap = new Map(), ): ReadonlyArray => { const seen = new Map(); for (const line of raw.split(/\r?\n/g)) { - const [hostRaw, portRaw, pidRaw, processNameRaw] = line.trim().split("|", 4); - const host = hostRaw?.trim() ?? ""; - if (!LSOF_LOCAL_HOST_TOKENS.has(host) && host !== "::") continue; - const port = Number(portRaw); - const pid = Number(pidRaw); - if (!Number.isInteger(port) || port <= 0 || port >= 65536) continue; - const normalizedPid = Number.isInteger(pid) && pid > 0 ? pid : null; + const parsed = parseWindowsListenerLine(line); + if (!parsed) continue; + const { port, pid: normalizedPid, processName } = parsed; const terminal = normalizedPid === null ? null : (terminalByProcessId.get(normalizedPid) ?? null); const existing = seen.get(port); @@ -273,7 +337,7 @@ const parseWindowsListenerOutput = ( host: "localhost", port, url: `http://localhost:${port}`, - processName: processNameRaw?.trim() || null, + processName, pid: normalizedPid, terminal, }); @@ -358,6 +422,10 @@ export const make = Effect.gen(function* PortDiscoveryMake() { const webProbeCacheRef = yield* Ref.make>(new Map()); const scanSemaphore = yield* Semaphore.make(1); const lsofMissingRef = yield* Ref.make(false); + /** Windows image names by PID; netstat reports only PIDs. */ + const windowsProcessNamesRef = yield* Ref.make< + ReadonlyMap + >(new Map()); /** Confirmed owners of listening socket inodes. */ const socketOwnersRef = yield* Ref.make< ReadonlyMap @@ -604,6 +672,57 @@ export const make = Effect.gen(function* PortDiscoveryMake() { return { discovered, configured } satisfies WebProbeSnapshot; }); + // `tasklist` costs ~200-300ms per PID, so look up only visible servers, a few at a time, and + // reuse each name until its TTL expires. + const withWindowsProcessNames = Effect.fn("PortDiscovery.withWindowsProcessNames")(function* ( + snapshot: WebProbeSnapshot, + ) { + const servers = [...snapshot.discovered, ...snapshot.configured.values()]; + const pids = new Set(servers.flatMap((server) => (server.pid === null ? [] : [server.pid]))); + const nowMillis = yield* Clock.currentTimeMillis; + const cached = [...(yield* Ref.get(windowsProcessNamesRef))].filter( + ([pid, entry]) => pids.has(pid) && entry.expiresAtMillis > nowMillis, + ); + const cachedPids = new Set(cached.map(([pid]) => pid)); + const expiresAtMillis = nowMillis + WINDOWS_PROCESS_NAME_TTL_MS; + const fetched = yield* Effect.forEach( + [...pids].filter((pid) => !cachedPids.has(pid)), + (pid) => + processRunner + .run({ + command: "tasklist.exe", + args: ["/FO", "CSV", "/NH", "/FI", `PID eq ${pid}`], + timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS), + maxOutputBytes: 64 * 1024, + }) + .pipe( + // Only a completed lookup is cached; failures retry on the next scan. + Effect.map((result) => + exitedWithError(result) + ? [] + : [ + [ + pid, + { name: parseTasklistProcessName(result.stdout, pid), expiresAtMillis }, + ] as const, + ], + ), + Effect.orElseSucceed(() => []), + ), + { concurrency: WINDOWS_PROCESS_NAME_CONCURRENCY }, + ); + const names = new Map([...cached, ...fetched.flat()]); + yield* Ref.set(windowsProcessNamesRef, names); + const withName = (server: DiscoveredLocalServer): DiscoveredLocalServer => + server.pid === null || server.processName !== null + ? server + : { ...server, processName: names.get(server.pid)?.name ?? null }; + return { + discovered: snapshot.discovered.map(withName), + configured: new Map([...snapshot.configured].map(([key, server]) => [key, withName(server)])), + } satisfies WebProbeSnapshot; + }); + const recoverProcessProbeFailure = (probe: "lsof" | "windows-listeners") => (error: ProcessRunner.ProcessRunError) => Effect.logDebug("preview port process probe failed; probing configured URLs only", { @@ -623,28 +742,38 @@ export const make = Effect.gen(function* PortDiscoveryMake() { } } if (hostPlatform === "win32") { + if (terminalByProcessId.size === 0 && configuredUrls.length === 0) { + return { discovered: [], configured: new Map() } satisfies WebProbeSnapshot; + } const recoverWindowsProbeFailure = recoverProcessProbeFailure("windows-listeners"); - const command = - 'Get-NetTCPConnection -State Listen -ErrorAction Stop | ForEach-Object { $processName = (Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue).ProcessName; Write-Output "$($_.LocalAddress)|$($_.LocalPort)|$($_.OwningProcess)|$processName" }'; - const listeners = yield* processRunner - .run({ - command: "powershell.exe", - args: ["-NoProfile", "-NonInteractive", "-Command", command], + const runNetstat = (protocol: "tcp" | "tcpv6") => + processRunner.run({ + command: "netstat.exe", + args: ["-ano", "-p", protocol], timeout: Duration.millis(WINDOWS_LISTENER_TIMEOUT_MS), - maxOutputBytes: 1024 * 1024, - }) - .pipe( - Effect.map((result) => parseWindowsListenerOutput(result.stdout, terminalByProcessId)), - Effect.catchTags({ - ProcessSpawnError: recoverWindowsProbeFailure, - ProcessStdinError: recoverWindowsProbeFailure, - ProcessOutputLimitError: recoverWindowsProbeFailure, - ProcessReadError: recoverWindowsProbeFailure, - ProcessTimeoutError: recoverWindowsProbeFailure, - }), - ); - if (listeners !== null) return yield* probeWebServers(listeners, configuredUrls); - return yield* probeWebServers([], configuredUrls); + maxOutputBytes: WINDOWS_NETSTAT_MAX_OUTPUT_BYTES, + }); + const listeners = yield* Effect.all([runNetstat("tcp"), runNetstat("tcpv6")], { + concurrency: 2, + }).pipe( + // One failed query leaves a partial snapshot that could hide another process sharing a + // port across IPv4/IPv6, so fall back to configured URLs instead. + Effect.map(([tcp4, tcp6]) => + exitedWithError(tcp4) || exitedWithError(tcp6) + ? null + : parseWindowsListenerOutput(`${tcp4.stdout}\n${tcp6.stdout}`, terminalByProcessId), + ), + Effect.catchTags({ + ProcessSpawnError: recoverWindowsProbeFailure, + ProcessStdinError: recoverWindowsProbeFailure, + ProcessOutputLimitError: recoverWindowsProbeFailure, + ProcessReadError: recoverWindowsProbeFailure, + ProcessTimeoutError: recoverWindowsProbeFailure, + }), + ); + return yield* withWindowsProcessNames( + yield* probeWebServers(listeners ?? [], configuredUrls), + ); } const recoverLsofProbeFailure = recoverProcessProbeFailure("lsof"); if (yield* Ref.get(lsofMissingRef)) { diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index 2cec3411d5752..65425179c197b 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -595,8 +595,8 @@ function transcriptIdentity(filePath: string, stats: FileSystem.File.Info) { filePath, size: Number(stats.size), mtimeMs: Option.match(stats.mtime, { onNone: () => null, onSome: (date) => date.getTime() }), - device: stats.dev, - inode: Option.getOrNull(stats.ino), + device: Number(stats.dev), + inode: Option.match(stats.ino, { onNone: () => null, onSome: Number }), birthtimeMs: Option.match(stats.birthtime, { onNone: () => null, onSome: (date) => date.getTime(), @@ -674,12 +674,7 @@ export const make = Effect.gen(function* () { ) { const resolved = path.resolve(target); const stats = knownStats === undefined ? yield* statOption(resolved) : Option.some(knownStats); - if ( - Option.isSome(stats) && - Option.isSome(stats.value.ino) && - Number.isSafeInteger(stats.value.ino.value) && - stats.value.ino.value > 0 - ) { + if (Option.isSome(stats) && Option.isSome(stats.value.ino) && stats.value.ino.value > 0n) { return `inode:${stats.value.dev}:${stats.value.ino.value}`; } const realPath = yield* fileSystem diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index e99c2f684954a..2f572d1d4e9cf 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -16,6 +16,7 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientResponse } from "effect/http"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; @@ -127,6 +128,7 @@ interface HarnessOptions { readonly contentLength?: number; readonly contentEncoding?: string; readonly platform?: NodeJS.Platform; + readonly arch?: NodeJS.Architecture; readonly path?: string; readonly previous?: boolean; readonly fileSystem?: FileSystem.FileSystem; @@ -142,10 +144,11 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( const baseDir = options.baseDir ?? (yield* fs.makeTempDirectoryScoped({ prefix: "t3-agy-test-" })); const platform = options.platform ?? hostPlatform; + const arch = options.arch ?? "x64"; const archive = options.archive ?? completeArchive; const asset = options.asset === undefined ? yield* releaseAsset(archive, platform) : options.asset; - const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-x64`); + const managedDirectory = path.join(baseDir, "tools", "antigravity-acp", `${platform}-${arch}`); if (options.previous) { yield* writeRelease(managedDirectory, { ...(yield* releaseAsset(archive, platform)), @@ -185,7 +188,7 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( }).pipe( Effect.provideService(FileSystem.FileSystem, trackedFs), Effect.provideService(HostProcess.Platform, platform), - Effect.provideService(HostProcess.Architecture, "x64"), + Effect.provideService(HostProcess.Architecture, arch), Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }), Effect.provideService( HttpClient.HttpClient, @@ -305,38 +308,76 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { }), ); - it.effect.each([ - { - name: "the expected release with protocol 1", - protocolVersion: 1, - agentName: "antigravity-acp", - version: "fixture-new", - valid: true, - }, - { - name: "the expected release with protocol 2 and legacy fields", - protocolVersion: 2, - agentName: "antigravity-acp", - version: "fixture-new", - valid: true, - }, - { - name: "an unsupported protocol version", - protocolVersion: 3, - agentName: "antigravity-acp", - version: "fixture-new", - valid: false, - }, - { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false }, - { - name: "a different version", - agentName: "antigravity-acp", - version: "other-version", - valid: false, - }, - ])("validates $name with initialize only and removes the disposable profile", (testCase) => + it.effect.each( + [ + { + name: "the expected release with protocol 1", + protocolVersion: 1, + agentName: "antigravity-acp", + version: "fixture-new", + valid: true, + }, + { + name: "the expected release with protocol 2 and legacy fields", + protocolVersion: 2, + agentName: "antigravity-acp", + version: "fixture-new", + valid: true, + }, + { + name: "an unsupported protocol version", + protocolVersion: 3, + agentName: "antigravity-acp", + version: "fixture-new", + valid: false, + }, + { name: "a different agent", agentName: "other-agent", version: "fixture-new", valid: false }, + { + name: "a different version", + agentName: "antigravity-acp", + version: "other-version", + valid: false, + }, + { + name: "the Windows ARM release with locked child processes", + platform: "win32" as const, + arch: "arm64" as const, + agentName: "antigravity-acp", + version: "fixture-new", + valid: true, + }, + { + name: "an invalid Windows ARM release with locked child processes", + platform: "win32" as const, + arch: "arm64" as const, + agentName: "antigravity-acp", + version: "other-version", + valid: false, + }, + { + name: "a cancelled Windows ARM verification with locked child processes", + platform: "win32" as const, + arch: "arm64" as const, + agentName: "antigravity-acp", + version: "fixture-new", + cancel: true, + valid: false, + }, + ].flatMap((testCase) => { + const cleanupErrorTags = + testCase.platform === "win32" + ? (["Unknown", "PermissionDenied", "Busy"] as const) + : (["Unknown"] as const); + return cleanupErrorTags.map((cleanupErrorTag) => ({ + ...testCase, + cleanupErrorTag, + name: `${cleanupErrorTag}: ${testCase.name}`, + })); + }), + )("validates $name with initialize only and removes the disposable profile", (testCase) => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; + const platform = testCase.platform ?? hostPlatform; const encoder = new TextEncoder(); const decodeRequest = Schema.decodeUnknownEffect( Schema.fromJsonString( @@ -348,6 +389,10 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { ); const methods: string[] = []; const profiles = new Set(); + const cleanupRetryStarted = yield* Deferred.make(); + const initializationStarted = yield* Deferred.make(); + let childProcessesRunning = false; + let profileRemovalAttempts = 0; let closedRuntimes = 0; const spawner = ChildProcessSpawner.make( Effect.fn("test.spawnAntigravityValidator")(function* (command) { @@ -358,8 +403,16 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { if (!profile) return yield* Effect.die("Expected a disposable validation profile."); profiles.add(profile); const helper = command.args[0] === "-e"; + if (!helper) childProcessesRunning = true; // The runtime unpacks straight into the disposable profile. - if (!helper) expect(command.options.env?.TMPDIR).toBe(profile); + if (!helper) { + if (platform === "win32") { + expect(command.options.env?.TEMP).toBe(profile); + expect(command.options.env?.TMP).toBe(profile); + } else { + expect(command.options.env?.TMPDIR).toBe(profile); + } + } const output = yield* Queue.unbounded(); const exited = yield* Deferred.make(); const terminate = Deferred.succeed(exited, ChildProcessSpawner.ExitCode(0)).pipe( @@ -381,7 +434,10 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { ? Effect.succeed(ChildProcessSpawner.ExitCode(0)) : Deferred.await(exited), isRunning: Deferred.isDone(exited).pipe(Effect.map((done) => !done)), - kill: () => terminate, + kill: () => + Effect.sync(() => { + if (!helper) childProcessesRunning = false; + }).pipe(Effect.andThen(terminate)), unref: Effect.succeed(Effect.void), stdin: Sink.forEach((bytes: Uint8Array) => Effect.gen(function* () { @@ -389,6 +445,10 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { Effect.orDie, ); methods.push(request.method); + if (testCase.cancel) { + yield* Deferred.succeed(initializationStarted, undefined); + return; + } yield* Queue.offer( output, encoder.encode( @@ -431,15 +491,59 @@ it.layer(NodeServices.layer)("Antigravity installation", (it) => { const { installation, stagingReleased } = yield* makeHarness({ previous: true, useDefaultValidation: true, + platform, + ...(testCase.arch ? { arch: testCase.arch } : {}), + archive: + platform === "win32" ? Buffer.from(zipFixtures.windows, "base64") : completeArchive, + fileSystem: FileSystem.FileSystem.of({ + ...fs, + remove: (target, options) => + Effect.suspend(() => { + if (platform === "win32" && profiles.has(target)) { + profileRemovalAttempts += 1; + expect(childProcessesRunning).toBe(false); + // Even after the tree exits, Windows can briefly retain a DLL handle. + if (profileRemovalAttempts === 1) { + return Deferred.succeed(cleanupRetryStarted, undefined).pipe( + Effect.andThen( + Effect.fail( + PlatformError.systemError({ + _tag: testCase.cleanupErrorTag, + module: "FileSystem", + method: "remove", + description: "Unpacked DLL is in use", + }), + ), + ), + ); + } + } + return fs.remove(target, options); + }), + }), }).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)); - yield* installation.start; + const started = yield* installation.start; + const cancellation = testCase.cancel + ? yield* Deferred.await(initializationStarted).pipe( + Effect.andThen(installation.cancel(started.operationId!)), + Effect.forkChild, + ) + : undefined; + if (platform === "win32") { + yield* Effect.raceFirst( + Deferred.await(cleanupRetryStarted).pipe(Effect.andThen(TestClock.adjust("100 millis"))), + terminalState(installation), + ); + } + if (cancellation) yield* Fiber.join(cancellation); expect((yield* terminalState(installation)).phase).toBe( - testCase.valid ? "succeeded" : "failed", + testCase.cancel ? "cancelled" : testCase.valid ? "succeeded" : "failed", ); yield* Deferred.await(stagingReleased); expect(methods).toEqual(["initialize"]); expect(closedRuntimes).toBe(1); expect(profiles.size).toBe(1); + if (platform === "win32") expect(profileRemovalAttempts).toBe(2); for (const profile of profiles) { expect(yield* fs.exists(profile)).toBe(false); } diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index b985f0f2b0442..b73d26a906530 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -15,6 +15,7 @@ import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; +import * as Schedule from "effect/Schedule"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -349,9 +350,23 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma options.validate ?? Effect.fn("AntigravityInstallation.validate")( function* (executable: AntigravityExecutable, expectedVersion: string) { - const profileDirectory = yield* fs.makeTempDirectoryScoped({ - prefix: "t3-antigravity-validate-", - }); + const validationScope = yield* Effect.scope; + const profileDirectory = yield* Effect.acquireRelease( + fs.makeTempDirectory({ prefix: "t3-antigravity-validate-" }), + (directory) => + fs.remove(directory, { recursive: true, force: true }).pipe( + // Windows may retain DLL handles briefly after taskkill returns. + Effect.retry({ + times: platform === "win32" ? 10 : 0, + schedule: Schedule.spaced("100 millis"), + while: (error) => + error.reason._tag === "PermissionDenied" || + error.reason._tag === "Busy" || + error.reason._tag === "Unknown", + }), + Effect.orDie, + ), + ); const profile = yield* prepareAntigravityProfile({ profileDirectory, platform, @@ -368,7 +383,22 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma baseEnv: environment, }), cwd: profileDirectory, - childProcessSpawner: spawner, + childProcessSpawner: + platform === "win32" + ? ChildProcessSpawner.make( + Effect.fnUntraced(function* (command) { + const child = yield* spawner.spawn(command); + // Stop PyInstaller's tree before ACP closes its pipes. Once + // the launcher exits, taskkill cannot reach its children, + // which keep the executable and unpacked DLLs locked. + yield* Scope.addFinalizer( + validationScope, + child.kill({ forceKillAfter: "1 second" }).pipe(Effect.orDie), + ); + return child; + }), + ) + : spawner, clientInfo: { name: "t3-code", version: "0.0.0" }, }); const initialized = yield* runtime.initialize(); diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index abc67ad55ea18..045d005f87b37 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -2,16 +2,23 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import * as ModelManifest from "./ModelManifest.ts"; import { expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Clock from "effect/Clock"; import * as Crypto from "effect/Crypto"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Hex from "effect/encoding/Hex"; import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; +import * as Path from "effect/Path"; +import * as PlatformError from "effect/PlatformError"; import * as Exit from "effect/Exit"; +import * as Queue from "effect/Queue"; import * as Scope from "effect/Scope"; +import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import { HttpClient, HttpClientResponse } from "effect/http"; +import * as TestClock from "effect/testing/TestClock"; +import { ChildProcessSpawner } from "effect/process"; import * as CodexInstallation from "./CodexInstallation.ts"; const archive = Buffer.from( @@ -31,6 +38,10 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( body?: Stream.Stream; baseDir?: string; local?: { version: string; appServerFails?: boolean; versionFails?: boolean }; + platform?: NodeJS.Platform; + spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; + // Fails this many renames of an extracted runtime before letting one through. + runtimeRenameFailures?: number; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -50,6 +61,30 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( let downloads = 0; const crypto = yield* Crypto.Crypto; const sha256 = Hex.encode(yield* crypto.digest("SHA-256", archive).pipe(Effect.orDie)); + let runtimeRenameFailures = input.runtimeRenameFailures ?? 0; + const failedRenames = yield* Queue.unbounded(); + const lockingFs: FileSystem.FileSystem = { + ...fs, + // Suspended so each retry of the same effect is a fresh attempt, like the real rename. + rename: (from, to) => + Effect.suspend(() => + /[/\\]runtime$/u.test(from) && runtimeRenameFailures-- > 0 + ? Queue.offer(failedRenames, undefined).pipe( + Effect.andThen( + Effect.fail( + PlatformError.systemError({ + _tag: "PermissionDenied", + module: "FileSystem", + method: "rename", + pathOrDescriptor: from, + }), + ), + ), + ) + : fs.rename(from, to), + ), + }; + const spawner = input.spawner ?? (yield* ChildProcessSpawner.ChildProcessSpawner); const installation = yield* CodexInstallation.makeCodexInstallation({ baseDir, releaseAsset: { ...asset, sha256 }, @@ -62,9 +97,14 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), refreshInBackground: Effect.void, }), - Effect.provideService(HostProcess.Platform, "darwin"), + Effect.provideService(HostProcess.Platform, input.platform ?? "darwin"), Effect.provideService(HostProcess.Architecture, "arm64"), - Effect.provideService(HostProcess.Environment, { PATH: input.local ? localDirectory : "" }), + Effect.provideService(HostProcess.Environment, { + PATH: input.local ? localDirectory : "", + SystemRoot: "C:\\Windows", + }), + Effect.provideService(FileSystem.FileSystem, lockingFs), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService( HttpClient.HttpClient, HttpClient.make((request) => @@ -81,7 +121,15 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( ), ), ); - return { installation, fs, baseDir, localBinaryPath, probeLog, downloads: () => downloads }; + return { + installation, + fs, + baseDir, + localBinaryPath, + probeLog, + failedRenames, + downloads: () => downloads, + }; }); const terminalState = (installation: CodexInstallation.CodexInstallation["Service"]) => installation.changes.pipe( @@ -358,3 +406,112 @@ it("publishes complete packages for all supported platforms", () => { ); expect(CodexInstallation.resolveCodexReleaseAsset("linux", "riscv64")).toBeNull(); }); +// Live clock: staleness compares real filesystem mtimes. +it.live("startup removes only stale staging directories", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-codex-install-test-" }); + const managed = `${baseDir}/tools/codex`; + // utimes takes seconds when given numbers. + const stale = ((yield* Clock.currentTimeMillis) - 25 * 60 * 60_000) / 1000; + for (const name of [".install-stale", ".active-stale", ".install-live"]) { + yield* fs.makeDirectory(`${managed}/${name}`, { recursive: true }); + } + yield* fs.utimes(`${managed}/.install-stale`, stale, stale); + yield* fs.utimes(`${managed}/.active-stale`, stale, stale); + const h = yield* makeHarness({ baseDir }); + expect(yield* fs.readDirectory(managed)).toEqual([".install-live"]); + expect((yield* h.installation.state).canRemove).toBe(true); + + yield* fs.remove(`${managed}/.install-live`, { recursive: true }); + yield* fs.makeDirectory(`${managed}/.install-stale`); + yield* fs.utimes(`${managed}/.install-stale`, stale, stale); + const fresh = yield* makeHarness({ baseDir }); + expect(yield* fs.readDirectory(managed)).toEqual([]); + expect((yield* fresh.installation.state).canRemove).toBe(false); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); + +const processHandle = (stdout: string) => + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + unref: Effect.succeed(Effect.void), + stdin: Sink.drain, + stdout: Stream.make(new TextEncoder().encode(stdout)), + stderr: Stream.empty, + all: Stream.empty, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + }); +const windowsPackage: Record = { + "bin/codex.exe": "codex", + "bin/codex-code-mode-host.exe": "host", + "codex-path/rg.exe": "rg", + "codex-package.json": JSON.stringify({ + layoutVersion: 1, + version: asset.version, + target: asset.target, + entrypoint: "bin/codex.exe", + }), +}; +// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout. +const makeWindowsTar = (fs: FileSystem.FileSystem, commands: Array) => + ChildProcessSpawner.make((command) => + Effect.gen(function* () { + const { command: executable, args } = command as unknown as { + readonly command: string; + readonly args: ReadonlyArray; + }; + commands.push(executable); + const names = Object.keys(windowsPackage); + if (args[0] === "-tzf") return processHandle(`${names.join("\r\n")}\r\n`); + if (args[0] === "-tvzf") + return processHandle(`${names.map((name) => `-rwxr-xr-x 0 0 ${name}`).join("\r\n")}\r\n`); + const runtime = args[3] ?? ""; + for (const [name, contents] of Object.entries(windowsPackage)) { + yield* fs.makeDirectory(`${runtime}/${name.split("/").slice(0, -1).join("/")}`, { + recursive: true, + }); + yield* fs.writeFileString(`${runtime}/${name}`, contents); + } + return processHandle(""); + }).pipe(Effect.orDie), + ); + +it.effect("installs on Windows via System32 tar with CRLF output and a locked runtime", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const commands: Array = []; + const h = yield* makeHarness({ + platform: "win32", + spawner: makeWindowsTar(fs, commands), + runtimeRenameFailures: 3, + }); + yield* h.installation.start; + // Each failed attempt has scheduled its retry before the test fiber resumes. + for (let attempt = 0; attempt < 3; attempt++) { + yield* Queue.take(h.failedRenames); + yield* TestClock.adjust("100 millis"); + } + expect(yield* terminalState(h.installation)).toMatchObject({ phase: "succeeded" }); + expect(commands).toEqual([ + "C:\\Windows\\System32\\tar.exe", + "C:\\Windows\\System32\\tar.exe", + "C:\\Windows\\System32\\tar.exe", + ]); + const path = yield* Path.Path; + expect((yield* h.installation.resolve()).executablePath).toBe( + path.join(h.baseDir, "tools", "codex", "0.156.1", "bin", "codex.exe"), + ); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); +it.effect("does not retry a failed runtime rename outside Windows", () => + Effect.gen(function* () { + const h = yield* makeHarness({ runtimeRenameFailures: 1 }); + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("failed"); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 9bd746c608ae6..d7b62424c6d13 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -1,5 +1,6 @@ // @effect-diagnostics nodeBuiltinImport:off - Effect has no incremental digest. import { ProviderDriverKind, type ProviderInstallState } from "@t3tools/contracts"; +import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; import * as Clock from "effect/Clock"; @@ -13,6 +14,7 @@ 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 * as Schedule from "effect/Schedule"; import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; @@ -26,6 +28,7 @@ import * as ModelManifest from "./ModelManifest.ts"; import { resolveProviderCompatibility } from "./providerCompatibility.ts"; const DRIVER = ProviderDriverKind.make("codex"); +const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000; const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u)); const ActiveRelease = Schema.Struct({ version: Version }); const InstalledRelease = Schema.Struct({ @@ -512,8 +515,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function message: "Extracting Codex.", }) satisfies ProviderInstallState, ); - const entries = (yield* runCommand("tar", ["-tzf", archivePath])).trim().split("\n"); - const types = (yield* runCommand("tar", ["-tvzf", archivePath])).trim().split("\n"); + // Bare `tar` on Windows can resolve to Git's MSYS tar, which reads `C:\...` as a remote host. + const tarCommand = cliArchiveTarCommand(platform, environment); + const entries = (yield* runCommand(tarCommand, ["-tzf", archivePath])).trim().split(/\r?\n/u); + const types = (yield* runCommand(tarCommand, ["-tvzf", archivePath])).trim().split(/\r?\n/u); if ( entries.length > 10000 || entries.length !== types.length || @@ -529,7 +534,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }) ) return yield* installationError("extract", "The Codex archive contains unsafe entries."); - yield* runCommand("tar", ["-xzf", archivePath, "-C", runtime]); + yield* runCommand(tarCommand, ["-xzf", archivePath, "-C", runtime]); yield* SubscriptionRef.update( state, (current) => @@ -553,7 +558,12 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }), { flag: "wx", mode: 0o600 }, ); - yield* fs.rename(runtime, destination); + // On Windows, Defender and kernel process rundown can briefly hold the + // verified codex.exe handle open right after `--version` exits. + const renameRuntime = fs.rename(runtime, destination); + yield* platform === "win32" + ? renameRuntime.pipe(Effect.retry({ times: 10, schedule: Schedule.spaced("100 millis") })) + : renameRuntime; yield* activate(); }, Effect.scoped, @@ -692,7 +702,34 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); yield* Effect.gen(function* () { - const canRemove = yield* fs.exists(managedDirectory); + // Clear staging directories left behind by an interrupted install so they + // neither leak disk nor make an otherwise empty runtime look removable. Two + // servers can share a home, and writes below a staging directory do not + // refresh its mtime, so only directories far older than any real install + // (download is capped at 45 minutes) are treated as abandoned. + let canRemove = false; + if (yield* fs.exists(managedDirectory)) { + const entries = yield* fs + .readDirectory(managedDirectory) + .pipe(Effect.orElseSucceed((): ReadonlyArray => [])); + const now = yield* Clock.currentTimeMillis; + for (const entry of entries) { + if (!entry.startsWith(".install-") && !entry.startsWith(".active-")) continue; + const target = path.join(managedDirectory, entry); + const info = yield* fs.stat(target).pipe(Effect.option); + if (Option.isNone(info)) continue; + const modifiedAt = Option.match(info.value.mtime, { + onNone: () => now, + onSome: (date) => date.getTime(), + }); + if (now - modifiedAt < STAGING_STALE_AFTER_MS) continue; + yield* fs.remove(target, { recursive: true, force: true }).pipe(Effect.ignore); + } + // The empty root itself stays: deleting it could race another server + // creating a staging directory inside. An unreadable root stays removable. + const remaining = yield* fs.readDirectory(managedDirectory).pipe(Effect.option); + canRemove = Option.isNone(remaining) || remaining.value.length > 0; + } yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove })); if (yield* reuseLocal()) return; if (!(yield* fs.exists(activePath))) return; diff --git a/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts b/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts index 38969188dcd2d..4b8f3c38ac13f 100644 --- a/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts +++ b/apps/server/src/pullRequest/PullRequestProviderRateLimit.test.ts @@ -3,7 +3,8 @@ import { assert, it } from "@effect/vitest"; import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli"; import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; +import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; import { azureDevOpsProviderFailure } from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestProvider"; @@ -16,7 +17,7 @@ const cause = new Error("redacted provider failure"); it("classifies rate limits from every pull-request provider", () => { assert.deepStrictEqual( gitHubProviderFailure( - new GitHubApi.GitHubApiRateLimitError({ host: "github.com", operation: "execute" }), + new GitHubRequestPolicy.GitHubApiRateLimitError({ host: "github.com", operation: "execute" }), ), { reason: "rate-limited" }, ); diff --git a/apps/server/src/pullRequest/PullRequestService.test.ts b/apps/server/src/pullRequest/PullRequestService.test.ts index 7086597385421..b507848aa18e2 100644 --- a/apps/server/src/pullRequest/PullRequestService.test.ts +++ b/apps/server/src/pullRequest/PullRequestService.test.ts @@ -36,7 +36,7 @@ import * as SourceControlProviderRegistry from "../sourceControl/SourceControlPr import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit"; import * as ForgejoCli from "@t3tools/source-control-forgejo/server/ForgejoCli"; import * as ForgejoPullRequestProvider from "@t3tools/source-control-forgejo/server/ForgejoPullRequestProvider"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider"; @@ -1750,13 +1750,14 @@ it.effect("keeps branch deletion on the credential that passed source repository body = { data: { node: { + __typename: "Repository", defaultBranchRef: { name: "main" }, - ref: { target: { oid: "abc123" } }, + ref: { target: { __typename: "Commit", oid: "abc123" } }, }, }, }; } else if (operation.includes("updateRefs(")) { - body = { data: { updateRefs: {} } }; + body = { data: { updateRefs: { clientMutationId: null } } }; } else { activeToken = "account-b"; body = { @@ -1775,18 +1776,24 @@ it.effect("keeps branch deletion on the credential that passed source repository }, }; } - return HttpClientResponse.fromWeb(request, new Response(JSON.stringify(body))); + return HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify(body), { + headers: { "content-type": "application/json" }, + }), + ); }), ), ); const provider = yield* GitHubPullRequestProvider.make.pipe( Effect.provide( GitHubPullRequestApi.layer.pipe( + // GraphQL reads go over `http` too, through the same credential and quota as REST. Layer.provide( - GitHubApi.layer.pipe( - Layer.provide(Layer.mergeAll(credentials, http)), - Layer.provide(GitHubQuota.layer), - Layer.provide(SourceControlRateLimit.layer), + GitHubRest.layer.pipe( + Layer.provideMerge(Layer.mergeAll(credentials, http)), + Layer.provideMerge(GitHubQuota.layer), + Layer.provideMerge(SourceControlRateLimit.layer), ), ), Layer.provide(TestSourceControlHost.layer()), diff --git a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts index cc79c19571ea9..64661058d8583 100644 --- a/apps/server/src/sourceControl/SourceControlDiscovery.test.ts +++ b/apps/server/src/sourceControl/SourceControlDiscovery.test.ts @@ -21,7 +21,8 @@ import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/Azu import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsPullRequestCli"; import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; +import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; import * as GitLabPullRequestCli from "@t3tools/source-control-gitlab/server/GitLabPullRequestCli"; @@ -51,7 +52,13 @@ const layerSourceControlProviderRegistryTest = (input: { Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}), ServerSettings.ServerSettingsService.layerTest(), Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}), - Layer.mock(GitHubApi.GitHubApi)({}), + Layer.mock(GitHubRest.GitHubRest)({}), + // The GitHub provider's GraphQL reads go through these; no test here makes one. + Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))), + ), Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(GitLabCli.GitLabCli)({}), Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}), diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts index 2ff7fdb0d7020..117d8ff574fba 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.test.ts @@ -2,12 +2,24 @@ import { SourceControlProviderKind } from "@t3tools/contracts"; import { assert, it } from "@effect/vitest"; import * as NodeServices from "@effect/platform-node/NodeServices"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as PlatformError from "effect/PlatformError"; +import * as PubSub from "effect/PubSub"; import * as Redacted from "effect/Redacted"; +import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; +import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; -import { VcsRepositoryDetectionError } from "@t3tools/contracts"; +import { + DEFAULT_SERVER_SETTINGS, + VcsProcessSpawnError, + VcsProcessTimeoutError, + VcsRepositoryDetectionError, +} from "@t3tools/contracts"; import * as ServerSettings from "../serverSettings.ts"; import * as ServerConfig from "../config.ts"; @@ -19,7 +31,8 @@ import * as AzureDevOpsPullRequestCli from "@t3tools/source-control-azure-devops import * as BitbucketApi from "@t3tools/source-control-bitbucket/server/BitbucketApi"; import * as BitbucketPullRequestApi from "@t3tools/source-control-bitbucket/server/BitbucketPullRequestApi"; import * as GitVcsDriver from "../vcs/GitVcsDriver.ts"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; +import * as GitHubRequestPolicy from "@t3tools/source-control-github/server/GitHubRequestPolicy"; import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; import * as GitHubCredentials from "@t3tools/source-control-github/server/GitHubCredentials"; import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; @@ -52,8 +65,10 @@ function makeRegistry(input: { readonly url: string; }>; readonly process?: Partial; - readonly githubApi?: Partial; + readonly githubApi?: Partial; readonly gitlab?: Partial; + readonly forgejo?: Partial; + readonly settings?: Partial; readonly resolve?: VcsDriverRegistry.VcsDriverRegistry["Service"]["resolve"]; }) { const driver = { @@ -118,9 +133,17 @@ function makeRegistry(input: { Layer.mock(AzureDevOpsPullRequestCli.AzureDevOpsPullRequestCli)({}), Layer.mock(BitbucketApi.BitbucketApi)({}), Layer.mock(BitbucketPullRequestApi.BitbucketPullRequestApi)({}), - ServerSettings.ServerSettingsService.layerTest(), + input.settings + ? Layer.mock(ServerSettings.ServerSettingsService)(input.settings) + : ServerSettings.ServerSettingsService.layerTest(), Layer.mock(GitHubPullRequestApi.GitHubPullRequestApi)({}), - Layer.mock(GitHubApi.GitHubApi)({ + // The GitHub provider's GraphQL reads go through these; no test here makes one. + Layer.mock(GitHubRequestPolicy.GitHubRequestPolicy)({}), + Layer.succeed( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die(new Error("Unexpected GitHub GraphQL read"))), + ), + Layer.mock(GitHubRest.GitHubRest)({ // No GitHub credential unless a test supplies one, so custom hosts stay unclaimed. credential: (host) => Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })), ...input.githubApi, @@ -128,7 +151,10 @@ function makeRegistry(input: { Layer.mock(GitVcsDriver.GitVcsDriver)({}), Layer.mock(GitLabCli.GitLabCli)(input.gitlab ?? {}), Layer.mock(GitLabPullRequestCli.GitLabPullRequestCli)({}), - Layer.mock(ForgejoCli.ForgejoCli)({ listLogins: () => Effect.succeed([]) }), + Layer.mock(ForgejoCli.ForgejoCli)({ + listLogins: () => Effect.succeed([]), + ...input.forgejo, + }), Layer.mock(GitCafeApi.GitCafeApi)({}), Layer.mock(GitCafeCredentials.GitCafeCredentials)({ cliEnv: () => Effect.succeed({}), @@ -459,3 +485,150 @@ it.effect("skips GitHub discovery for the identity resolver's empty base URL", ( assert.deepStrictEqual(hosts, ["githubenterprise.dev.example.com"]); }), ); + +const notFound = (command: string, cwd: string) => + new VcsProcessSpawnError({ + operation: "test", + command, + cwd, + cause: PlatformError.systemError({ _tag: "NotFound", module: "ChildProcess", method: "spawn" }), + }); + +const resolveUnknown = ( + registry: SourceControlProviderRegistry.SourceControlProviderRegistry["Service"], + repository: string, +) => + registry.resolveHandle({ + cwd: `/${repository}`, + context: { + provider: { + kind: SourceControlProviderKind.make("unknown"), + name: "git.example.internal", + baseUrl: "https://git.example.internal", + }, + remoteName: "origin", + remoteUrl: `git@Git.Example.Internal:team/${repository}.git`, + }, + }); + +it.effect("asks once for every checkout of a server no integration claims", () => + Effect.gen(function* () { + const asked: Array = []; + const release = yield* Deferred.make(); + const registry = yield* makeRegistry({ + remotes: [], + process: { + run: ({ command, args, cwd }) => { + asked.push([command, ...args].join(" ")); + return Deferred.await(release).pipe(Effect.andThen(Effect.fail(notFound(command, cwd)))); + }, + }, + githubApi: { + credential: (host) => { + asked.push(`credential ${host}`); + return Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })); + }, + }, + forgejo: { + listLogins: ({ command = "tea", cwd }) => { + asked.push(command); + const cause = notFound(command, cwd); + return Effect.fail(new ForgejoCli.ForgejoCliError({ command, cwd, detail: "", cause })); + }, + }, + }); + + // Three checkouts read while the first probe is still running share it. + const started = yield* Effect.forEach(["a", "b", "c"], () => Deferred.make()); + const callers = yield* Effect.forEach( + ["a", "b", "c"], + (repository, index) => + Deferred.succeed(started[index]!, undefined).pipe( + Effect.andThen(resolveUnknown(registry, repository)), + ), + { concurrency: "unbounded" }, + ).pipe(Effect.forkChild); + yield* Effect.forEach(started, Deferred.await); + yield* Deferred.succeed(release, undefined); + const handles = yield* Fiber.join(callers); + yield* resolveUnknown(registry, "d"); + assert.deepStrictEqual( + handles.map((handle) => handle.provider.kind), + ["unknown", "unknown", "unknown"], + ); + const once = asked.slice(); + // glab is asked about the remote's host as the remote spells it. + assert.sameMembers(once, [ + "credential git.example.internal", + "glab auth status --hostname Git.Example.Internal", + "fj", + "tea", + ]); + + // A login made in a terminal sends no signal, so the server is asked again later. + yield* TestClock.adjust("5 minutes"); + yield* resolveUnknown(registry, "a"); + assert.deepStrictEqual(asked, [...once, ...once]); + }), +); + +it.effect("asks again after a check that could not answer", () => + Effect.gen(function* () { + let asks = 0; + const registry = yield* makeRegistry({ + remotes: [], + process: { + run: ({ command, cwd }) => { + asks += 1; + return Effect.fail( + new VcsProcessTimeoutError({ operation: "test", command, cwd, timeoutMs: 1 }), + ); + }, + }, + }); + yield* resolveUnknown(registry, "a"); + yield* resolveUnknown(registry, "b"); + assert.strictEqual(asks, 2); + }), +); + +it.effect("asks again once Settings change", () => + Effect.gen(function* () { + const changes = yield* PubSub.unbounded(); + const handled = yield* Deferred.make(); + let signedIn = false; + const registry = yield* makeRegistry({ + remotes: [], + settings: { + subscribeChanges: PubSub.subscribe(changes).pipe( + Effect.map((subscription) => + // A change is handled once the registry asks for the next one. + Stream.fromSubscription(subscription).pipe( + Stream.flatMap((settings) => + Stream.concat( + Stream.make(settings), + Stream.fromEffectDrain(Deferred.succeed(handled, undefined)), + ), + ), + ), + ), + ), + }, + process: { run: ({ command, cwd }) => Effect.fail(notFound(command, cwd)) }, + githubApi: { + credential: (host) => + signedIn + ? Effect.succeed({ token: Redacted.make("token"), fingerprint: `${host}:fingerprint` }) + : Effect.fail(new GitHubCredentials.GitHubNotSignedInError({ host })), + }, + }); + assert.strictEqual((yield* resolveUnknown(registry, "a")).provider.kind, "unknown"); + signedIn = true; + assert.strictEqual((yield* resolveUnknown(registry, "b")).provider.kind, "unknown"); + + // A token saved for the host in Settings. + yield* PubSub.publish(changes, DEFAULT_SERVER_SETTINGS); + yield* Deferred.await(handled); + assert.strictEqual((yield* resolveUnknown(registry, "c")).provider.kind, "github"); + }), +); diff --git a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts index 821e24bf7bc3e..fd306a986d104 100644 --- a/apps/server/src/sourceControl/SourceControlProviderRegistry.ts +++ b/apps/server/src/sourceControl/SourceControlProviderRegistry.ts @@ -3,8 +3,11 @@ import * as Cache from "effect/Cache"; import * as Context from "effect/Context"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Exit from "effect/Exit"; +import * as Hash from "effect/Hash"; import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; import { SourceControlProviderError, type SourceControlProviderDiscoveryItem, @@ -18,14 +21,19 @@ import { probeSourceControlProvider, refineUnknownRemoteProvider, type SourceControlProviderDiscoverySpec, + type UnknownRemoteVerdict, } from "@t3tools/source-control-core/server/discovery"; import * as SourceControlHost from "@t3tools/source-control-core/server/SourceControlHost"; import * as ServerConfig from "../config.ts"; +import * as ServerSettings from "../serverSettings.ts"; import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts"; const PROVIDER_DETECTION_CACHE_CAPACITY = 2_048; const PROVIDER_DETECTION_CACHE_TTL = Duration.seconds(5); +const UNKNOWN_REMOTE_CACHE_CAPACITY = 512; +// Outlasts the one-minute pull request sweep. A login made since is noticed after this. +const UNKNOWN_REMOTE_CACHE_TTL = Duration.minutes(5); export interface SourceControlProviderRegistration { readonly kind: SourceControlProviderKind; @@ -150,6 +158,38 @@ function selectProviderContext( ); } +/** + * One lookup per server: remotes that differ only in `owner/repo` share a verdict, and callers + * that arrive while it runs wait on it. `cwd` is left out because it only matters when a probe + * fails there, and a failed probe is not kept. Equality ignores `lookup`, so this is not a + * `Data.Class`. + */ +class UnknownRemoteLookup { + readonly key: string; + readonly lookup: Effect.Effect; + + constructor( + context: SourceControlProvider.SourceControlProviderContext, + lookup: Effect.Effect, + ) { + this.lookup = lookup; + this.key = [ + context.provider.name, + context.provider.baseUrl, + // Strip a trailing `owner/repo`, never the host after `//`, so one-segment remotes stay apart. + context.remoteUrl.trim().replace(/(?) { const config = yield* ServerConfig.ServerConfig; + const serverSettings = yield* ServerSettings.ServerSettingsService; const { process } = yield* SourceControlHost.SourceControlHost; const vcsRegistry = yield* VcsDriverRegistry.VcsDriverRegistry; const providers = new Map< @@ -209,6 +250,36 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit const get: SourceControlProviderRegistry["Service"]["get"] = (kind) => Effect.succeed(providers.get(kind) ?? unsupportedProvider(kind)); + // "No integration holds this host" is the common verdict and the one worth keeping. A verdict + // reached while some probe failed is handed to the callers waiting on it, then dropped. + const unknownRemoteCache = yield* Cache.makeWith( + (request: UnknownRemoteLookup) => request.lookup, + { + capacity: UNKNOWN_REMOTE_CACHE_CAPACITY, + timeToLive: (exit) => + Exit.isSuccess(exit) && exit.value.settled ? UNKNOWN_REMOTE_CACHE_TTL : Duration.zero, + }, + ); + // A token saved or a host toggled in Settings must show on the next read, not after the TTL. + const settingsChanges = yield* serverSettings.subscribeChanges; + yield* Stream.runForEach(settingsChanges, () => Cache.invalidateAll(unknownRemoteCache)).pipe( + Effect.forkScoped, + ); + + const refineContext = ( + cwd: string, + context: SourceControlProvider.SourceControlProviderContext | null, + ): Effect.Effect => + context === null || context.provider.kind !== "unknown" + ? Effect.succeed(context) + : Cache.get( + unknownRemoteCache, + new UnknownRemoteLookup( + context, + refineUnknownRemoteProvider({ specs: discoverySpecs, process, cwd, context }), + ), + ).pipe(Effect.map(({ provider }) => (provider ? { ...context, provider } : context))); + const detectProviderContext = Effect.fn("SourceControlProviderRegistry.detectProviderContext")( function* (cwd: string) { const handle = yield* vcsRegistry.resolve({ cwd }).pipe( @@ -235,14 +306,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit }), ), ); - const context = selectProviderContext(remotes.remotes); - - return yield* refineUnknownRemoteProvider({ - specs: discoverySpecs, - process, - cwd, - context, - }); + return yield* refineContext(cwd, selectProviderContext(remotes.remotes)); }, ); @@ -258,12 +322,7 @@ export const makeWithProviders = Effect.fn("makeSourceControlProviderRegistryWit const resolveHandle: SourceControlProviderRegistry["Service"]["resolveHandle"] = (input) => (input.context === undefined ? Cache.get(providerContextCache, input.cwd) - : refineUnknownRemoteProvider({ - specs: discoverySpecs, - process, - cwd: input.cwd, - context: input.context, - }) + : refineContext(input.cwd, input.context) ).pipe( Effect.map((context) => { const kind = context?.provider.kind ?? SourceControlProviderKind.make("unknown"); diff --git a/apps/server/src/sourceControl/builtInDrivers.ts b/apps/server/src/sourceControl/builtInDrivers.ts index 1b891ce9259aa..5bd63ca8da573 100644 --- a/apps/server/src/sourceControl/builtInDrivers.ts +++ b/apps/server/src/sourceControl/builtInDrivers.ts @@ -18,7 +18,7 @@ import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeApi from "@t3tools/source-control-gitcafe/server/GitCafeApi"; import * as GitCafeCredentials from "@t3tools/source-control-gitcafe/server/GitCafeCredentials"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; import * as GitLabCli from "@t3tools/source-control-gitlab/server/GitLabCli"; @@ -49,9 +49,9 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVERS: ReadonlyArray< /** The services the built-in drivers' packages own, plus the host port they all run against. */ export const layer = Layer.mergeAll( - // `GitHubApi.layerWithDependencies` carries the quota reserve and rate-limit pause every GitHub + // `GitHubRest.layerWithDependencies` carries the quota reserve and rate-limit pause every GitHub // reader shares, so the server builds it once, here. - GitHubPullRequestApi.layer.pipe(Layer.provideMerge(GitHubApi.layerWithDependencies)), + GitHubPullRequestApi.layer.pipe(Layer.provideMerge(GitHubRest.layerWithDependencies)), AzureDevOpsPullRequestCli.layer.pipe(Layer.provideMerge(AzureDevOpsCli.layer)), BitbucketPullRequestApi.layer.pipe(Layer.provideMerge(BitbucketApi.layer)), ForgejoCli.layer, diff --git a/apps/server/src/sourceControl/githubStackRebase.test.ts b/apps/server/src/sourceControl/githubStackRebase.test.ts index 613c0016c65fd..921d499ff0b0e 100644 --- a/apps/server/src/sourceControl/githubStackRebase.test.ts +++ b/apps/server/src/sourceControl/githubStackRebase.test.ts @@ -5,7 +5,7 @@ import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Redacted from "effect/Redacted"; -import * as GitHubApi from "@t3tools/source-control-github/server/GitHubApi"; +import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest"; import { cascadeRebaseStack } from "@t3tools/source-control-github/server/githubStackRebase"; import * as ServerSettings from "../serverSettings.ts"; @@ -15,7 +15,7 @@ import * as VcsProcess from "../vcs/VcsProcess.ts"; import * as ServerSourceControlHost from "./ServerSourceControlHost.ts"; const layer = Layer.mergeAll( - Layer.mock(GitHubApi.GitHubApi)({ + Layer.mock(GitHubRest.GitHubRest)({ credential: () => Effect.succeed({ token: Redacted.make("token"), fingerprint: "fp" }), }), // The cascade runs real git through the server's host; the git driver itself is never asked. diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts new file mode 100644 index 0000000000000..973bf2939055e --- /dev/null +++ b/apps/server/src/workspace/WorkspaceSearchIndex.native.test.ts @@ -0,0 +1,115 @@ +import * as NodeModule from "node:module"; +import type { Result } from "@ff-labs/fff-node"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; + +// Use the same require export as WorkspaceSearchIndex, with the actual native library. +const requireForFff = NodeModule.createRequire(import.meta.url); +const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node"); + +function valueOf(result: Result): T { + if (!result.ok) throw new Error(result.error); + return result.value; +} + +it.effect("decodes native search and grep strings and keeps scores only through 200 results", () => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const basePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-fff-native-" }); + const names = [ + ...Array.from({ length: 205 }, (_, index) => `file-${String(index).padStart(3, "0")}`), + "日本語", + "café", + "emoji-🦊", + ]; + const relativePaths = names.map((name) => `${name}/${name}.ts`); + const content = "prefix marker-日本語🦊\n"; + yield* Effect.forEach( + names, + (name) => + Effect.gen(function* () { + yield* fileSystem.makeDirectory(path.join(basePath, name)); + yield* fileSystem.writeFileString(path.join(basePath, name, `${name}.ts`), content); + }), + { concurrency: "unbounded" }, + ); + expect(requireForFff.resolve("@ff-labs/fff-node").replaceAll("\\", "/")).toMatch( + /\/dist\/index\.js$/u, + ); + const finder = yield* Effect.acquireRelease( + Effect.sync(() => + valueOf(FileFinder.create({ basePath, disableWatch: true, disableMmapCache: true })), + ), + (finder) => Effect.sync(() => finder.destroy()), + ); + expect(valueOf(yield* Effect.promise(() => finder.waitForIndexReady(10_000)))).toBe(true); + + const files200 = valueOf(finder.fileSearch("", { pageSize: 200 })); + const files201 = valueOf(finder.fileSearch("", { pageSize: 201 })); + expect(files200.items).toHaveLength(200); + expect(files200.scores).toHaveLength(200); + expect(files201.items).toHaveLength(201); + expect(files201.scores).toEqual([]); + expect(files201.items.slice(0, 200)).toEqual(files200.items); + const files = valueOf(finder.fileSearch("", { pageSize: 1000 })); + expect(files.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual( + relativePaths.toSorted(), + ); + for (const item of files.items) { + expect(item.fileName.normalize("NFC")).toBe( + path.basename(item.relativePath).normalize("NFC"), + ); + expect(item.size).toBe(Buffer.byteLength(content)); + expect(Number.isFinite(item.modified)).toBe(true); + } + const exact = valueOf(finder.fileSearch("日本語.ts", { pageSize: 1 })); + expect(exact.items[0]?.fileName.normalize("NFC")).toBe("日本語.ts"); + expect(exact.scores[0]).toMatchObject({ exactMatch: true, matchType: "exact_filename" }); + + const dirs200 = valueOf(finder.directorySearch("", { pageSize: 200 })); + const dirs201 = valueOf(finder.directorySearch("", { pageSize: 201 })); + expect(dirs200.scores).toHaveLength(200); + expect(dirs201.items).toHaveLength(201); + expect(dirs201.scores).toEqual([]); + expect(dirs201.items.slice(0, 200)).toEqual(dirs200.items); + const directories = valueOf(finder.directorySearch("", { pageSize: 1000 })); + expect( + directories.items + .map((item) => item.relativePath.normalize("NFC")) + .filter(Boolean) + .toSorted(), + ).toEqual(names.map((name) => `${name}/`).toSorted()); + + const mixed200 = valueOf(finder.mixedSearch("", { pageSize: 200 })); + const mixed201 = valueOf(finder.mixedSearch("", { pageSize: 201 })); + expect(mixed200.scores).toHaveLength(200); + expect(mixed201.items).toHaveLength(201); + expect(mixed201.scores).toEqual([]); + expect(mixed201.items.slice(0, 200)).toEqual(mixed200.items); + const mixed = valueOf(finder.mixedSearch("", { pageSize: 1000 })); + expect(mixed.items.filter((item) => item.type === "file").map(({ item }) => item)).toEqual( + files.items, + ); + expect(mixed.items.filter((item) => item.type === "directory").map(({ item }) => item)).toEqual( + directories.items, + ); + + const grep = valueOf(finder.grep("marker", { mode: "plain", pageSize: 1000 })); + expect(grep.items.map((item) => item.relativePath.normalize("NFC")).toSorted()).toEqual( + relativePaths.toSorted(), + ); + for (const item of grep.items) { + expect(item.fileName.normalize("NFC")).toBe( + path.basename(item.relativePath).normalize("NFC"), + ); + expect(item.lineContent).toBe(content.trimEnd()); + expect(item.lineNumber).toBe(1); + expect(item.col).toBe(7); + expect(item.matchRanges).toEqual([[7, 13]]); + } + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), +); diff --git a/apps/web/index.html b/apps/web/index.html index c2d164742402c..bd4a3d6d5f8ac 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -477,7 +477,7 @@ cursor: pointer; } - T3 Code (Alpha) + T3 Code (Beta)
diff --git a/apps/web/src/branding.ts b/apps/web/src/branding.ts index 7fc57cf0d03fe..528609d36e608 100644 --- a/apps/web/src/branding.ts +++ b/apps/web/src/branding.ts @@ -20,7 +20,7 @@ export const APP_BASE_NAME = injectedDesktopAppBranding?.baseName ?? "T3 Code"; export const APP_STAGE_LABEL = injectedDesktopAppBranding?.stageLabel ?? HOSTED_APP_CHANNEL_LABEL ?? - (import.meta.env.DEV ? "Dev" : "Alpha"); + (import.meta.env.DEV ? "Dev" : "Beta"); export const APP_DISPLAY_NAME = injectedDesktopAppBranding?.displayName ?? formatAppDisplayName({ baseName: APP_BASE_NAME, stageLabel: APP_STAGE_LABEL }); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index de314137fb9ed..e020f5183f52f 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -200,7 +200,10 @@ import { type TerminalContextSelection, } from "../../lib/terminalContext"; import { useComposerPathSearch } from "../../lib/composerPathSearchState"; -import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { + replaceComposerContextReferences, + toKindScopedComposerContextId, +} from "@t3tools/shared/composerContextReferences"; import { getRestingComposerImagePreviewCounts, resolveRestingComposerControlsLayout, @@ -229,7 +232,6 @@ import { formatInlineContextReference, insertInlineContextReference, inlineContextReferenceReplacement, - toKindScopedComposerContextId, } from "~/lib/composerContextReferences"; import { asKnownContextRecord, diff --git a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx b/apps/web/src/components/chat/HtmlRenderDialog.test.tsx index fbf0b4b536c0e..9cd22832f0e4c 100644 --- a/apps/web/src/components/chat/HtmlRenderDialog.test.tsx +++ b/apps/web/src/components/chat/HtmlRenderDialog.test.tsx @@ -10,7 +10,8 @@ import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { HtmlRenderDialog } from "./HtmlRenderDialog"; import { HtmlRenderFrame } from "./HtmlRenderFrame"; -const { refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({ +const { cachedUrl, refresh, showError, openLink, openChangeRequestLink } = vi.hoisted(() => ({ + cachedUrl: { lifeMs: 60 * 60_000 }, refresh: vi.fn(), showError: vi.fn(), openLink: vi.fn(), @@ -24,7 +25,7 @@ vi.mock("~/assets/assetUrls", () => ({ useAssetUrlState: () => ({ _tag: "Success", url: "https://environment.test/original.html", - expiresAt: Date.now() + 60 * 60_000, + expiresAt: Date.now() + cachedUrl.lifeMs, }), useAssetUrlRefresh: () => refresh, })); @@ -50,6 +51,7 @@ beforeEach(async () => { }, ); refresh.mockReset(); + cachedUrl.lifeMs = 60 * 60_000; openLink.mockReset().mockResolvedValue(undefined); openChangeRequestLink.mockReset().mockReturnValue(false); showError.mockClear(); @@ -109,7 +111,8 @@ it("closes with the close button or Escape", async () => { }); async function renderInline() { - await act(() => + // Async so a URL minted at mount lands inside act. + await act(async () => root.render( { +it("offers only full screen and opens with the inline URL while keeping the inline page loaded", async () => { await renderInline(); expect(document.querySelector('[aria-label="Open in panel"]')).toBeNull(); const inlineFrame = document.querySelector("iframe")!; @@ -132,11 +135,10 @@ it("offers only full screen and opens with a fresh URL while keeping the inline '[aria-label="Open full screen"]', )!; expandButton.focus(); - refresh.mockResolvedValue("https://environment.test/renewed.html"); await click("Open full screen"); - expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).not.toHaveBeenCalled(); expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain( - "https://environment.test/renewed.html#", + "https://environment.test/original.html#", ); expect(inlineFrame.src).toBe(originalSrc); await click("Close"); @@ -145,9 +147,26 @@ it("offers only full screen and opens with a fresh URL while keeping the inline expect(document.activeElement).toBe(expandButton); }); -it("routes links from the expanded page through its thread", async () => { +// An inline URL near expiry is minted at mount, and full screen mints another. +async function renderInlineNearExpiry() { + cachedUrl.lifeMs = 60_000; + refresh.mockResolvedValueOnce("https://environment.test/inline.html"); await renderInline(); + expect(refresh).toHaveBeenCalledOnce(); +} + +it("opens full screen with a fresh URL when the inline one is near expiry", async () => { + await renderInlineNearExpiry(); refresh.mockResolvedValue("https://environment.test/renewed.html"); + await click("Open full screen"); + expect(refresh).toHaveBeenCalledTimes(2); + expect(document.querySelector('[role="dialog"] iframe')?.getAttribute("src")).toContain( + "https://environment.test/renewed.html#", + ); +}); + +it("routes links from the expanded page through its thread", async () => { + await renderInline(); openChangeRequestLink.mockReturnValue(true); await click("Open full screen"); const frame = document.querySelector('[role="dialog"] iframe')!; @@ -173,7 +192,7 @@ it("routes links from the expanded page through its thread", async () => { it.each([null, new Error("Disconnected")])( "reports an unavailable URL instead of opening a blank page: %s", async (failure) => { - await renderInline(); + await renderInlineNearExpiry(); if (failure === null) refresh.mockResolvedValue(null); else refresh.mockRejectedValue(failure); await click("Open full screen"); diff --git a/apps/web/src/components/chat/HtmlRenderFrame.tsx b/apps/web/src/components/chat/HtmlRenderFrame.tsx index 5133c0ea55cd5..4112cc9ebfe64 100644 --- a/apps/web/src/components/chat/HtmlRenderFrame.tsx +++ b/apps/web/src/components/chat/HtmlRenderFrame.tsx @@ -3,15 +3,19 @@ import { HTML_RENDER_COLUMN_WIDTH, htmlRenderFileName, htmlRenderFrameHeight, + htmlRenderOutlineBoxes, + type HtmlRenderOutlineBox, type HtmlRenderReference, } from "@t3tools/shared/htmlRender"; import { Maximize2Icon } from "lucide-react"; -import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useAssetUrlRefresh, useAssetUrlState } from "~/assets/assetUrls"; +import { cn } from "~/lib/utils"; import { HtmlRenderDocument } from "../files/BrowserDocumentFrame"; import { Button } from "../ui/button"; +import { Skeleton } from "../ui/skeleton"; import { toastManager } from "../ui/toast"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; import { HtmlRenderDialog } from "./HtmlRenderDialog"; @@ -64,7 +68,17 @@ export function HtmlRenderFrame(props: { // page again; one near expiry is minted afresh, since a frame cannot report a // failed load. The page keeps its first URL for its lifetime. const [src, setSrc] = useState(null); + // Full screen reuses the inline URL while it has life left, so the page + // comes from the browser's cache instead of a new mint and download. + const srcExpiresAt = useRef(0); const [expandedSrc, setExpandedSrc] = useState(null); + // The page stays hidden behind a skeleton until it reports its content. + const [ready, setReady] = useState(false); + const showPage = useCallback(() => setReady(true), []); + const fitPage = useCallback((contentHeight: number) => { + setContentHeight(contentHeight); + setReady(true); + }, []); const { onFullscreenChange } = props; useEffect(() => { if (expandedSrc === null) return; @@ -89,6 +103,7 @@ export function HtmlRenderFrame(props: { } if (cachedUrl === null) return; if (cachedExpiresAt - Date.now() > MIN_URL_LIFE_MS) { + srcExpiresAt.current = cachedExpiresAt; setSrc(cachedUrl); return; } @@ -101,14 +116,26 @@ export function HtmlRenderFrame(props: { return (
+ {!ready && !failed ? ( + + ) : null} {src !== null ? ( <>
@@ -119,7 +146,10 @@ export function HtmlRenderFrame(props: { size="icon-xs" variant="glass" onClick={async () => { - const url = await refresh().catch(() => null); + const url = + srcExpiresAt.current - Date.now() > MIN_URL_LIFE_MS + ? src + : await refresh().catch(() => null); if (url !== null) setExpandedSrc(url); else toastManager.add({ @@ -153,3 +183,79 @@ export function HtmlRenderFrame(props: {
); } + +// Without an outline: one heading, a line of text, and a chart-sized block, +// the shape most pages take, repeated to fill the frame's reserved height. +const SKELETON_SECTION_HEIGHT = 264; + +const OUTLINE_BOX_CLASS = { + media: "rounded-lg bg-muted-foreground/15", + text: "", + table: "", +} as const; + +const OUTLINE_BAR = "color-mix(in srgb, var(--color-muted-foreground) 15%, transparent)"; + +// Text lines and table rows are bars painted by one gradient per box, so a +// long page costs one element per block rather than one per line. +function outlineBoxStyle(box: HtmlRenderOutlineBox): React.CSSProperties { + const style: React.CSSProperties = { + left: box.x, + top: box.y, + width: box.width, + height: box.height, + }; + if (box.kind !== "text" && box.kind !== "table") return style; + const step = box.height / box.lines; + const bar = Math.min(box.kind === "table" ? 12 : 10, step * 0.6); + const start = (step - bar) / 2; + return { + ...style, + backgroundImage: `repeating-linear-gradient(to bottom, transparent 0 ${start}px, ${OUTLINE_BAR} ${start}px ${start + bar}px, transparent ${start + bar}px ${step}px)`, + }; +} + +/** + * Holds the frame's place while the page loads: the page's own blocks when the + * server measured an outline, else a generic page shape. The outline pulses + * as one layer. + */ +function HtmlRenderSkeleton(props: { + readonly title: string; + readonly height: number; + readonly outline: ReadonlyArray; +}) { + if (props.outline.length > 0) { + return ( +
+ {props.outline.map((box) => ( +
+ ))} +
+ ); + } + const sections = Math.ceil(props.height / SKELETON_SECTION_HEIGHT); + return ( +
+ {Array.from({ length: sections }, (_, index) => ( +
+ + + +
+ ))} +
+ ); +} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 80c697d6fc8cd..c769f8f4e6129 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -1774,6 +1774,24 @@ function timelineMinimapEventTargetsPreview(target: EventTarget): boolean { return target instanceof Element && target.closest("[data-minimap-preview]") !== null; } +// Calls `onRelease` once no mouse button is held. A release outside the window +// can skip `mouseup`, so the next button-free `mousemove` also counts. Returns a +// function that stops listening. +function onMouseButtonsReleased(onRelease: () => void): () => void { + const check = (event: globalThis.MouseEvent) => { + if (event.buttons !== 0) return; + stop(); + onRelease(); + }; + const stop = () => { + window.removeEventListener("mouseup", check); + window.removeEventListener("mousemove", check); + }; + window.addEventListener("mouseup", check); + window.addEventListener("mousemove", check); + return stop; +} + function TimelineMinimap({ hasPersistentGutter, hitStripWidth, @@ -1801,6 +1819,18 @@ function TimelineMinimap({ [onWheel], ); + // A held drag that started on the minimap (the strip or its turn buttons) is a + // scrub; one that started anywhere else is a text selection. While a selection + // crosses the minimap, the minimap lets the pointer through so the selection + // keeps following the text underneath, until the button is released. + const pressedOnStripRef = useRef(false); + const [passThrough, setPassThrough] = useState(false); + + useEffect(() => { + if (!passThrough) return; + return onMouseButtonsReleased(() => setPassThrough(false)); + }, [passThrough]); + const resolvedActiveIndex = activeIndex !== null && activeIndex < items.length ? activeIndex : null; const activeItem = useMemo( @@ -1810,7 +1840,8 @@ function TimelineMinimap({ ), [items, resolvedActiveIndex], ); - const navigationInteractive = resolveTimelineMinimapNavigationInteractive(hitStripWidth); + const navigationInteractive = + resolveTimelineMinimapNavigationInteractive(hitStripWidth) && !passThrough; const activeTopPercent = resolvedActiveIndex === null ? 0 @@ -1882,8 +1913,18 @@ function TimelineMinimap({ "absolute top-1/2 left-3 -translate-y-1/2", // The strip is width-capped to the side gutter so it never overlays // the centered content column; with no usable gutter it goes inert. - hitStripWidth > 0 ? "pointer-events-auto" : "pointer-events-none", + hitStripWidth > 0 && !passThrough ? "pointer-events-auto" : "pointer-events-none", )} + onMouseDown={() => { + if (pressedOnStripRef.current) return; + pressedOnStripRef.current = true; + onMouseButtonsReleased(() => { + pressedOnStripRef.current = false; + }); + }} + onMouseMove={(event) => { + if (event.buttons !== 0 && !pressedOnStripRef.current) setPassThrough(true); + }} style={{ height: resolveTimelineMinimapHeightStyle(items.length), width: resolveTimelineMinimapInteractiveWidth(hitStripWidth, activeItem !== null), @@ -1934,7 +1975,10 @@ function TimelineMinimap({ } }} onMouseLeave={() => setActiveIndex(null)} - onMouseMove={updateActiveIndexFromPointer} + onMouseMove={(event) => { + if (event.buttons !== 0 && !pressedOnStripRef.current) return; + updateActiveIndexFromPointer(event); + }} onMouseDown={(event) => { if (timelineMinimapEventTargetsPreview(event.target)) { return; diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index da5b0d74df284..583a37d0ec741 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -21,7 +21,7 @@ import { parseModelPickerLegacySectionKey, parseModelPickerModelKey, } from "./modelPickerKeys"; -import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch"; +import { rankModelPickerSearch } from "./modelPickerSearch"; import { Combobox, ComboboxEmpty, @@ -451,77 +451,20 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { let result = flatModels; // Apply tokenized fuzzy search across the combined provider/model search fields. + // When searching, we only respect locked provider (by driver kind), + // ignoring sidebar selection so account-scoped searches can find a + // model before the user chooses a specific instance rail item. if (searchQuery.trim()) { - const rankedMatches = result - .map((model) => ({ - model, - score: scoreModelPickerSearch( - { - name: model.name, - ...(model.shortName ? { shortName: model.shortName } : {}), - ...(model.subProvider ? { subProvider: model.subProvider } : {}), - driverKind: model.driverKind, - providerDisplayName: model.instanceDisplayName, - isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)), - }, - searchQuery, - ), - isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)), - tieBreaker: buildModelPickerSearchText({ - name: model.name, - ...(model.shortName ? { shortName: model.shortName } : {}), - ...(model.subProvider ? { subProvider: model.subProvider } : {}), - driverKind: model.driverKind, - providerDisplayName: model.instanceDisplayName, - }), - })) - .filter( - ( - rankedModel, - ): rankedModel is { - model: ModelPickerItem; - score: number; - isFavorite: boolean; - tieBreaker: string; - } => rankedModel.score !== null, - ); - - // When searching, we only respect locked provider (by driver kind), - // ignoring sidebar selection so account-scoped searches can find a - // model before the user chooses a specific instance rail item. - if (props.lockedProvider !== null) { - const lockedProviderMatches: Array<(typeof rankedMatches)[number]> = []; - for (const rankedModel of rankedMatches) { - if (matchesLockedProvider(rankedModel.model)) { - lockedProviderMatches.push(rankedModel); - } - } - return lockedProviderMatches - .toSorted((a, b) => { - const scoreDelta = a.score - b.score; - if (scoreDelta !== 0) { - return scoreDelta; - } - if (a.isFavorite !== b.isFavorite) { - return a.isFavorite ? -1 : 1; - } - return a.tieBreaker.localeCompare(b.tieBreaker); - }) - .map((rankedModel) => rankedModel.model); - } - - return rankedMatches - .toSorted((a, b) => { - const scoreDelta = a.score - b.score; - if (scoreDelta !== 0) { - return scoreDelta; - } - if (a.isFavorite !== b.isFavorite) { - return a.isFavorite ? -1 : 1; - } - return a.tieBreaker.localeCompare(b.tieBreaker); - }) - .map((rankedModel) => rankedModel.model); + const candidates = + props.lockedProvider !== null ? result.filter((m) => matchesLockedProvider(m)) : result; + return rankModelPickerSearch(candidates, searchQuery, (model) => ({ + name: model.name, + ...(model.shortName ? { shortName: model.shortName } : {}), + ...(model.subProvider ? { subProvider: model.subProvider } : {}), + driverKind: model.driverKind, + providerDisplayName: model.instanceDisplayName, + isFavorite: favoritesSet.has(providerModelKey(model.instanceId, model.slug)), + })); } if (props.lockedProvider !== null) { diff --git a/apps/web/src/components/chat/modelPickerSearch.test.ts b/apps/web/src/components/chat/modelPickerSearch.test.ts index 57a7142c6b9a4..14f2cd7139c00 100644 --- a/apps/web/src/components/chat/modelPickerSearch.test.ts +++ b/apps/web/src/components/chat/modelPickerSearch.test.ts @@ -1,6 +1,10 @@ import { describe, expect, it } from "vite-plus/test"; -import { buildModelPickerSearchText, scoreModelPickerSearch } from "./modelPickerSearch"; +import { + buildModelPickerSearchText, + rankModelPickerSearch, + scoreModelPickerSearch, +} from "./modelPickerSearch"; describe("buildModelPickerSearchText", () => { it("builds provider-agnostic search text from generic fields", () => { @@ -129,3 +133,187 @@ describe("scoreModelPickerSearch", () => { ).not.toBeNull(); }); }); + +type CatalogModel = { + driverKind: string; + providerDisplayName: string; + name: string; + subProvider?: string; + isFavorite?: boolean; +}; + +function instanceModels( + driverKind: string, + providerDisplayName: string, + names: ReadonlyArray, +): CatalogModel[] { + return names.map((name) => ({ driverKind, providerDisplayName, name })); +} + +// Each provider lists its models newest first, as the picker receives them. +// Claude, Codex, and Antigravity mirror apps/server/src/provider/model-manifest.json; +// Grok and OpenCode report their catalogs at runtime. +const catalog: CatalogModel[] = [ + ...instanceModels("claudeAgent", "Claude", [ + "Claude Opus 5.5", + "Claude Sonnet 5.5", + "Claude Fable 5.1", + "Claude Fable 5", + "Claude Opus 5", + "Claude Opus 4.8", + "Claude Opus 4.7", + "Claude Opus 4.6", + "Claude Opus 4.5", + "Claude Sonnet 5", + "Claude Sonnet 4.6", + "Claude Haiku 5.5", + "Claude Haiku 4.5", + ]), + ...instanceModels("codex", "Codex", [ + "GPT-6.1 Sol", + "GPT-6 Astra", + "GPT-6 Luna", + "GPT-6 Sol", + "GPT-5.6 Sol", + "GPT-5.6 Terra", + "GPT-5.6 Luna", + "GPT-5.5", + ]), + ...instanceModels("grok", "Grok", ["Grok 4.7", "Grok 4.6", "Grok 4.5"]), + ...instanceModels("antigravity", "Antigravity", [ + "Gemini 3.8 Flash (High)", + "Gemini 3.8 Flash (Medium)", + "Gemini 3.8 Flash (Low)", + "Gemini 3.7 Flash (High)", + "Gemini 3.7 Flash (Medium)", + "Gemini 3.7 Flash (Low)", + "Gemini 3.6 Flash (High)", + "Gemini 3.6 Flash (Medium)", + "Gemini 3.6 Flash (Low)", + "Gemini 3.1 Pro (High)", + "Gemini 3.1 Pro (Low)", + ]), + { + driverKind: "opencode", + providerDisplayName: "OpenCode", + name: "Kimi K3", + subProvider: "Moonshot", + }, + { + driverKind: "opencode", + providerDisplayName: "OpenCode", + name: "Kimi K2.5", + subProvider: "Moonshot", + }, + { + driverKind: "opencode", + providerDisplayName: "OpenCode", + name: "Kimi K2", + subProvider: "Moonshot", + }, +]; + +function search(query: string, models: ReadonlyArray = catalog): string[] { + return rankModelPickerSearch(models, query, (model) => model).map((model) => model.name); +} + +describe("rankModelPickerSearch", () => { + it.each([ + [ + "opus", + [ + "Claude Opus 5.5", + "Claude Opus 5", + "Claude Opus 4.8", + "Claude Opus 4.7", + "Claude Opus 4.6", + "Claude Opus 4.5", + ], + ], + ["sonnet", ["Claude Sonnet 5.5", "Claude Sonnet 5", "Claude Sonnet 4.6"]], + ["fable", ["Claude Fable 5.1", "Claude Fable 5"]], + ["haiku", ["Claude Haiku 5.5", "Claude Haiku 4.5"]], + [ + "gpt", + [ + "GPT-6.1 Sol", + "GPT-6 Astra", + "GPT-6 Luna", + "GPT-6 Sol", + "GPT-5.6 Sol", + "GPT-5.6 Terra", + "GPT-5.6 Luna", + "GPT-5.5", + ], + ], + ["sol", ["GPT-6.1 Sol", "GPT-6 Sol", "GPT-5.6 Sol"]], + ["luna", ["GPT-6 Luna", "GPT-5.6 Luna"]], + ["grok", ["Grok 4.7", "Grok 4.6", "Grok 4.5"]], + [ + "flash", + [ + "Gemini 3.8 Flash (High)", + "Gemini 3.8 Flash (Medium)", + "Gemini 3.8 Flash (Low)", + "Gemini 3.7 Flash (High)", + "Gemini 3.7 Flash (Medium)", + "Gemini 3.7 Flash (Low)", + "Gemini 3.6 Flash (High)", + "Gemini 3.6 Flash (Medium)", + "Gemini 3.6 Flash (Low)", + ], + ], + ["kimi", ["Kimi K3", "Kimi K2.5", "Kimi K2"]], + ])("lists equally good matches for %j newest first", (query, expected) => { + // Loose fuzzy matches from other families may follow; they rank last. + expect(search(query).slice(0, expected.length)).toEqual(expected); + }); + + it("keeps newest first when a version token narrows the family", () => { + expect(search("opus 4")).toEqual([ + "Claude Opus 4.8", + "Claude Opus 4.7", + "Claude Opus 4.6", + "Claude Opus 4.5", + ]); + // "5" only appears mid-version in 4.5, a weaker match. + expect(search("opus 5")).toEqual(["Claude Opus 5.5", "Claude Opus 5", "Claude Opus 4.5"]); + expect(search("opus 5.")).toEqual(["Claude Opus 5.5"]); + }); + + it("still ranks an exact name above newer models that extend it", () => { + expect(search("gpt-6 sol").slice(0, 2)).toEqual(["GPT-6 Sol", "GPT-6.1 Sol"]); + expect(search("claude opus 5").slice(0, 2)).toEqual(["Claude Opus 5", "Claude Opus 5.5"]); + expect(search("Grok 4.6")[0]).toBe("Grok 4.6"); + }); + + it("matches an exact name regardless of extra whitespace in the query", () => { + expect(search(" claude opus 5 ")[0]).toBe("Claude Opus 5"); + }); + + it("ranks an exact name above a favorite partial match", () => { + const models = catalog.map((model) => + model.name === "Claude Opus 5.5" ? { ...model, isFavorite: true } : model, + ); + expect(search("claude opus 5", models)[0]).toBe("Claude Opus 5"); + }); + + it("matches the provider when the name does not", () => { + expect(search("moonshot")).toEqual(["Kimi K3", "Kimi K2.5", "Kimi K2"]); + }); + + it("ranks a favorite above newer models in the same family", () => { + const models = catalog.map((model) => + model.name === "Claude Opus 4.5" ? { ...model, isFavorite: true } : model, + ); + expect(search("opus", models).slice(0, 3)).toEqual([ + "Claude Opus 4.5", + "Claude Opus 5.5", + "Claude Opus 5", + ]); + }); + + it("follows the order it is given, including a user's custom model order", () => { + expect(search("grok", catalog.toReversed())).toEqual(["Grok 4.5", "Grok 4.6", "Grok 4.7"]); + }); +}); diff --git a/apps/web/src/components/chat/modelPickerSearch.ts b/apps/web/src/components/chat/modelPickerSearch.ts index ff265e4a65a5e..b2791725bd599 100644 --- a/apps/web/src/components/chat/modelPickerSearch.ts +++ b/apps/web/src/components/chat/modelPickerSearch.ts @@ -16,6 +16,8 @@ type ModelPickerSearchableModel = { }; const MODEL_PICKER_FAVORITE_SCORE_BOOST = 24; +// Far below any token-scored match, favorites included. +const MODEL_PICKER_EXACT_NAME_SCORE = -1000; function getModelPickerSearchFields(model: ModelPickerSearchableModel): string[] { return [ @@ -41,9 +43,14 @@ function scoreModelPickerSearchToken( boundaryBase: fieldBase + 4, includesBase: fieldBase + 6, ...(token.length >= 3 ? { fuzzyBase: fieldBase + 100 } : {}), + ignorePosition: true, }); } +function normalizeModelName(name: string): string { + return normalizeSearchQuery(name).replace(/\s+/gu, " "); +} + export function buildModelPickerSearchText(model: ModelPickerSearchableModel): string { return normalizeSearchQuery( [model.name, model.shortName, model.subProvider, model.driverKind, model.providerDisplayName] @@ -64,6 +71,14 @@ export function scoreModelPickerSearch( return 0; } + const normalizedQuery = tokens.join(" "); + if ( + normalizedQuery === normalizeModelName(model.name) || + normalizedQuery === normalizeModelName(model.shortName ?? "") + ) { + return MODEL_PICKER_EXACT_NAME_SCORE; + } + const fields = getModelPickerSearchFields(model); let score = 0; @@ -85,3 +100,38 @@ export function scoreModelPickerSearch( return model.isFavorite ? score - MODEL_PICKER_FAVORITE_SCORE_BOOST : score; } + +/** + * Filters `items` to those matching `query`, best match first. Equal matches + * keep their order in `items`, which is the provider's own newest-first order. + */ +export function rankModelPickerSearch( + items: ReadonlyArray, + query: string, + toSearchable: (item: T) => ModelPickerSearchableModel, +): T[] { + const ranked: Array<{ + item: T; + score: number; + isFavorite: boolean; + order: number; + }> = []; + items.forEach((item, order) => { + const searchable = toSearchable(item); + const score = scoreModelPickerSearch(searchable, query); + if (score !== null) { + ranked.push({ + item, + score, + isFavorite: searchable.isFavorite === true, + order, + }); + } + }); + return ranked + .toSorted( + (a, b) => + a.score - b.score || Number(b.isFavorite) - Number(a.isFavorite) || a.order - b.order, + ) + .map((entry) => entry.item); +} diff --git a/apps/web/src/components/diffs/StyledDiffCodeView.tsx b/apps/web/src/components/diffs/StyledDiffCodeView.tsx index 9522f53b6d148..85344ebafb9d8 100644 --- a/apps/web/src/components/diffs/StyledDiffCodeView.tsx +++ b/apps/web/src/components/diffs/StyledDiffCodeView.tsx @@ -14,6 +14,13 @@ import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider"; /** The app's diff stylesheet, shared by single-file renderers so their separators match. */ export const DIFF_VIEW_UNSAFE_CSS = `${DIFF_SURFACE_THEME_UNSAFE_CSS} +/* A 1fr track's automatic minimum grows with the currently mounted lines. In split + wrap mode that shifts width between columns, rewraps rows and makes the virtualizer + repeatedly correct the scroll position. Keep both code columns at the same width. */ +[data-diff-type="split"][data-overflow="wrap"] { + --diffs-code-grid: var(--diffs-grid-number-column-width) minmax(0, 1fr); +} + :is( [data-line], [data-line-annotation], diff --git a/apps/web/src/components/files/BrowserDocumentFrame.tsx b/apps/web/src/components/files/BrowserDocumentFrame.tsx index a2fbaa0fb92e9..237c60939c134 100644 --- a/apps/web/src/components/files/BrowserDocumentFrame.tsx +++ b/apps/web/src/components/files/BrowserDocumentFrame.tsx @@ -13,6 +13,7 @@ import { htmlRenderThemeMessage, htmlRenderResult, readHtmlRenderContentHeight, + readHtmlRenderImageRequest, readHtmlRenderKeyDown, readHtmlRenderLinkRequest, } from "@t3tools/shared/htmlRender"; @@ -24,6 +25,8 @@ import { import { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react"; import { useOpenLink } from "~/browser/useOpenLink"; +import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog"; +import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview"; import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme"; import { shortcutConflictKey } from "~/keybindings"; import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink"; @@ -124,11 +127,16 @@ export function HtmlRenderDocument(props: { readonly threadRef?: ScopedThreadRef | undefined; /** Receives the page's content height whenever it changes, so an inline frame can fit it. */ readonly onContentHeight?: (height: number) => void; + /** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */ + readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined; + /** Called when the page has loaded. */ + readonly onLoad?: () => void; }) { const theme = useHtmlRenderTheme(); const frameRef = useRef(null); const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`); const [loaded, setLoaded] = useState(false); + const [expandedImage, setExpandedImage] = useState(null); const postTheme = () => { frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*"); }; @@ -265,6 +273,31 @@ export function HtmlRenderDocument(props: { window.addEventListener("message", replayKey); return () => window.removeEventListener("message", replayKey); }, []); + // A clicked page image opens in the same viewer as chat images, gated like a link. + useEffect(() => { + const openImage = (event: MessageEvent) => { + const frame = frameRef.current; + const request = readHtmlRenderImageRequest(event.data); + if ( + request === undefined || + frame === null || + event.source !== frame.contentWindow || + document.activeElement !== frame || + navigator.userActivation?.isActive === false + ) { + return; + } + setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 }); + }; + window.addEventListener("message", openImage); + return () => window.removeEventListener("message", openImage); + }, []); + const { onFullscreenChange } = props; + useEffect(() => { + if (expandedImage === null) return; + onFullscreenChange?.(true); + return () => onFullscreenChange?.(false); + }, [expandedImage, onFullscreenChange]); const { onContentHeight } = props; // A page posts its height once per change, so listen from the commit that // inserts the frame; a passive effect could run after a fast page's first post. @@ -280,24 +313,30 @@ export function HtmlRenderDocument(props: { return () => window.removeEventListener("message", resize); }, [onContentHeight]); return ( -