diff --git a/apps/desktop/src/backend/DesktopBackendConfiguration.ts b/apps/desktop/src/backend/DesktopBackendConfiguration.ts index 983c00a04c3fd..9c12690f31351 100644 --- a/apps/desktop/src/backend/DesktopBackendConfiguration.ts +++ b/apps/desktop/src/backend/DesktopBackendConfiguration.ts @@ -90,6 +90,7 @@ const WSL_FORWARDED_ENV_NAMES = [ "ANTHROPIC_API_KEY", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", // Otherwise the WSL server keeps exporting to endpoints from the bootstrap. "T3CODE_OTEL_SDK_DISABLED", "OTEL_SDK_DISABLED", diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index 2a01977302594..9c15a0e0a4a95 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -1680,6 +1680,30 @@ describe("PreviewManager", () => { ), ); + effectIt.effect( + "does not open picture-in-picture against a destroyed webview's WebContents", + () => + withManager((manager) => + Effect.gen(function* () { + const guest = makeAttachingGuest(49); + fromId.mockImplementation((id) => + id === 49 && !guest.wc.isDestroyed() ? guest.wc : null, + ); + yield* manager.prepareWebview(guest.wc); + yield* manager.createTab("tab_destroyed_guest"); + yield* manager.registerWebview("tab_destroyed_guest", 49); + + guest.destroy(); + yield* Effect.yieldNow; + + const pictureInPicture = yield* Effect.flip( + manager.openPictureInPicture("tab_destroyed_guest"), + ).pipe(Effect.orDie); + expect(pictureInPicture._tag).toBe("PreviewWebviewNotInitializedError"); + }), + ), + ); + effectIt.effect("skips a guest destroyed while another guest's session opens", () => withManager((manager) => Effect.gen(function* () { diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index fbf70e12fd375..531e269a07f11 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -2040,6 +2040,51 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function ); }); + // Clears a tab's dead guest so callers see "no webview" until the renderer registers a new one. + const detachDestroyedWebContents = Effect.fn("PreviewManager.detachDestroyedWebContents")( + function* (tabId: string, webContentsId: number) { + const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); + yield* withTabLifecycleLock( + tabId, + Effect.gen(function* () { + const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); + const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); + const currentWebContents = webContents.fromId(webContentsId); + if ( + currentTab?.webContentsId !== webContentsId || + currentAttachment !== expectedAttachment || + (currentWebContents && !currentWebContents.isDestroyed()) + ) { + return; + } + yield* Effect.all( + [ + detachControlSession(webContentsId), + detachListeners(webContentsId), + cancelPickElement(tabId), + ], + { concurrency: 3, discard: true }, + ); + const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => { + const current = tabs.get(tabId); + if (current?.webContentsId !== webContentsId) { + return [Option.none(), tabs] as const; + } + const { favicon: _favicon, ...currentWithoutFavicon } = current; + const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; + return [ + Option.some(next), + replaceMap(tabs, (copy) => { + copy.set(tabId, next); + }), + ] as const; + }); + if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value); + }), + ); + }, + ); + // URL tabs can paint before registerWebview; set the background at attach time. const prepareWebview = Effect.fn("PreviewManager.prepareWebview")(function* ( wc: Electron.WebContents, @@ -2059,7 +2104,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function }); wc.once("destroyed", () => { guestLoadFailures.delete(webContentsId); - runFork(hideDestroyedGuest(webContentsId)); + runFork( + Effect.gen(function* () { + yield* hideDestroyedGuest(webContentsId); + const tabId = yield* tabIdForWebContents(webContentsId); + if (tabId) yield* detachDestroyedWebContents(tabId, webContentsId); + }), + ); runFork(detachControlSession(webContentsId)); }); yield* ensureControlSession(wc).pipe( @@ -2135,45 +2186,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function const webContentsId = pending.webContentsId; const wc = webContents.fromId(webContentsId); if (!wc || wc.isDestroyed()) { - const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); - yield* withTabLifecycleLock( - tabId, - Effect.gen(function* () { - const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId); - const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId); - const currentWebContents = webContents.fromId(webContentsId); - if ( - currentTab?.webContentsId !== webContentsId || - currentAttachment !== expectedAttachment || - (currentWebContents && !currentWebContents.isDestroyed()) - ) { - return; - } - yield* Effect.all( - [ - detachControlSession(webContentsId), - detachListeners(webContentsId), - cancelPickElement(tabId), - ], - { concurrency: 3, discard: true }, - ); - const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => { - const current = tabs.get(tabId); - if (current?.webContentsId !== webContentsId) { - return [Option.none(), tabs] as const; - } - const { favicon: _favicon, ...currentWithoutFavicon } = current; - const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null }; - return [ - Option.some(next), - replaceMap(tabs, (copy) => { - copy.set(tabId, next); - }), - ] as const; - }); - if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value); - }), - ); + yield* detachDestroyedWebContents(tabId, webContentsId); return; } yield* leaveBusyPage(wc); @@ -2248,6 +2261,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function Effect.catchTags({ PreviewTabNotFoundError: () => Effect.void, PreviewWebContentsNotFoundError: () => Effect.void, + PreviewWebviewNotInitializedError: () => Effect.void, }), ); diff --git a/apps/desktop/src/shell/DesktopShellEnvironment.ts b/apps/desktop/src/shell/DesktopShellEnvironment.ts index 8d046fc5ca646..3c90d7bfcaff1 100644 --- a/apps/desktop/src/shell/DesktopShellEnvironment.ts +++ b/apps/desktop/src/shell/DesktopShellEnvironment.ts @@ -124,6 +124,7 @@ const LOGIN_SHELL_ENV_NAMES = [ "NODE_EXTRA_CA_CERTS", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", "T3CODE_RELEASE_BASE_URL", "__MISE_DIFF", "JAVA_HOME", @@ -553,6 +554,7 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix "PNPM_HOME", "T3CODE_TELEMETRY_ENABLED", "T3CODE_GITHUB_APP_CLIENT_ID", + "T3CODE_TANSTACK_SOURCE", "T3CODE_RELEASE_BASE_URL", ] as const) { if (!config.env[name] && shellEnvironment[name]) { diff --git a/apps/mobile/app.config.ts b/apps/mobile/app.config.ts index bad4faed441fd..464f7ab9929b0 100644 --- a/apps/mobile/app.config.ts +++ b/apps/mobile/app.config.ts @@ -346,7 +346,12 @@ const config: ExpoConfig = { }, { fontFamily: "DMSans-Bold", - fontDefinitions: [{ path: dmSansFonts.bold, weight: 700 }], + // Android picks fallback glyphs (such as Vietnamese) at the requested weight, so bold text + // asks for 700; the 400 entry lets a relative bold step (Typeface.BOLD) land on 700 too. + fontDefinitions: [ + { path: dmSansFonts.bold, weight: 400 }, + { path: dmSansFonts.bold, weight: 700 }, + ], }, ], }, diff --git a/apps/mobile/global.css b/apps/mobile/global.css index 7a4cd4eff5046..79010054c1492 100644 --- a/apps/mobile/global.css +++ b/apps/mobile/global.css @@ -50,6 +50,7 @@ @utility font-t3-bold { font-family: var(--font-bold); + font-weight: 700; } @utility font-t3-extrabold { diff --git a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt index 8b0a84a952caf..e2d5a12d76304 100644 --- a/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt +++ b/apps/mobile/modules/t3-review-diff/android/src/main/java/expo/modules/t3reviewdiff/T3ReviewDiffView.kt @@ -1314,12 +1314,13 @@ private class DiffCanvasView(context: Context) : View(context) { } val selected = selectedRowIds.contains(row.id) if (selected) { + // Source files hide the change bar (width 0); the selection marker still needs to show. fill( canvas, withAlpha(theme.hunkText, 242), 0f, top.toFloat(), - style.changeBarWidthPx, + maxOf(style.changeBarWidthPx, 4f * density), bottom.toFloat() ) } diff --git a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift index 7fe4a068f9bbb..0c65ddf19460a 100644 --- a/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift +++ b/apps/mobile/modules/t3-review-diff/ios/T3ReviewDiffView.swift @@ -2661,8 +2661,9 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate { return } + // Source files hide the change bar (width 0); the selection marker still needs to show. theme.hunkText.withAlphaComponent(0.95).setFill() - context.fill(CGRect(x: 0, y: rect.minY, width: style.changeBarWidth, height: rect.height)) + context.fill(CGRect(x: 0, y: rect.minY, width: max(style.changeBarWidth, 4), height: rect.height)) } private func drawWordDiffRanges( diff --git a/apps/mobile/src/features/review/useReviewDiffData.ts b/apps/mobile/src/features/review/useReviewDiffData.ts index cf6574d87b26b..d530279f8ca25 100644 --- a/apps/mobile/src/features/review/useReviewDiffData.ts +++ b/apps/mobile/src/features/review/useReviewDiffData.ts @@ -215,9 +215,11 @@ export function useReviewDiffData(input: { request: { cwd, ...(lazySource.baseRef ? { baseRef: lazySource.baseRef } : {}), + ...(lazySource.mergeBase ? { mergeBase: lazySource.mergeBase } : {}), file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: lazySource.kind, }, }, diff --git a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx index b916b49697fc5..1da0ec450a572 100644 --- a/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx +++ b/apps/mobile/src/features/threads/git/GitConfirmSheet.tsx @@ -3,7 +3,7 @@ import { sourceControlClients } from "@t3tools/client-runtime/source-control-cli import { resolveAutoFeatureBranchName } from "@t3tools/shared/git"; import * as Arr from "effect/Array"; import * as Result from "effect/Result"; -import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native"; +import { useNavigation, type StaticScreenProps } from "@react-navigation/native"; import { useGT, useMessages } from "gt-react-native"; import { useCallback, useMemo } from "react"; import { View } from "react-native"; @@ -20,6 +20,7 @@ import { type GitRepositoryRouteParams, } from "../../../state/thread-git-target"; import { vcsEnvironment } from "../../../state/vcs"; +import { useReturnToThread } from "../thread-inspector-navigation"; import { SheetActionButton } from "./gitSheetComponents"; type GitConfirmSheetProps = StaticScreenProps< @@ -38,6 +39,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const gt = useGT(); const messages = useMessages(); const navigation = useNavigation(); + const returnToThread = useReturnToThread(); const repository = gitRepositoryTargetFromRoute(props.route.params); const gitState = useSelectedThreadGitState(repository); const gitActions = useSelectedThreadGitActions(repository); @@ -89,7 +91,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const continuePendingAction = async () => { if (!canWriteSourceControl || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); await gitActions.onRunSelectedThreadGitAction({ action: confirmAction, ...(params.commitMessage ? { commitMessage: params.commitMessage } : {}), @@ -99,7 +101,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { const movePendingActionToFeatureBranch = useCallback(async () => { if (!canCreateFeatureBranch || !confirmAction) return; - navigation.dispatch(StackActions.replace("Thread", { environmentId, threadId })); + returnToThread({ environmentId, threadId }); if (includesCommit) { await gitActions.onRunSelectedThreadGitAction({ @@ -131,7 +133,7 @@ export function GitConfirmSheet(props: GitConfirmSheetProps) { gitState.selectedThreadBranches, includesCommit, params, - navigation, + returnToThread, environmentId, threadId, ]); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx index 404d28184d7b8..f2398d6e1fc90 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.test.tsx @@ -29,7 +29,7 @@ vi.mock("@react-navigation/native", async () => { }; }); -import { useOpenThreadInspector } from "./thread-inspector-navigation"; +import { useOpenThreadInspector, useReturnToThread } from "./thread-inspector-navigation"; import { useOpenLinkedThread, useOpenLinkedThreadRead } from "./useOpenLinkedThread"; const requireNavigation = NodeModule.createRequire( @@ -45,7 +45,15 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; const router = StackRouter({}); const options = { - routeNames: ["Home", "Thread", "ThreadAgents", "ThreadInspectorFullscreen", "LinkedThread"], + routeNames: [ + "Home", + "Thread", + "ThreadAgents", + "ThreadInspectorFullscreen", + "LinkedThread", + "ThreadReview", + "GitConfirm", + ], routeParamList: {}, routeGetIdList: {}, }; @@ -70,14 +78,17 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru let openInspector: ReturnType; let openLinkedThread: ReturnType; let openLinkedThreadRead: ReturnType; + let returnToThread: ReturnType; function Probe() { const open = useOpenThreadInspector(); const openLinked = useOpenLinkedThread(); const openLinkedRead = useOpenLinkedThreadRead(); + const returnTo = useReturnToThread(); useLayoutEffect(() => { openInspector = open; openLinkedThread = openLinked; openLinkedThreadRead = openLinkedRead; + returnToThread = returnTo; }); return null; } @@ -103,6 +114,9 @@ function setup(fromAgents: boolean, fullscreen = false, inspectorSupported = tru openLinkedRead(...input: Parameters) { act(() => openLinkedThreadRead(...input)); }, + returnTo(thread: Parameters[0]) { + act(() => returnToThread(thread)); + }, [Symbol.dispose]() { act(() => root.unmount()); }, @@ -190,6 +204,29 @@ it.each([ }, ); +it.each([ + { confirmFrom: "parent", routes: ["Home", "Thread"] }, + // A side thread's review, opened from the parent's inspector, sits above the parent's route. + { confirmFrom: "child", routes: ["Home", "Thread", "ThreadReview", "Thread"] }, +])( + "returns from a Git confirmation to the $confirmFrom thread without replacing another", + ({ confirmFrom, routes }) => { + using screen = setup(false); + const inspector = { type: "device", ...screen.source } as const; + screen.open(inspector); + const thread = { ...screen.source, threadId: confirmFrom }; + if (confirmFrom !== "parent") screen.dispatch(StackActions.push("ThreadReview", thread)); + screen.dispatch(StackActions.push("GitConfirm", thread)); + screen.returnTo(thread); + expect(screen.state.routes.map((route) => route.name)).toEqual(routes); + expect(screen.state.routes[1]).toMatchObject({ + key: screen.parentKey, + params: { ...screen.source, prompt: "retained prompt", inspector }, + }); + expect(screen.state.routes.at(-1)?.params).toMatchObject(thread); + }, +); + it("switches between subagents and devices in the same parent route", () => { using screen = setup(false); screen.open({ type: "thread", environmentId: screen.source.environmentId, threadId: "child" }); diff --git a/apps/mobile/src/features/threads/thread-inspector-navigation.ts b/apps/mobile/src/features/threads/thread-inspector-navigation.ts index 966dd1a92a632..04fc59ed636e1 100644 --- a/apps/mobile/src/features/threads/thread-inspector-navigation.ts +++ b/apps/mobile/src/features/threads/thread-inspector-navigation.ts @@ -41,15 +41,7 @@ export function useOpenThreadInspector() { if (presentation === "full-screen") return false; if (openInInspector) openInInspector(target); else { - const parent = navigation.getState()?.routes.findLast((route) => route.name === "Thread"); - if ( - !parent?.params || - !("environmentId" in parent.params) || - parent.params.environmentId !== source.environmentId || - !("threadId" in parent.params) || - parent.params.threadId !== source.threadId - ) - return false; + if (!isNearestThreadRoute(navigation.getState(), source)) return false; navigation.dispatch( StackActions.popTo("Thread", { ...source, inspector: target }, { merge: true }), ); @@ -57,3 +49,31 @@ export function useOpenThreadInspector() { return true; }; } + +/** Closes the screens above `thread`, or opens it when the nearest thread route is another one. */ +export function useReturnToThread() { + const navigation = useNavigation(); + return (thread: { readonly environmentId: string; readonly threadId: string }) => + navigation.dispatch( + isNearestThreadRoute(navigation.getState(), thread) + ? StackActions.popTo("Thread", thread, { merge: true }) + : StackActions.replace("Thread", thread), + ); +} + +// `Thread` has no `getId`, so `popTo("Thread")` lands on the nearest one whatever thread it shows. +function isNearestThreadRoute( + state: + | { readonly routes: ReadonlyArray<{ readonly name: string; readonly params?: object }> } + | undefined, + thread: { readonly environmentId: string; readonly threadId: string }, +) { + const params = state?.routes.findLast((route) => route.name === "Thread")?.params; + return ( + params !== undefined && + "environmentId" in params && + params.environmentId === thread.environmentId && + "threadId" in params && + params.threadId === thread.threadId + ); +} diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index 7c61d3f95e40d..e0eb437599e38 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installiere die Origin CLI mit {install} und führe dann {login} aus.", "eb0f60ef4f92ab7d": "Installiere {fj} 0.6 oder neuer von {fjUrl} und führe {fjLogin} aus, oder installiere {tea} 0.16 oder neuer von {teaUrl} und führe {teaLogin} für jeden Forgejo- oder Gitea-Server aus.", "d026a85e2e50e675": "Installiere die GitCafe CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", + "22d3c0c48a34b5b3": "Installiere die TanStack Source CLI mit {install} und führe dann {login} aus, speichere ein Token in den Einstellungen oder setze {variable} auf dem Server.", "79d776428f4d0650": "Die Datei konnte nicht geladen werden. Verbinde dich erneut und versuch es noch einmal.", "3ea34cbb1ca5ba9b": "Vorschau abgebrochen.", "7c0af279ecb3da3a": "Streamende Dateivorschauen sind in dieser Laufzeitumgebung nicht verfügbar.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Überschriften", "29005b7a742cae1e": "Links", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopieren", + "0165ef55eb6c8a99": "Als Markdown kopieren", + "439737cb6de2a5b3": "Bild-URL kopieren", + "d3d24474c922eef2": "{count} Bild-URLs kopieren", "f18f6d80b6bd08a0": "Modellreferenz kopieren", "d7a551536aa43f3e": "Modellreferenz teilen", "9f1b29c948772f0f": "Link öffnen", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Link teilen", "51244cd196696a00": "Zitieren", "6cdca065884f77f2": "Kopieren", - "0165ef55eb6c8a99": "Als Markdown kopieren", "7c1923203049d602": "Code kopieren", "74d986aed0381cb0": "Der Diagramm-Renderer konnte nicht geladen werden.", "9cc6288e83305ca3": "Das Diagramm konnte nicht gerendert werden.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Akzeptieren", "255ae21697461ef6": "Übernimm die Steuerung, um zu antworten.", "d2a40ef08ef016ec": "{command} kopieren", - "a034d65164bb39de": "Kopieren", "e0cfab9ded209e81": "Neu verbinden", "b00379f06c304b6a": "Browser öffnen, {title}", "149eba5f977b0549": "Öffnet den Browser-Tab im Vollbild", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 53ae1e18e3efa..bca87cee0884f 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Install the Origin CLI with {install}, then run {login}.", "eb0f60ef4f92ab7d": "Install {fj} 0.6 or later from {fjUrl} and run {fjLogin}, or install {tea} 0.16 or later from {teaUrl} and run {teaLogin} for each Forgejo or Gitea server.", "d026a85e2e50e675": "Install the GitCafe CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", + "22d3c0c48a34b5b3": "Install the TanStack Source CLI with {install}, then run {login}, save a token in Settings, or set {variable} on the server.", "79d776428f4d0650": "The file could not be loaded. Reconnect and try again.", "3ea34cbb1ca5ba9b": "Preview cancelled.", "7c0af279ecb3da3a": "Streaming file previews are unavailable in this runtime.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Headings", "29005b7a742cae1e": "Links", "728a49012344e673": "Images", + "a034d65164bb39de": "Copy", + "0165ef55eb6c8a99": "Copy as Markdown", + "439737cb6de2a5b3": "Copy Image URL", + "d3d24474c922eef2": "Copy {count} Image URLs", "f18f6d80b6bd08a0": "Copy model reference", "d7a551536aa43f3e": "Share model reference", "9f1b29c948772f0f": "Open link", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Share link", "51244cd196696a00": "Cite", "6cdca065884f77f2": "Copy", - "0165ef55eb6c8a99": "Copy as Markdown", "7c1923203049d602": "Copy code", "74d986aed0381cb0": "The diagram renderer failed to load.", "9cc6288e83305ca3": "The diagram could not be rendered.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Accept", "255ae21697461ef6": "Take control to respond.", "d2a40ef08ef016ec": "Copy {command}", - "a034d65164bb39de": "Copy", "e0cfab9ded209e81": "Reconnect", "b00379f06c304b6a": "Open browser, {title}", "149eba5f977b0549": "Opens the browser tab full screen", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index e8c92c5285382..3f73e995b2521 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instala la CLI de Origin con {install} y ejecuta {login}.", "eb0f60ef4f92ab7d": "Instala {fj} 0.6 o posterior desde {fjUrl} y ejecuta {fjLogin}, o instala {tea} 0.16 o posterior desde {teaUrl} y ejecuta {teaLogin} para cada servidor de Forgejo o Gitea.", "d026a85e2e50e675": "Instala la CLI de GitCafe con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", + "22d3c0c48a34b5b3": "Instala la CLI de TanStack Source con {install} y ejecuta {login}, guarda un token en Ajustes o define {variable} en el servidor.", "79d776428f4d0650": "No se pudo cargar el archivo. Vuelve a conectarte e inténtalo de nuevo.", "3ea34cbb1ca5ba9b": "Vista previa cancelada.", "7c0af279ecb3da3a": "Las vistas previas de archivos en streaming no están disponibles en este entorno de ejecución.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Encabezados", "29005b7a742cae1e": "Enlaces", "728a49012344e673": "Imágenes", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL de la imagen", + "d3d24474c922eef2": "Copiar {count} URL de imágenes", "f18f6d80b6bd08a0": "Copiar referencia del modelo", "d7a551536aa43f3e": "Compartir referencia del modelo", "9f1b29c948772f0f": "Abrir enlace", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Compartir enlace", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "No se pudo cargar el renderizador de diagramas.", "9cc6288e83305ca3": "No se pudo renderizar el diagrama.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Aceptar", "255ae21697461ef6": "Toma el control para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Volver a conectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre la pestaña del navegador a pantalla completa", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 9115edfa725dd..3aff16728eeff 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installez la CLI Origin avec {install}, puis exécutez {login}.", "eb0f60ef4f92ab7d": "Installez {fj} 0.6 ou version ultérieure depuis {fjUrl} et exécutez {fjLogin}, ou installez {tea} 0.16 ou version ultérieure depuis {teaUrl} et exécutez {teaLogin} pour chaque serveur Forgejo ou Gitea.", "d026a85e2e50e675": "Installez la CLI GitCafe avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", + "22d3c0c48a34b5b3": "Installez la CLI TanStack Source avec {install}, puis exécutez {login}, enregistrez un jeton dans Paramètres ou définissez {variable} sur le serveur.", "79d776428f4d0650": "Le fichier n’a pas pu être chargé. Reconnectez-vous et réessayez.", "3ea34cbb1ca5ba9b": "Aperçu annulé.", "7c0af279ecb3da3a": "Les aperçus de fichiers en streaming ne sont pas disponibles dans cet environnement d’exécution.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Titres", "29005b7a742cae1e": "Liens", "728a49012344e673": "Images", + "a034d65164bb39de": "Copier", + "0165ef55eb6c8a99": "Copier en Markdown", + "439737cb6de2a5b3": "Copier l’URL de l’image", + "d3d24474c922eef2": "Copier {count} URL d’images", "f18f6d80b6bd08a0": "Copier la référence du modèle", "d7a551536aa43f3e": "Partager la référence du modèle", "9f1b29c948772f0f": "Ouvrir le lien", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Partager le lien", "51244cd196696a00": "Citer", "6cdca065884f77f2": "Copier", - "0165ef55eb6c8a99": "Copier en Markdown", "7c1923203049d602": "Copier le code", "74d986aed0381cb0": "Le moteur de rendu des diagrammes n’a pas pu se charger.", "9cc6288e83305ca3": "Impossible d’afficher le diagramme.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Accepter", "255ae21697461ef6": "Prenez le contrôle pour répondre.", "d2a40ef08ef016ec": "Copier {command}", - "a034d65164bb39de": "Copier", "e0cfab9ded209e81": "Se reconnecter", "b00379f06c304b6a": "Ouvrir le navigateur, {title}", "149eba5f977b0549": "Ouvre l’onglet du navigateur en plein écran", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 3c6e09395d097..302318926d092 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install} で Origin CLI をインストールしてから、{login} を実行してください。", "eb0f60ef4f92ab7d": "Forgejo または Gitea のサーバーごとに、{fjUrl} から {fj} 0.6 以降をインストールして {fjLogin} を実行するか、{teaUrl} から {tea} 0.16 以降をインストールして {teaLogin} を実行してください。", "d026a85e2e50e675": "{install} で GitCafe CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", + "22d3c0c48a34b5b3": "{install} で TanStack Source CLI をインストールしてから、{login} を実行するか、設定にトークンを保存するか、サーバーで {variable} を設定してください。", "79d776428f4d0650": "ファイルを読み込めませんでした。再接続してもう一度お試しください。", "3ea34cbb1ca5ba9b": "プレビューをキャンセルしました。", "7c0af279ecb3da3a": "このランタイムではファイルのストリーミングプレビューを利用できません。", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "見出し", "29005b7a742cae1e": "リンク", "728a49012344e673": "画像", + "a034d65164bb39de": "コピー", + "0165ef55eb6c8a99": "Markdown としてコピー", + "439737cb6de2a5b3": "画像URLをコピー", + "d3d24474c922eef2": "{count}件の画像URLをコピー", "f18f6d80b6bd08a0": "モデルの参照をコピー", "d7a551536aa43f3e": "モデルの参照を共有", "9f1b29c948772f0f": "リンクを開く", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "リンクを共有", "51244cd196696a00": "引用", "6cdca065884f77f2": "コピー", - "0165ef55eb6c8a99": "Markdown としてコピー", "7c1923203049d602": "コードをコピー", "74d986aed0381cb0": "図のレンダラーを読み込めませんでした。", "9cc6288e83305ca3": "図をレンダリングできませんでした。", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "承諾", "255ae21697461ef6": "応答するには操作権を取得してください。", "d2a40ef08ef016ec": "{command} をコピー", - "a034d65164bb39de": "コピー", "e0cfab9ded209e81": "再接続", "b00379f06c304b6a": "ブラウザーを開く、{title}", "149eba5f977b0549": "ブラウザータブを全画面で開きます", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 67eaab0392cd9..ec0ee0864e6ef 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "{install}로 Origin CLI를 설치한 후 {login}을(를) 실행하세요.", "eb0f60ef4f92ab7d": "{fjUrl}에서 {fj} 0.6 이상을 설치하고 {fjLogin}을(를) 실행하거나, {teaUrl}에서 {tea} 0.16 이상을 설치하고 Forgejo 또는 Gitea 서버마다 {teaLogin}을(를) 실행하세요.", "d026a85e2e50e675": "{install}로 GitCafe CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", + "22d3c0c48a34b5b3": "{install}로 TanStack Source CLI를 설치한 후 {login}을(를) 실행하거나, 설정에 토큰을 저장하거나, 서버에서 {variable}을(를) 설정하세요.", "79d776428f4d0650": "파일을 불러올 수 없습니다. 다시 연결한 뒤 시도하세요.", "3ea34cbb1ca5ba9b": "미리 보기가 취소되었습니다.", "7c0af279ecb3da3a": "이 런타임에서는 스트리밍 파일 미리 보기를 사용할 수 없습니다.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "제목", "29005b7a742cae1e": "링크", "728a49012344e673": "이미지", + "a034d65164bb39de": "복사", + "0165ef55eb6c8a99": "Markdown으로 복사", + "439737cb6de2a5b3": "이미지 URL 복사", + "d3d24474c922eef2": "이미지 URL {count}개 복사", "f18f6d80b6bd08a0": "모델 참조 복사", "d7a551536aa43f3e": "모델 참조 공유", "9f1b29c948772f0f": "링크 열기", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "링크 공유", "51244cd196696a00": "인용하기", "6cdca065884f77f2": "복사", - "0165ef55eb6c8a99": "Markdown으로 복사", "7c1923203049d602": "코드 복사", "74d986aed0381cb0": "다이어그램 렌더러를 불러오지 못했습니다.", "9cc6288e83305ca3": "다이어그램을 렌더링할 수 없습니다.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "수락", "255ae21697461ef6": "응답하려면 제어하세요.", "d2a40ef08ef016ec": "{command} 복사", - "a034d65164bb39de": "복사", "e0cfab9ded209e81": "다시 연결", "b00379f06c304b6a": "브라우저 열기, {title}", "149eba5f977b0549": "브라우저 탭을 전체 화면으로 엽니다", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 101a01c28c43e..56b52f85e6d01 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Instale a CLI do Origin com {install} e execute {login}.", "eb0f60ef4f92ab7d": "Instale o {fj} 0.6 ou posterior em {fjUrl} e execute {fjLogin}, ou instale o {tea} 0.16 ou posterior em {teaUrl} e execute {teaLogin} para cada servidor Forgejo ou Gitea.", "d026a85e2e50e675": "Instale a CLI do GitCafe com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", + "22d3c0c48a34b5b3": "Instale a CLI do TanStack Source com {install} e execute {login}, salve um token nas Configurações ou defina {variable} no servidor.", "79d776428f4d0650": "Não foi possível carregar o arquivo. Reconecte e tente novamente.", "3ea34cbb1ca5ba9b": "Pré-visualização cancelada.", "7c0af279ecb3da3a": "As pré-visualizações de arquivos por streaming não estão disponíveis neste runtime.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Títulos", "29005b7a742cae1e": "Links", "728a49012344e673": "Imagens", + "a034d65164bb39de": "Copiar", + "0165ef55eb6c8a99": "Copiar como Markdown", + "439737cb6de2a5b3": "Copiar URL da imagem", + "d3d24474c922eef2": "Copiar {count} URLs de imagens", "f18f6d80b6bd08a0": "Copiar referência do modelo", "d7a551536aa43f3e": "Compartilhar referência do modelo", "9f1b29c948772f0f": "Abrir link", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Compartilhar link", "51244cd196696a00": "Citar", "6cdca065884f77f2": "Copiar", - "0165ef55eb6c8a99": "Copiar como Markdown", "7c1923203049d602": "Copiar código", "74d986aed0381cb0": "Falha ao carregar o renderizador de diagramas.", "9cc6288e83305ca3": "Não foi possível renderizar o diagrama.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Aceitar", "255ae21697461ef6": "Assuma o controle para responder.", "d2a40ef08ef016ec": "Copiar {command}", - "a034d65164bb39de": "Copiar", "e0cfab9ded209e81": "Reconectar", "b00379f06c304b6a": "Abrir navegador, {title}", "149eba5f977b0549": "Abre a aba do navegador em tela cheia", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index e1578fe1ade8a..9b3b38bcf0234 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Установите Origin CLI командой {install}, затем выполните {login}.", "eb0f60ef4f92ab7d": "Установите {fj} 0.6 или новее с {fjUrl} и выполните {fjLogin} либо установите {tea} 0.16 или новее с {teaUrl} и выполните {teaLogin} для каждого сервера Forgejo или Gitea.", "d026a85e2e50e675": "Установите GitCafe CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", + "22d3c0c48a34b5b3": "Установите TanStack Source CLI командой {install}, затем выполните {login}, сохраните токен в настройках или задайте {variable} на сервере.", "79d776428f4d0650": "Не удалось загрузить файл. Переподключитесь и попробуйте ещё раз.", "3ea34cbb1ca5ba9b": "Предпросмотр отменён.", "7c0af279ecb3da3a": "Потоковый предпросмотр файлов недоступен в этой среде выполнения.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Заголовки", "29005b7a742cae1e": "Ссылки", "728a49012344e673": "Изображения", + "a034d65164bb39de": "Копировать", + "0165ef55eb6c8a99": "Копировать как Markdown", + "439737cb6de2a5b3": "Копировать URL изображения", + "d3d24474c922eef2": "Копировать URL изображений: {count}", "f18f6d80b6bd08a0": "Копировать ссылку на модель", "d7a551536aa43f3e": "Поделиться ссылкой на модель", "9f1b29c948772f0f": "Открыть ссылку", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Поделиться ссылкой", "51244cd196696a00": "Цитировать", "6cdca065884f77f2": "Копировать", - "0165ef55eb6c8a99": "Копировать как Markdown", "7c1923203049d602": "Копировать код", "74d986aed0381cb0": "Не удалось загрузить отрисовщик диаграмм.", "9cc6288e83305ca3": "Не удалось отрисовать диаграмму.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Принять", "255ae21697461ef6": "Возьмите управление, чтобы ответить.", "d2a40ef08ef016ec": "Копировать {command}", - "a034d65164bb39de": "Копировать", "e0cfab9ded209e81": "Переподключить", "b00379f06c304b6a": "Открыть браузер, {title}", "149eba5f977b0549": "Открывает вкладку браузера на весь экран", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 0c1c76802160a..5b94cd6efe6ea 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "Installera Origin CLI med {install} och kör sedan {login}.", "eb0f60ef4f92ab7d": "Installera {fj} 0.6 eller senare från {fjUrl} och kör {fjLogin}, eller installera {tea} 0.16 eller senare från {teaUrl} och kör {teaLogin} för varje Forgejo- eller Gitea-server.", "d026a85e2e50e675": "Installera GitCafe CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", + "22d3c0c48a34b5b3": "Installera TanStack Source CLI med {install} och kör sedan {login}, spara en token i Inställningar eller ange {variable} på servern.", "79d776428f4d0650": "Filen kunde inte läsas in. Återanslut och försök igen.", "3ea34cbb1ca5ba9b": "Förhandsvisningen avbröts.", "7c0af279ecb3da3a": "Strömmande förhandsvisning av filer är inte tillgänglig i den här körmiljön.", @@ -1545,6 +1546,10 @@ "8f2e6a13eee27d59": "Rubriker", "29005b7a742cae1e": "Länkar", "728a49012344e673": "Bilder", + "a034d65164bb39de": "Kopiera", + "0165ef55eb6c8a99": "Kopiera som Markdown", + "439737cb6de2a5b3": "Kopiera bild-URL", + "d3d24474c922eef2": "Kopiera {count} bild-URL:er", "f18f6d80b6bd08a0": "Kopiera modellreferens", "d7a551536aa43f3e": "Dela modellreferens", "9f1b29c948772f0f": "Öppna länk", @@ -1552,7 +1557,6 @@ "d7dc565616d13a5c": "Dela länk", "51244cd196696a00": "Citera", "6cdca065884f77f2": "Kopiera", - "0165ef55eb6c8a99": "Kopiera som Markdown", "7c1923203049d602": "Kopiera kod", "74d986aed0381cb0": "Diagramrenderaren kunde inte läsas in.", "9cc6288e83305ca3": "Diagrammet kunde inte renderas.", @@ -1861,7 +1865,6 @@ "1d0a7acef4a95536": "Godkänn", "255ae21697461ef6": "Ta kontrollen för att svara.", "d2a40ef08ef016ec": "Kopiera {command}", - "a034d65164bb39de": "Kopiera", "e0cfab9ded209e81": "Återanslut", "b00379f06c304b6a": "Öppna webbläsaren, {title}", "149eba5f977b0549": "Öppnar webbläsarfliken i helskärm", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 42127c1ec5d75..0478b5b378409 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -51,6 +51,7 @@ "d810ecd91e8cf9d0": "请使用 {install} 安装 Origin CLI,然后运行 {login}。", "eb0f60ef4f92ab7d": "请从 {fjUrl} 安装 {fj} 0.6 或更高版本并运行 {fjLogin},或从 {teaUrl} 安装 {tea} 0.16 或更高版本,并为每个 Forgejo 或 Gitea 服务器运行 {teaLogin}。", "d026a85e2e50e675": "请使用 {install} 安装 GitCafe CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", + "22d3c0c48a34b5b3": "请使用 {install} 安装 TanStack Source CLI,然后运行 {login}、在设置中保存 token,或在服务器上设置 {variable}。", "79d776428f4d0650": "无法加载文件。请重新连接后重试。", "3ea34cbb1ca5ba9b": "预览已取消。", "7c0af279ecb3da3a": "此运行时不支持流式文件预览。", @@ -1546,6 +1547,10 @@ "8f2e6a13eee27d59": "标题", "29005b7a742cae1e": "链接", "728a49012344e673": "图片", + "a034d65164bb39de": "复制", + "0165ef55eb6c8a99": "复制为 Markdown", + "439737cb6de2a5b3": "复制图片 URL", + "d3d24474c922eef2": "复制 {count} 个图片 URL", "f18f6d80b6bd08a0": "复制模型引用", "d7a551536aa43f3e": "分享模型引用", "9f1b29c948772f0f": "打开链接", @@ -1553,7 +1558,6 @@ "d7dc565616d13a5c": "分享链接", "51244cd196696a00": "引用", "6cdca065884f77f2": "复制", - "0165ef55eb6c8a99": "复制为 Markdown", "7c1923203049d602": "复制代码", "74d986aed0381cb0": "图表渲染器加载失败。", "9cc6288e83305ca3": "无法渲染图表。", @@ -1862,7 +1866,6 @@ "1d0a7acef4a95536": "接受", "255ae21697461ef6": "接管控制后才能回应。", "d2a40ef08ef016ec": "复制 {command}", - "a034d65164bb39de": "复制", "e0cfab9ded209e81": "重新连接", "b00379f06c304b6a": "打开浏览器,{title}", "149eba5f977b0549": "全屏打开浏览器标签页", diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx index 9c207a3034eb5..ff542959413ec 100644 --- a/apps/mobile/src/native/EnrichedMarkdownText.tsx +++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx @@ -22,6 +22,7 @@ import { type MarkdownImageBlock, type MarkdownLinkOccurrence, type MarkdownStyle, + type TextSelectionMenuConfig, } from "react-native-enriched-markdown"; import { codeFenceRenderer } from "./codeBlockMarkdown"; import { HighlightedCodeBlock } from "./HighlightedCodeBlock"; @@ -49,6 +50,8 @@ function enrichedStyle( fontScale: number, ): MarkdownStyle { const monospace = Platform.OS === "ios" ? "Menlo" : "monospace"; + // Android only bolds fallback glyphs when the bold family is asked for at a bold weight (app.config.ts). + const boldFontWeight = Platform.OS === "android" ? "bold" : undefined; // Keep the radius modest: iOS clips square table-cell borders without stroking the corner arcs. const block = { marginTop: 4, @@ -71,6 +74,7 @@ function enrichedStyle( ...body, color: style.strongColor, fontFamily: style.headingFontFamily, + fontWeight: boldFontWeight, fontSize, lineHeight: fontSize * 1.35, marginTop: 8, @@ -93,7 +97,11 @@ function enrichedStyle( h4: heading(4), h5: heading(5), h6: heading(6), - strong: { color: style.strongColor, fontFamily: style.boldFontFamily, fontWeight: "normal" }, + strong: { + color: style.strongColor, + fontFamily: style.boldFontFamily, + fontWeight: boldFontWeight ?? "normal", + }, link: { color: style.linkColor, underline: false }, code: { fontFamily: monospace, @@ -183,6 +191,7 @@ function codeBlockElement( mathRenderingEnabled: boolean, scheme: HighlightScheme, accessibilityLabels: AccessibilityLabels, + selectionMenuConfig: TextSelectionMenuConfig, ): ReactElement | undefined { const renderer = codeFenceRenderer(block.language, mathRenderingEnabled); if (renderer.kind === "mermaid") { @@ -203,6 +212,7 @@ function codeBlockElement( selectionColor={textStyle.selectionColor} selectionHandleColor={textStyle.selectionHandleColor} accessibilityLabels={accessibilityLabels} + selectionMenuConfig={selectionMenuConfig} /> ) : undefined; } @@ -247,6 +257,18 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { }), [gt], ); + // The library's built-in selection menu items default to English labels. + const selectionMenuConfig = useMemo( + () => ({ + copy: { label: gt("Copy", { $context: "verb" }) }, + copyAsMarkdown: { label: gt("Copy as Markdown") }, + copyImageUrl: { + label: gt("Copy Image URL"), + pluralLabels: { other: gt("Copy {count} Image URLs", { count: "{count}" }) }, + }, + }), + [gt], + ); const { markdown, fileHrefs } = useMemo(() => { if (!fileEmbedLabel) { return { @@ -408,6 +430,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { mathRenderingEnabled, themeAppearance, accessibilityLabels, + selectionMenuConfig, ), }; const resolveNativeImageSource = useRetryingImageSource(resolveImageSource); @@ -465,6 +488,7 @@ export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) { : undefined } selectionClipboard={selectionClipboard} + selectionMenuConfig={selectionMenuConfig} selectionColor={props.textStyle.selectionColor} selectionHandleColor={props.textStyle.selectionHandleColor} md4cFlags={{ diff --git a/apps/server/package.json b/apps/server/package.json index 8ece0aaa8118f..9b9b3c022cacb 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -63,6 +63,7 @@ "@t3tools/source-control-gitcafe": "workspace:*", "@t3tools/source-control-github": "workspace:*", "@t3tools/source-control-gitlab": "workspace:*", + "@t3tools/source-control-tanstack-source": "workspace:*", "character-entities": "2.0.2", "diff": "8.0.3", "effect": "catalog:", diff --git a/apps/server/src/cli/update.test.ts b/apps/server/src/cli/update.test.ts index b5d3394f23fd2..2de00fc24bf54 100644 --- a/apps/server/src/cli/update.test.ts +++ b/apps/server/src/cli/update.test.ts @@ -229,6 +229,32 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => { }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")), ); + it.effect("repoints a recorded Windows launcher outside PATH", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const root = yield* fs.makeTempDirectoryScoped(); + const baseDir = path.join(root, "home"); + const runtimeDir = path.join(baseDir, "runtime"); + const launcher = path.join(root, "custom bin", "t3.cmd"); + const launchedAs = path.join(runtimeDir, "versions", "1.0.0", "t3.exe"); + const targetEntryPath = path.join(runtimeDir, "versions", "2.0.0", "t3.exe"); + yield* fs.makeDirectory(runtimeDir, { recursive: true }); + yield* fs.makeDirectory(path.dirname(launcher), { recursive: true }); + yield* fs.writeFileString(launcher, `@echo off\r\n"${launchedAs}" %*`); + yield* fs.writeFileString(path.join(runtimeDir, "launchers"), `${launcher}\r\n`); + + const repointed = yield* repointLauncher({ launchedAs, baseDir, targetEntryPath }); + + assert.equal(Option.getOrUndefined(repointed), launcher); + assert.equal(yield* fs.readFileString(launcher), `@echo off\r\n"${targetEntryPath}" %*`); + }).pipe( + Effect.scoped, + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(HostProcess.Environment, { PATH: "" }), + ), + ); + it.effect.skipIf(HostProcess.Platform.defaultValue() === "win32")( "finds the script that ran this executable and rewrites it, keeping aliases and arguments", () => diff --git a/apps/server/src/cli/update.ts b/apps/server/src/cli/update.ts index b7b76f2f34223..07f3458fb3b66 100644 --- a/apps/server/src/cli/update.ts +++ b/apps/server/src/cli/update.ts @@ -25,6 +25,7 @@ import * as BootService from "../cloud/bootService.ts"; import { ensurePinnedRuntimeInstalled, findPosixLauncher, + generatedWindowsShimTarget, launcherOwnsVersionsDir, isUnpublishedRelease, pinnedRuntimePaths, @@ -171,7 +172,7 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function ); if (platform === "win32") { - const shimPath = yield* findWindowsShim(input.launchedAs); + const shimPath = yield* findWindowsShim(input.launchedAs, versionsDir); if (shimPath === undefined) return Option.none(); const current = yield* fs.readFileString(shimPath).pipe(Effect.option); const quoted = Option.isSome(current) ? windowsShimTarget(current.value) : undefined; @@ -203,9 +204,10 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function return Option.some(launcher); }); -/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */ +/** Windows executables see their own path, so locate the installer shim by matching its target. */ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* ( executablePath: string, + versionsDir?: string, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -213,12 +215,26 @@ export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(functio const candidates = [ ...(environment["T3CODE_INSTALL_BIN_DIR"] ? [environment["T3CODE_INSTALL_BIN_DIR"]] : []), ...(environment["PATH"] ?? environment["Path"] ?? "").split(";"), - ].filter((entry) => entry.trim().length > 0); - for (const directory of candidates) { - const shimPath = path.join(directory, "t3.cmd"); + ] + .filter((entry) => entry.trim().length > 0) + .map((directory) => ({ + shimPath: path.join(directory, "t3.cmd"), + parseTarget: windowsShimTarget, + })); + if (versionsDir !== undefined) { + const recorded = yield* fs + .readFileString(path.join(path.dirname(versionsDir), "launchers")) + .pipe(Effect.orElseSucceed(() => "")); + for (const shimPath of recorded.split(/\r?\n/)) { + if (path.isAbsolute(shimPath) && path.basename(shimPath).toLowerCase() === "t3.cmd") { + candidates.push({ shimPath, parseTarget: generatedWindowsShimTarget }); + } + } + } + for (const { shimPath, parseTarget } of candidates) { const contents = yield* fs.readFileString(shimPath).pipe(Effect.option); if (Option.isNone(contents)) continue; - const target = windowsShimTarget(contents.value); + const target = parseTarget(contents.value); if ( target !== undefined && path.resolve(target).toLowerCase() === path.resolve(executablePath).toLowerCase() diff --git a/apps/server/src/git/GitManager.test.ts b/apps/server/src/git/GitManager.test.ts index 7a0e7b30aea3b..f66235ce4e04a 100644 --- a/apps/server/src/git/GitManager.test.ts +++ b/apps/server/src/git/GitManager.test.ts @@ -1092,6 +1092,41 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("status of a repository without remotes runs no remote, provider or PR lookups", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + yield* runGit(repoDir, ["checkout", "-b", "feature/local-only"]); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const local = yield* manager.localStatus({ cwd: repoDir }); + const remote = yield* manager.remoteStatus({ cwd: repoDir }); + + expect(local.hasPrimaryRemote).toBe(false); + expect(local.sourceControlProvider).toBeUndefined(); + expect(remote?.pr ?? null).toBeNull(); + // Once git reports no remotes, remote URLs, branch remotes and remote refs cannot exist. + expect( + gitCommands.filter((args) => + /remote get-url|remote\.[^ ]+\.url|branch\.[^ ]+\.remote|refs\/remotes/.test(args), + ), + ).toEqual([]); + + // A remote added outside T3 Code shows on the next read. + yield* runGit(repoDir, [ + "remote", + "add", + "origin", + "https://github.com/pingdotgg/codething-mvp.git", + ]); + yield* TestClock.adjust("2 seconds"); + const afterRemote = yield* manager.localStatus({ cwd: repoDir }); + expect(afterRemote.hasPrimaryRemote).toBe(true); + expect(afterRemote.sourceControlProvider?.kind).toBe("github"); + }), + ); + it.effect("a git read in flight during a T3 git action does not outlive it", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -3399,6 +3434,12 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { const repoDir = yield* makeTempDir("t3code-git-manager-"); yield* initRepo(repoDir); yield* runGit(repoDir, ["checkout", "-b", "feature/status-open-over-merged"]); + yield* runGit(repoDir, [ + "remote", + "add", + "origin", + "https://github.com/pingdotgg/codething-mvp.git", + ]); const { manager } = yield* makeManager({ providerScenario: { @@ -3570,6 +3611,51 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { }), ); + it.effect("stages the worktree once for a typed commit message", () => + Effect.gen(function* () { + const repoDir = yield* makeTempDir("t3code-git-manager-"); + yield* initRepo(repoDir); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const gitCommands: string[] = []; + const { manager } = yield* makeManager({ gitCommands }); + + const created = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Typed subject\n\nTyped body", + }); + + expect(created.commit).toMatchObject({ status: "created", subject: "Typed subject" }); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(1); + expect((yield* runGit(repoDir, ["log", "-1", "--pretty=%B"])).stdout.trim()).toBe( + "Typed subject\n\nTyped body", + ); + + // Status shows the staged change, but staging the reverted worktree leaves nothing. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "staged\n"); + yield* runGit(repoDir, ["add", "README.md"]); + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "typed\n"); + const head = (yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout; + + const skipped = yield* runStackedAction(manager, { + cwd: repoDir, + action: "commit", + commitMessage: "Nothing to commit", + }); + + expect(skipped.commit.status).toBe("skipped_no_changes"); + expect((yield* runGit(repoDir, ["rev-parse", "HEAD"])).stdout).toBe(head); + expect((yield* runGit(repoDir, ["show", ":README.md"])).stdout).toBe("staged\n"); + + // A generated message already checked a scratch index, so staging again stays at two. + NodeFS.writeFileSync(NodePath.join(repoDir, "README.md"), "generated\n"); + gitCommands.length = 0; + const generated = yield* runStackedAction(manager, { cwd: repoDir, action: "commit" }); + expect(generated.commit.status).toBe("created"); + expect(gitCommands.filter((args) => args.endsWith("add -A"))).toHaveLength(2); + }), + ); + it.effect("lowercases a capitalized Conventional Commits description", () => Effect.gen(function* () { const repoDir = yield* makeTempDir("t3code-git-manager-"); @@ -4139,7 +4225,7 @@ it.layer(layerGitManagerTest)("GitManager", (it) => { ), ); yield* Deferred.await(gate.reached); - NodeFS.writeFileSync(NodePath.join(repoDir, ".git", "index.lock"), ""); + NodeFS.appendFileSync(NodePath.join(repoDir, ".git", "config"), "\n[broken\n"); yield* Deferred.succeed(gate.release, undefined); const result = yield* Fiber.join(action); diff --git a/apps/server/src/git/GitManager.ts b/apps/server/src/git/GitManager.ts index 0242234a013f4..85aec9b439df5 100644 --- a/apps/server/src/git/GitManager.ts +++ b/apps/server/src/git/GitManager.ts @@ -1286,7 +1286,7 @@ export const make = Effect.gen(function* () { .pipe( Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(nonRepositoryStatusDetails)), ); - const hostingProvider = details.isRepo + const hostingProvider = details.hasOriginRemote ? yield* resolveHostingProvider(cwd, details.branch) : null; @@ -1611,7 +1611,7 @@ export const make = Effect.gen(function* () { } const { pr, headSha } = - details.branch !== null + details.branch !== null && details.hasPrimaryRemote ? yield* lookupStatusPr( cwd, { @@ -2256,7 +2256,9 @@ export const make = Effect.gen(function* () { const finalStatus = result.action === "commit" ? null - : yield* gitCore.statusDetails(cwd).pipe(Effect.orElseSucceed(() => null)); + : yield* gitCore + .statusDetailsRemote(cwd, { refreshUpstream: false, includeAheadOfDefault: false }) + .pipe(Effect.orElseSucceed(() => null)); if (finalStatus?.branch) { finalBranchContext = { branch: finalStatus.branch, @@ -2494,7 +2496,13 @@ export const make = Effect.gen(function* () { } as GitActionProgressEvent) : Effect.void; - let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion; + const customCommit = parseCustomCommitMessage(commitMessage ?? ""); + let suggestion: CommitAndBranchSuggestion | null | undefined = + preResolvedSuggestion ?? + (customCommit && { + ...customCommit, + commitMessage: formatCommitMessage(customCommit.subject, customCommit.body), + }); if (!suggestion) { const needsGeneration = !commitMessage?.trim(); if (needsGeneration) { @@ -2566,11 +2574,20 @@ export const make = Effect.gen(function* () { }, } : null; - const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, { - timeoutMs: COMMIT_TIMEOUT_MS, - stage: filePaths ? { filePaths } : {}, - ...(commitProgress ? { progress: commitProgress } : {}), - }); + const committed = yield* gitCore + .commit(cwd, suggestion.subject, suggestion.body, { + timeoutMs: COMMIT_TIMEOUT_MS, + stage: { + ...(filePaths ? { filePaths } : {}), + ...(!preResolvedSuggestion && customCommit ? { unverified: true } : {}), + }, + ...(commitProgress ? { progress: commitProgress } : {}), + }) + .pipe(Effect.catchTags({ GitNothingToCommitError: () => Effect.succeed(null) })); + if (!committed) { + return { status: "skipped_no_changes" as const }; + } + const { commitSha } = committed; if (currentHookName !== null) { yield* emit({ kind: "hook_finished", diff --git a/apps/server/src/issue/IssueService.test.ts b/apps/server/src/issue/IssueService.test.ts index 231559e9eb4df..a291d5bee11f7 100644 --- a/apps/server/src/issue/IssueService.test.ts +++ b/apps/server/src/issue/IssueService.test.ts @@ -283,6 +283,24 @@ describe("IssueService", () => { yield* enterprise.resolveUrl("https://code.acme.test/acme/web/issues/7"), ).toMatchObject({ projectId: "ghes", host: "code.acme.test", key: "7", writable: true }); + // The same holds for a self-hosted Forgejo. + const forgejo = yield* makeService({ + projects: [ + project({ + id: "forge", + repository: "acme/web", + provider: "forgejo", + host: "code.acme.test", + }), + ], + trackers: [fakeTracker({ kind: IssueTrackerKind.make("forgejo") })], + }); + expect(yield* forgejo.resolveUrl("https://code.acme.test/acme/web/issues/7")).toMatchObject({ + projectId: "forge", + host: "code.acme.test", + key: "7", + }); + // A fork lists its upstream's issues and its own, counted once, and may write to both. const fork = project({ id: "fork", repository: "acme/web" }); const forked = yield* makeService({ diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index ec56c0c389a69..d79257944c8e9 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -9234,6 +9234,95 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("session/load replay does not leave post-settle background work pending", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* bundledMockAgentPath; + const instanceId = ProviderInstanceId.make("acp-test"); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + enablePostSettleContinuation: true, + normalizeToolCall: normalizeXAiAcpToolCallState, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + }), + }), + }, + continuationRequests: { offer: () => Effect.void }, + }); + const threadId = ThreadId.make("thread-acp-load-replay-background"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-load-replay-background"), + modelSelection, + runtimePolicy, + }); + if (runtime.hasPendingBackgroundWork === undefined) { + return yield* Effect.die("ACP runtime must expose hasPendingBackgroundWork."); + } + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + assert.isFalse(yield* runtime.hasPendingBackgroundWork); + assert.isDefined(sessionUpdateHandler, "session update handler must be wired"); + + // A large session/load replays its tail after the session is active. + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "old reply from history" }, + }, + }); + yield* sessionUpdateHandler!({ + sessionId: "mock-session-1", + _meta: { isReplay: true }, + update: { + sessionUpdate: "tool_call", + toolCallId: "replayed-tool-1", + title: "run_command", + kind: "execute", + status: "completed", + rawInput: { command: "echo old" }, + }, + }); + yield* Effect.yieldNow; + + assert.isFalse( + yield* runtime.hasPendingBackgroundWork, + "replayed history must not pin background work", + ); + const snapshot = yield* runtime.readThreadSnapshot({ providerThread }); + assert.deepEqual( + snapshot.messages.map((message) => message.text), + ["old reply from history"], + ); + }).pipe(Effect.provide(layerTest)), + ); + it.effect("projects completed-root carryover eagerly and drain cannot resurrect it", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; @@ -11680,6 +11769,97 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect("persists context usage the agent reports after its prompt settles", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const path = yield* Path.Path; + const selfInvocation = yield* resolveSelfInvocation(); + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + type RuntimeService = AcpSessionRuntime.AcpSessionRuntime["Service"]; + let sessionUpdateHandler: Parameters[0] | undefined; + const promptStarted = yield* Deferred.make(); + const promptGate = yield* Deferred.make(); + const instanceId = ProviderInstanceId.make("acp-test"); + const adapter = yield* makeAcpAdapterV2({ + instanceId, + selfInvocation, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ + childProcessSpawner, + mockAgentPath, + wrapRuntime: (runtime) => ({ + ...runtime, + handleSessionUpdate: (handler) => + Effect.sync(() => { + sessionUpdateHandler = handler; + }).pipe(Effect.andThen(runtime.handleSessionUpdate(handler))), + prompt: () => + Deferred.succeed(promptStarted, undefined).pipe( + Effect.andThen(Deferred.await(promptGate)), + ), + }), + }), + }, + }); + const threadId = ThreadId.make("thread-acp-late-usage"); + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-late-usage"), + modelSelection, + runtimePolicy, + }); + const events = yield* Queue.unbounded(); + yield* runtime.events.pipe( + Stream.runForEach((event) => Queue.offer(events, event)), + Effect.forkScoped, + ); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread, + instanceId, + runtimePolicy, + now: yield* DateTime.now, + }), + ) + .pipe(Effect.forkScoped); + yield* Deferred.await(promptStarted); + const update = (update: EffectAcpSchema.SessionUpdate) => + sessionUpdateHandler!({ sessionId: "mock-session-1", update }); + yield* update({ + sessionUpdate: "agent_message_chunk", + content: { type: "text", text: "OK" }, + }); + yield* Deferred.succeed(promptGate, { stopReason: "end_turn" }); + while ((yield* Queue.take(events)).type !== "turn.terminal"); + + // Kimi Code 2.6.2 sends its usage_update just after answering session/prompt. + yield* update({ sessionUpdate: "usage_update", used: 13101, size: 1048576 }); + let late: ProviderAdapter.ProviderAdapterV2Event; + do late = yield* Queue.take(events); + while (late.type !== "provider_thread.updated"); + assert.deepInclude(late.providerThread.contextUsage, { usedTokens: 13101 }); + // With no run left to receive it, only a session-scoped update reaches the projection. + assert.isTrue(late.sessionScoped); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.live("durably poisons start and resume when required hard teardown is unavailable", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 2ed84ecd1a51e..e1665b1bafb3e 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6325,6 +6325,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000002505", + text: "Build answer.", + }), + ); yield* harness.offerAndWait( claudeSdkFrame({ ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002500", result: "Built." }), @@ -6350,6 +6356,20 @@ describe("ClaudeAdapterV2 background wake turns", () => { (event) => event.type === "message.updated" && event.message.text === "Steer reply.", ); assert.equal(reply?.type === "message.updated" ? reply.message.runId : null, input.runId); + // Claude ended its native turn on this answer before it read the steer, so the timeline + // must not fold it away as a progress note of the run's last reply. + const answer = harness.events.findLast( + (event) => + event.type === "turn_item.updated" && + event.turnItem.type === "assistant_message" && + event.turnItem.text === "Build answer.", + ); + assert.equal( + answer?.type === "turn_item.updated" && answer.turnItem.type === "assistant_message" + ? answer.turnItem.phase + : null, + "final_answer", + ); assert.deepEqual( harness.events.flatMap((event) => event.type === "steer.updated" ? [[event.messageId, event.status]] : [], diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index df965d891487c..b120f9feb5e5a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5015,6 +5015,7 @@ function buildAssistantArtifacts(input: { readonly completedAt: DateTime.Utc; // A streamed message keeps its first timestamp across updates. readonly createdAt?: DateTime.Utc; + readonly finalAnswer?: boolean; }): { readonly node: OrchestrationV2ExecutionNode; readonly message: OrchestrationV2ConversationMessage; @@ -5089,6 +5090,7 @@ function buildAssistantArtifacts(input: { completedAt, updatedAt: input.completedAt, type: "assistant_message", + ...(input.finalAnswer === true ? { phase: "final_answer" as const } : {}), messageId, text: input.text, streaming, @@ -9333,6 +9335,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( readonly startedAt: DateTime.Utc; readonly completedAt: DateTime.Utc; readonly createdAt?: DateTime.Utc; + readonly finalAnswer?: boolean; }) { const ordinal = yield* resolveItemOrdinal(input.context, input.nativeItemId); const artifacts = buildAssistantArtifacts({ @@ -9346,6 +9349,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( startedAt: input.startedAt, completedAt: input.completedAt, ...(input.createdAt === undefined ? {} : { createdAt: input.createdAt }), + ...(input.finalAnswer === undefined ? {} : { finalAnswer: input.finalAnswer }), }); yield* Effect.all( [ @@ -12302,6 +12306,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( claudeEchoedPromptUuids(message).length > 0 ) { context.heldResult = message; + // Claude ended its native turn on this reply; the run continues only for the steer. + const answer = context.assistant.lastReply; + if (answer !== null) { + yield* publishAssistantArtifacts({ + context, + ...answer, + createdAt: answer.startedAt, + status: "completed", + completedAt, + finalAnswer: true, + }); + } return; } yield* finalizeActiveTurn({ diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.ts index e9f829524948b..d5b06dbf6c47f 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts @@ -252,6 +252,30 @@ it("steers a Grok follow-up into its running turn without restarting it", () => assert.isTrue(grok.turns.supportsActiveSteering); }); +// regression: #32606 a slash command steered into a running turn replaced the task +it.each([ + ["/compact", { type: "queue_after_active" }], + ["/context", { type: "queue_after_active" }], + [" /context all\n", { type: "queue_after_active" }], + ["/plugin:review-pr 12", { type: "queue_after_active" }], + ["/home/me/x.ts fails", { type: "steer_active", targetRunId: activeRunId }], + ["/ context", { type: "steer_active", targetRunId: activeRunId }], + ["$skill /context", { type: "steer_active", targetRunId: activeRunId }], +] as const)("steers %j only when it is not a slash command", (text, expected) => { + const projection = dispatchProjection(baseCapabilities); + for (const deliveryIntent of ["auto", "steer"] as const) { + assert.deepEqual( + CommandPolicy.resolveMessageDispatch(projection, { + dispatchMode: { type: "start_immediately" }, + deliveryIntent, + text, + attachments: [], + }), + expected, + ); + } +}); + it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => { const projection = dispatchProjection(baseCapabilities); const maintenance = { diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.ts index 451ca978b9e51..1319083cca030 100644 --- a/apps/server/src/orchestration-v2/CommandPolicy.ts +++ b/apps/server/src/orchestration-v2/CommandPolicy.ts @@ -10,6 +10,7 @@ import { ProviderInstanceId, ThreadId, } from "@t3tools/contracts"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { latestExecutedRun } from "@t3tools/shared/orchestrationV2ThreadError"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; @@ -101,6 +102,25 @@ export function goalCommandStopsActiveRun( } } +export function resolveMessageDispatch( + projection: OrchestrationV2ThreadProjection, + message: Pick< + Extract, + "dispatchMode" | "deliveryIntent" | "text" | "attachments" + >, +): MessageDispatchMode { + const mode = resolveMessageDispatchIntent( + projection, + message.dispatchMode, + message.deliveryIntent, + ); + // A provider runs a steered command in place of the turn's task, so commands wait. + return mode.type === "steer_active" && isSlashCommand(message) + ? { type: "queue_after_active" } + : mode; +} + +/** How a message joins active work when it is free to steer. */ export function resolveMessageDispatchIntent( projection: OrchestrationV2ThreadProjection, requestedMode: MessageDispatchMode, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 00939843c13f1..e27fe09d07d1b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -92,6 +92,7 @@ import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { outputRequestProblem } from "./runOutput.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { backgroundWorkHoldsCompletion, derivePendingBackgroundWork, @@ -126,6 +127,7 @@ import { isNativeMaintenanceCommand, providerSwitchWaitsForTurn, providerTurnCapabilities, + resolveMessageDispatch, resolveMessageDispatchIntent, } from "./CommandPolicy.ts"; import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts"; @@ -6308,6 +6310,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); } yield* ensureSteeringMessage(input.command, input); + // An explicit restart already gives up the turn, so only steering holds commands back. + if (!input.forceRestart && isSlashCommand(input)) { + return yield* new OrchestratorDispatchError({ + commandId: input.command.commandId, + commandType: input.command.type, + cause: + "Commands must run as a separate turn. Queue it or wait for the active turn to finish.", + }); + } const targetMessage = input.projection.messages.find( (message) => message.id === targetRun.userMessageId, ); @@ -7416,11 +7427,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = applyToProjection(projection, event); } let modelSelection = command.modelSelection ?? projection.thread.modelSelection; - let dispatchMode = resolveMessageDispatchIntent( - projection, - command.dispatchMode, - command.deliveryIntent, - ); + // Native goal commands must not steer an existing turn. + const parsedGoalCommand = parseGoalCommand(command); + const goalCommand = + parsedGoalCommand === null || + (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined + ? null + : parsedGoalCommand; + // A goal command keeps the run it was sent at; the goal handling below queues it. + let dispatchMode = + goalCommand === null + ? resolveMessageDispatch(projection, command) + : resolveMessageDispatchIntent(projection, command.dispatchMode, command.deliveryIntent); if (dispatchMode.type === "steer_active" || dispatchMode.type === "restart_active") { const targetRunId = dispatchMode.targetRunId; const target = projection.runs.find((run) => run.id === targetRunId); @@ -7515,13 +7533,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { dispatchMode = { type: "queue_after_active" }; } - // Native goal commands must not steer an existing turn. - const parsedGoalCommand = parseGoalCommand(command); - const goalCommand = - parsedGoalCommand === null || - (yield* goalDriverFor(command, modelSelection.instanceId)) === undefined - ? null - : parsedGoalCommand; let queuedRunStop: | { readonly runId: RunId; readonly reason: string; readonly skipsHeldQueue?: true } | undefined; @@ -7672,6 +7683,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const commandNotice = noticeKind === "command" && command.creationSource === "server"; if ( !freshContext && + // Steering refuses a command, so a notice that reads like one stays queued. + !isSlashCommand(command) && (delegatedCompletion !== undefined ? delegatedCompletion.taskIds.every( (id) => @@ -11856,8 +11869,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "A message that asks for a result can't steer the current turn.", }); } - if (goalCommand !== null) { - yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + // A steered command replaces the turn's task, so promoting one only moves it first. + if (goalCommand !== null || isSlashCommand(queuedMessage)) { + if (goalCommand !== null) { + yield* ensureGoalCommandSupported(command, queuedMessage, modelSelection.instanceId); + } const goal = projection.providerThreads.find( (candidate) => candidate.id === target?.providerThreadId, )?.goal; @@ -11871,6 +11887,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio payload: { ...queuedRun, queuePosition: 1 }, }); const stops = + goalCommand !== null && target !== undefined && isLiveRun(target) && goalCommandStopsActiveRun(goalCommand, goal?.status ?? null) && @@ -12298,6 +12315,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), }); } + // A command cannot steer, so an edit into one keeps it queued where it is. + if ( + queuedRun.steerWhenReadyRunId !== undefined && + isSlashCommand({ + text: command.text, + attachments: command.attachments ?? queuedMessage.attachments, + }) + ) { + const { steerWhenReadyRunId: _, ...queued } = queuedRun; + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: queued, + }); + } // Thread deletion only cleans files the thread still references. const keptAttachmentIds = new Set( (command.attachments ?? queuedMessage.attachments).map((attachment) => attachment.id), @@ -14182,7 +14218,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ); - /** Puts a queued goal command first and, given a target, stops the run in its way. */ + /** Puts a queued command first and, given a target, stops the run in its way. */ const stopRunForQueuedCommand = Effect.fn("Orchestrator.stopRunForQueuedCommand")( function* (input: { readonly command: Extract< diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index cc14fde257da8..3ef67192ceb77 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -711,14 +711,15 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* it.effect.each([ { notice: "delegated task question", goal: null, steers: true }, + { notice: "delegated task question", goal: null, steers: false, summary: "/review is ready" }, { notice: "background command", goal: "active", steers: true }, { notice: "background command", goal: null, steers: false }, ] as const)( "a $notice notice steers into the running turn: $steers (goal $goal)", - ({ notice, goal, steers }) => + ({ notice, goal, steers, ...row }) => Effect.gen(function* () { const { started, steered, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}`, + `notice-steer-${notice.replaceAll(" ", "-")}-${goal ?? "none"}-${steers}`, ); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -762,7 +763,7 @@ it.effect.each([ childThreadId: ThreadId.make("thread:question-child"), }, outcome: "updated" as const, - summary: "Delegated task has a question", + summary: "summary" in row ? row.summary : "Delegated task has a question", } : { source: { kind: "command" as const }, @@ -945,6 +946,7 @@ it.effect.each( const edited = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make("message:edited-steer"), )!; + assert.equal(edited.steerWhenReadyRunId, run.id); yield* orchestrator.dispatch({ type: "queued-run.edit", commandId: CommandId.make("edit-steer-to-compact"), @@ -952,6 +954,11 @@ it.effect.each( runId: edited.id, text: "/compact", }); + const compact = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === edited.id, + )!; + assert.isUndefined(compact.steerWhenReadyRunId); + assert.equal(compact.queuePosition, edited.queuePosition); } if (direct) { yield* orchestrator.dispatch({ @@ -998,16 +1005,18 @@ it.effect.each( const maintenance = (yield* orchestrator.getThreadProjection(threadId)).runs.find( (candidate) => candidate.userMessageId === MessageId.make(`message:${text}`), )!; - const error = yield* orchestrator - .dispatch({ - type: "queued-message.promote-to-steer", - commandId: CommandId.make(`promote-${text}`), - threadId, - queuedRunId: maintenance.id, - targetRunId: run.id, - }) - .pipe(Effect.flip); - assert.equal(error._tag, "OrchestratorDispatchError"); + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make(`promote-${text}`), + threadId, + queuedRunId: maintenance.id, + targetRunId: run.id, + }); + const promoted = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (candidate) => candidate.id === maintenance.id, + )!; + assert.equal(promoted.status, "queued"); + assert.equal(promoted.queuePosition, 1); } const command = { type: "queued-message.promote-to-steer" as const, @@ -3165,15 +3174,12 @@ it.effect.each([undefined, false, true])( const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; const threadId = yield* startFirstTurn; yield* send("queued", "queued", "queue"); - const sending = send("goal", "/goal all tests pass", "auto"); - if (nativeGoals === false) { - yield* Effect.flip(sending); - } else yield* sending; + yield* send("goal", "/goal all tests pass", "auto"); yield* worker.drain(); assert.deepEqual(steered, []); assert.deepEqual(yield* read(threadId), { - queue: ["queued"], + queue: nativeGoals === false ? ["queued", "/goal all tests pass"] : ["queued"], started: nativeGoals === false ? ["first"] : ["first", "/goal all tests pass"], stopRequested: nativeGoals !== false, }); @@ -3472,6 +3478,70 @@ it.effect("queues a goal clear without stopping work when no goal drives it", () }), ); +it.effect("promoting a queued /context moves it first and does not steer", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, send, read } = + yield* goalHarness("slash-promote"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* send("queued", "queued", "queue"); + yield* send("context", "/context", "queue"); + const queuedRun = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("message:context"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: queuedRun.id, + targetRunId: started[0]!.runId, + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: ["/context", "queued"], + started: ["first"], + stopRequested: false, + }); + }).pipe(Effect.provide(layer)); + }), +); + +it.effect("restarts the turn for a slash command sent as an explicit restart", () => + Effect.gen(function* () { + const { started, steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("slash-restart", true); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("restart-context"), + threadId, + messageId: MessageId.make("message:restart-context"), + text: "/context", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "restart_active", targetRunId: started[0]!.runId }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.lengthOf(interrupted, 1); + assert.deepEqual( + started.map((turn) => turn.message.text), + ["first", "/context"], + ); + }).pipe(Effect.provide(layer)); + }), +); + it.effect("promotes a queued goal by stopping the running turn", () => Effect.gen(function* () { const { started, steered, layer, startFirstTurn, send, read } = @@ -3504,6 +3574,38 @@ it.effect("promotes a queued goal by stopping the running turn", () => }), ); +it.effect("stops the running turn for a goal an agent steers into it", () => + Effect.gen(function* () { + const { started, steered, layer, startFirstTurn, read } = yield* goalHarness("goal-raw-steer"); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + // Agent sends carry a raw steer target and no delivery intent. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("goal"), + threadId, + messageId: MessageId.make("message:goal"), + text: "/goal ship it", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "steer_active", targetRunId: started[0]!.runId }, + createdBy: "agent", + creationSource: "server", + }); + yield* worker.drain(); + + assert.deepEqual(steered, []); + assert.deepEqual(yield* read(threadId), { + queue: [], + started: ["first", "/goal ship it"], + stopRequested: true, + }); + }).pipe(Effect.provide(layer)); + }), +); + // A fresh message skips compaction as its own turn, which steering a running turn would not. it.effect.each(["next", "/goal ship it", "fresh next"])( "promoting %s into a compaction stops it and sends it next", diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts index 2a3a8e5510550..73eaabdde2016 100644 --- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts @@ -913,7 +913,7 @@ it.effect("keeps native maintenance commands out of steering and restart message attachments: [], dispatchMode: { type: scenario.mode, targetRunId: targetRun.id }, }); - if (scenario.name.startsWith("steer-")) { + if (scenario.mode === "steer_active") { yield* dispatch; const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1]; assert.equal(queued?.status, "queued"); diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts index 96dd2c5dbaa44..0033755bfe706 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.test.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.test.ts @@ -435,8 +435,16 @@ it.layer(NodeServices.layer)("discoverAntigravitySkills", (it) => { yield* fileSystem.writeFileString( path.join(input.cwd, ".agents", "skills.json"), JSON.stringify({ + entries: null, + inherits: [{ path: "workspace-skills.json", include_only: null }], + }), + ); + yield* fileSystem.writeFileString( + path.join(input.cwd, "workspace-skills.json"), + JSON.stringify({ + inherits: null, entries: [ - { path: "tools/skills/deploy/SKILL.md" }, + { path: "tools/skills/deploy/SKILL.md", exclude: null }, { path: "tools/skills/internal/SKILL.md", exclude: ["internal"] }, ], }), diff --git a/apps/server/src/provider/Drivers/AntigravitySkills.ts b/apps/server/src/provider/Drivers/AntigravitySkills.ts index 51fd5535c8226..f69b3d1c455be 100644 --- a/apps/server/src/provider/Drivers/AntigravitySkills.ts +++ b/apps/server/src/provider/Drivers/AntigravitySkills.ts @@ -48,14 +48,14 @@ const SkillFrontmatter = Schema.Struct({ const decodeSkillFrontmatter = Schema.decodeUnknownSync(SkillFrontmatter); const SkillConfigEntry = Schema.Struct({ path: Schema.String, - include_only: Schema.optional(Schema.Array(Schema.String)), - exclude: Schema.optional(Schema.Array(Schema.String)), + include_only: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), + exclude: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))), }); const decodeSkillsConfig = Schema.decodeUnknownOption( Schema.fromJsonString( Schema.Struct({ - inherits: Schema.optional(Schema.Array(SkillConfigEntry)), - entries: Schema.optional(Schema.Array(SkillConfigEntry)), + inherits: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), + entries: Schema.optional(Schema.NullOr(Schema.Array(SkillConfigEntry))), }), ), ); @@ -289,10 +289,7 @@ function matchesSkillFilter(entry: string, filter: SkillEntryFilter): boolean { function narrowSkillFilter( parent: SkillEntryFilter, - entry: { - readonly include_only?: ReadonlyArray | undefined; - readonly exclude?: ReadonlyArray | undefined; - }, + entry: typeof SkillConfigEntry.Type, ): SkillEntryFilter { const includeGroups = entry.include_only && entry.include_only.length > 0 diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts index d0def84f1efe0..88e076d98f208 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.test.ts @@ -383,6 +383,9 @@ describe("readAntigravityUsage", () => { "gemini-3-flash-agent", "gemini-3-flash", "gemini-default", + "gemini-pro-orchestrator-neon", + "gemini-4-hydrogen-orchestrator", + "gemini-pro-orchestrator-g1-pro", ].entries()) { yield* db.run("INSERT INTO gen_metadata VALUES (?, ?)", [ idx, @@ -393,6 +396,11 @@ describe("readAntigravityUsage", () => { new Uint8Array(protoBytes(9, protoNumber(2, 10 + idx))), ]); } + // Orchestrator (Neon), MODEL_PLACEHOLDER_M537, with no name in the metadata. + yield* db.run("INSERT INTO steps VALUES (?, ?)", [ + 20, + new Uint8Array(protoBytes(9, [...protoNumber(1, 1537), ...protoNumber(2, 30)])), + ]); }), ); const result = yield* readAntigravityUsage(dir, 0); @@ -405,6 +413,10 @@ describe("readAntigravityUsage", () => { ["gemini-3-flash-agent", "gemini-3.5-flash"], ["gemini-3-flash", "gemini-3-flash-preview"], ["gemini-default", undefined], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], + ["gemini-4-hydrogen-orchestrator", "gemini-4-hydrogen"], + ["gemini-pro-orchestrator-g1-pro", "gemini-4-argon"], + ["gemini-pro-orchestrator-neon", "gemini-4-neon"], ], ); }).pipe(Effect.provide(NodeServices.layer)), diff --git a/apps/server/src/provider/Drivers/antigravityUsageReader.ts b/apps/server/src/provider/Drivers/antigravityUsageReader.ts index 4a71c8ed2b056..5dff65928ad24 100644 --- a/apps/server/src/provider/Drivers/antigravityUsageReader.ts +++ b/apps/server/src/provider/Drivers/antigravityUsageReader.ts @@ -126,18 +126,26 @@ const MODEL_IDS: Record = { 1417: "gemini-4-argon", 1418: "gemini-4-argon", 1419: "gemini-4-argon", + 1537: "gemini-pro-orchestrator-neon", }; // Effort and routing variants share the base model's price. export const antigravityRateModel = (model: string) => { - const base = model.replace(/-(?:extra-low|low|medium|high|tiered|control|thinking|agent)$/, ""); + const base = model.replace( + /-(?:extra-low|low|medium|high|tiered|control|thinking|agent|orchestrator)$/, + "", + ); return /^gemini-3-flash-(?:agent(?:-[ab])?|[ab])$/.test(model) ? "gemini-3.5-flash" : model === "gemini-3.7-flash-safety-le" ? "gemini-3.7-flash" - : base === "gemini-3-flash" - ? "gemini-3-flash-preview" - : base; + : model === "gemini-pro-orchestrator-neon" + ? "gemini-4-neon" + : model === "gemini-pro-orchestrator-g1-pro" + ? "gemini-4-argon" + : base === "gemini-3-flash" + ? "gemini-3-flash-preview" + : base; }; function withRateModel(record: UsageRecord): UsageRecord { diff --git a/apps/server/src/sourceControl/sourceControlDefinitions.ts b/apps/server/src/sourceControl/sourceControlDefinitions.ts index 670047ccae618..c6a770a897f02 100644 --- a/apps/server/src/sourceControl/sourceControlDefinitions.ts +++ b/apps/server/src/sourceControl/sourceControlDefinitions.ts @@ -1,11 +1,18 @@ import * as AzureDevOpsDriver from "@t3tools/source-control-azure-devops/server/driver"; import * as BitbucketDriver from "@t3tools/source-control-bitbucket/server/driver"; import * as CursorOriginDriver from "@t3tools/source-control-cursor-origin/server/driver"; -import { builtInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; +import { makeBuiltInSourceControlDefinitions } from "@t3tools/source-control-definitions/registry"; import * as ForgejoDriver from "@t3tools/source-control-forgejo/server/driver"; import * as GitCafeDriver from "@t3tools/source-control-gitcafe/server/driver"; import * as GitHubDriver from "@t3tools/source-control-github/server/driver"; import * as GitLabDriver from "@t3tools/source-control-gitlab/server/driver"; +import * as TanStackSourceDriver from "@t3tools/source-control-tanstack-source/server/driver"; + +/** + * TanStack Source is in private beta, so its forge exists only on a server started with + * `T3CODE_TANSTACK_SOURCE=1`. Read once at load: the registry below is a module constant. + */ +const tanStackSourceEnabled = process.env.T3CODE_TANSTACK_SOURCE?.trim() === "1"; /** In the shared registry's order, which is the order hosts are listed and probed in. */ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ @@ -13,12 +20,15 @@ export const BUILT_IN_SOURCE_CONTROL_DRIVER_LIST = [ CursorOriginDriver.driver, GitLabDriver.driver, GitCafeDriver.driver, + ...(tanStackSourceEnabled ? [TanStackSourceDriver.driver] : []), ForgejoDriver.driver, BitbucketDriver.driver, AzureDevOpsDriver.driver, -] as const; +]; -export const sourceControlDefinitions = builtInSourceControlDefinitions; +export const sourceControlDefinitions = makeBuiltInSourceControlDefinitions({ + tanStackSource: tanStackSourceEnabled, +}); /** A host CLI command that merges or closes a change request, such as `gh pr merge`. */ export const isChangeRequestCloseCommand = (command: string) => diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index f2a7ce31e920a..f341ebd987a6c 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -10,6 +10,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 Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; import { @@ -76,6 +77,19 @@ export interface ExecuteGitResult { readonly stderrTruncated: boolean; } +export class GitNothingToCommitError extends Schema.TaggedError()( + "GitNothingToCommitError", + { + operation: Schema.String, + cwd: Schema.String, + detail: Schema.String, + }, +) { + override get message(): string { + return `Nothing to commit in ${this.operation} (${this.cwd}): ${this.detail}`; + } +} + export interface GitStatusDetails { isRepo: boolean; sourceControlProvider?: VcsStatusResult["sourceControlProvider"]; @@ -99,6 +113,7 @@ export interface GitLocalStatusOptions { export interface GitRemoteStatusDetails { isRepo: boolean; + hasPrimaryRemote: boolean; defaultBranch: string | null; isDefaultBranch: boolean; branch: string | null; @@ -172,7 +187,11 @@ export interface GitCommitProgress { export interface GitCommitOptions { readonly timeoutMs?: number; readonly progress?: GitCommitProgress; - readonly stage?: { readonly filePaths?: readonly string[] }; + readonly stage?: { + readonly filePaths?: readonly string[]; + /** The caller has not run `prepareCommitContext`, so an empty result must keep the index. */ + readonly unverified?: boolean; + }; } export interface GitDeleteLocalBranchInput { @@ -318,6 +337,8 @@ export interface GitSetBranchUpstreamInput { export interface GitRemoteStatusOptions { readonly refreshUpstream?: boolean; + /** False skips the base-branch lookup and reports `aheadOfDefaultCount` as 0. */ + readonly includeAheadOfDefault?: boolean; } /** @@ -360,7 +381,7 @@ export class GitVcsDriver extends Context.Service< subject: string, body: string, options?: GitCommitOptions, - ) => Effect.Effect<{ commitSha: string }, GitCommandError>; + ) => Effect.Effect<{ commitSha: string }, GitCommandError | GitNothingToCommitError>; readonly pushCurrentBranch: ( cwd: string, fallbackBranch: string | null, diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index a5ec6a0d05413..b25e0ff2a8f64 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -865,6 +865,22 @@ it.effect.each(["on a branch", "detached", "unborn"] as const)( assert.deepStrictEqual(discoveries(), branchRead); if (state !== "detached") assert.equal(headRef(afterCheckout), "outside-checkout"); + // A file read under that preview reuses its merge base instead of resolving it again. + const branchFile = yield* driver.getReviewDiffPreview({ + cwd, + mergeBase: afterCheckout.sources.find((entry) => entry.kind === "branch-range")! + .mergeBase!, + file: { path: "new.txt", previousPath: null, sourceKind: "branch-range" }, + }); + assert.isFalse(spawnedArgs.some((args) => args.includes("merge-base"))); + assert.deepStrictEqual(discoveries(), warm); + assert.deepStrictEqual( + branchFile.sources + .find((source) => source.kind === "branch-range")! + .files!.map((file) => file.path), + ["new.txt"], + ); + yield* driver.getReviewBranchCommits({ cwd }); assert.deepStrictEqual(discoveries(), branchRead); @@ -885,7 +901,7 @@ it.effect("resolves a branch's base once while its refs and branch config are un const spawner = ChildProcessSpawner.make((command) => { if (!ChildProcess.isStandardCommand(command)) return delegate.spawn(command); spawnedArgs.push(command.args.map(String)); - return failRemoteLookup && command.args[0] === "remote" + return failRemoteLookup && command.args.includes("remote") ? Effect.fail( PlatformError.systemError({ _tag: "Unknown", @@ -916,9 +932,39 @@ it.effect("resolves a branch's base once while its refs and branch config are un // One thread switch: two local status reads and the two diff preview passes. yield* driver.statusDetailsLocal(cwd); yield* driver.statusDetailsLocal(cwd); - yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); - yield* driver.getReviewDiffPreview({ cwd }); + const tracked = yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); + assert.isDefined(tracked.completionToken); assert.equal(lookups(), 1); + // The complete pass adds only the untracked listing to the tracked pass it follows. + const complete = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: tracked.completionToken!, + }); + assert.deepStrictEqual( + spawnedArgs.map((args) => args.find((arg) => !arg.startsWith("-") && !arg.includes("="))), + ["ls-files"], + ); + assert.isUndefined(complete.incomplete); + assert.deepStrictEqual(complete.sources, tracked.sources); + spawnedArgs.length = 0; + // A token is used once, and untracked files are still diffed when there are some. + yield* writeTextFile(cwd, "untracked.txt", "untracked\n"); + const second = yield* driver.getReviewDiffPreview({ cwd, trackedOnly: true }); + const withUntracked = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: second.completionToken!, + }); + assert.include( + withUntracked.sources.flatMap((source) => source.files?.map((file) => file.path) ?? []), + "untracked.txt", + ); + const reused = yield* driver.getReviewDiffPreview({ + cwd, + completionToken: tracked.completionToken!, + }); + assert.deepStrictEqual(reused.sources, withUntracked.sources); + yield* (yield* FileSystem.FileSystem).remove(`${cwd}/untracked.txt`); + spawnedArgs.length = 0; yield* git(cwd, ["config", "branch.feature/x.t3-merge-base-ref", "refs/heads/main"]); yield* driver.statusDetailsLocal(cwd); @@ -1584,6 +1630,56 @@ describe("pullCurrentBranch", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("does not scan the working tree to pull", () => + Effect.gen(function* () { + const { cwd, initialBranch, remoteHead } = yield* cloneBehindRemote; + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + const spawnedArgs: Array> = []; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command)) spawnedArgs.push(command.args.map(String)); + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + // The status broadcast after a pull re-reads the working tree for the UI. + assert.deepEqual( + spawnedArgs.filter((args) => args.includes("status") || args.includes("--numstat")), + [], + ); + }).pipe(Effect.provide(layerTest)), + ); + + it.effect("pulls into an unborn branch that tracks an unfetched upstream", () => + Effect.gen(function* () { + const { remote, initialBranch, remoteHead } = yield* cloneBehindRemote; + const cwd = yield* makeTmpDir(); + yield* git(cwd, ["init", "--initial-branch", initialBranch]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["config", `branch.${initialBranch}.remote`, "origin"]); + yield* git(cwd, ["config", `branch.${initialBranch}.merge`, `refs/heads/${initialBranch}`]); + const driver = yield* makeGitVcsDriverCore(); + + const result = yield* driver.pullCurrentBranch(cwd); + + assert.deepEqual(result, { + status: "pulled", + refName: initialBranch, + upstreamRef: `origin/${initialBranch}`, + }); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), remoteHead); + }).pipe(Effect.provide(layerTest)), + ); + it.effect.each([false, true])( "pulls past an unrelated lock with custom fetch mapping=%s", (customMapping) => @@ -3417,7 +3513,12 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const scoped = yield* driver.getReviewDiffPreview({ cwd: projectDirectory, baseRef: initialBranch, - file: { path: file.path, previousPath: file.previousPath, sourceKind: source.kind }, + file: { + path: file.path, + previousPath: file.previousPath, + sourceKind: source.kind, + ...(file.changeType ? { changeType: file.changeType } : {}), + }, }); const patch = scoped.sources.find((item) => item.kind === source.kind)!; assert.deepStrictEqual(patch.files, [file]); @@ -3428,6 +3529,53 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "lists untracked files for a file the preview called tracked only when it is not", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* writeTextFile(cwd, "tracked.txt", "one\n"); + yield* git(cwd, ["add", "."]); + yield* git(cwd, ["commit", "-m", "tracked"]); + yield* writeTextFile(cwd, "tracked.txt", "two\n"); + yield* writeTextFile(cwd, "README.md", "dirty\n"); + const delegate = yield* ChildProcessSpawner.ChildProcessSpawner; + let listings = 0; + const spawner = ChildProcessSpawner.make((command) => { + if (ChildProcess.isStandardCommand(command) && command.args.includes("--others")) { + listings++; + } + return delegate.spawn(command); + }); + const driver = yield* makeGitVcsDriverCore().pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), + ); + const read = (path: string, changeType?: "change") => + driver + .getReviewDiffPreview({ + cwd, + file: { + path, + previousPath: null, + sourceKind: "working-tree", + ...(changeType ? { changeType } : {}), + }, + }) + .pipe(Effect.map((preview) => preview.sources[0]!)); + + const tracked = yield* read("tracked.txt", "change"); + assert.include(tracked.diff, "+two"); + assert.equal(listings, 0); + + // A stale hint: the file left the index after the preview listed it. + yield* git(cwd, ["rm", "--cached", "-q", "README.md"]); + const stale = yield* read("README.md", "change"); + assert.equal(listings, 1); + assert.deepStrictEqual(stale, yield* read("README.md")); + }), + ); + it.effect("rejects a file selector for a different source than the request", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); @@ -3879,10 +4027,18 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { } const preview = yield* driver.getReviewDiffPreview({ cwd, ignoreWhitespace: false }); - const diff = preview.sources.find((source) => source.kind === "working-tree")?.diff ?? ""; + const source = preview.sources.find((candidate) => candidate.kind === "working-tree")!; + const [file] = source.files ?? []; + const single = yield* driver.getReviewDiffPreview({ + cwd, + sourceKind: "working-tree", + file: { path: file!.path, previousPath: file!.previousPath, sourceKind: source.kind }, + }); - for (const text of expected) assert.include(diff, text); - assert.notInclude(diff, "new file mode"); + for (const diff of [source.diff, single.sources[0]!.diff]) { + for (const text of expected) assert.include(diff, text); + assert.notInclude(diff, "new file mode"); + } }), ); @@ -4117,6 +4273,7 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { const request = yield* decodeReviewDiffPreviewInput({ cwd, baseRef: initialBranch, + mergeBase: branch.mergeBase!, file: { path, previousPath: stat.previousPath, sourceKind: "branch-range" }, }); const result = yield* driver.getReviewDiffPreview(request); @@ -4193,6 +4350,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { ]); assert.include(dirty.diff, "b/staged.txt"); assert.include(dirty.diff, "b/untracked.txt"); + const single = yield* driver.getReviewDiffPreview({ + cwd, + sourceKind: "working-tree", + file: { path: "untracked.txt", previousPath: null, sourceKind: "working-tree" }, + }); + assert.deepStrictEqual(single.sources[0]!.files, dirty.files!.slice(1)); + assert.include(single.sources[0]!.diff, "b/untracked.txt"); }), ); @@ -7743,6 +7907,23 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect("reports a rename as done when Git moved the ref but kept the config locked", () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + yield* initRepoWithCommit(cwd); + yield* git(cwd, ["checkout", "-b", "t3/abcd1234"]); + yield* writeTextFile(cwd, ".git/config.lock", ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + const renamed = yield* TestClock.withLive( + driver.renameBranch({ cwd, oldBranch: "t3/abcd1234", newBranch: "t3/fix-login" }), + ); + + assert.equal(renamed.branch, "t3/fix-login"); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), "t3/fix-login"); + }), + ); + it.effect.each([false, true])( "cleans up links left by successful worktree removal, preserving ordinary files: %s", (keepFile) => @@ -8559,6 +8740,17 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.notInclude(context?.stagedSummary ?? "", "b.txt"); assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); + // A selected file staged and then reverted stages to nothing, like git commit --only. + const head = yield* git(repository, ["rev-parse", "HEAD"]); + yield* writeTextFile(repository, "README.md", "staged\n"); + yield* git(repository, ["add", "README.md"]); + yield* git(repository, ["restore", "--source=HEAD", "--worktree", "--", "README.md"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["README.md"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(repository, ["rev-parse", "HEAD"]), head); + const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: [selected] }, }); @@ -8778,6 +8970,8 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { // A branch named MERGE_HEAD is not a merge in progress. yield* git(cwd, ["branch", "MERGE_HEAD"]); assert.isNull(yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false })); + const empty = yield* driver.commit(cwd, "Empty", "", { stage: {} }).pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); yield* git(cwd, ["branch", "-D", "MERGE_HEAD"]); yield* git(cwd, ["checkout", "-b", "feature"]); yield* writeTextFile(cwd, "README.md", "feature version\n"); @@ -8797,6 +8991,13 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { assert.isNotNull( yield* driver.prepareCommitContext(cwd, undefined, { includePatch: false }), ); + const mainHead = yield* git(cwd, ["rev-parse", "HEAD"]); + const featureHead = yield* git(cwd, ["rev-parse", "feature"]); + yield* driver.commit(cwd, "Merge feature", "", { stage: {} }); + assert.equal( + yield* git(cwd, ["show", "-s", "--format=%P", "HEAD"]), + `${mainHead} ${featureHead}`, + ); }), ); @@ -8942,6 +9143,9 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { yield* writeTextFile(cwd, "README.md", "stashed version\n"); yield* git(cwd, ["stash"]); yield* writeTextFile(cwd, "README.md", "committed version\n"); + yield* writeTextFile(cwd, "same.txt", "same\n"); + yield* writeTextFile(cwd, "gone.txt", "gone\n"); + yield* git(cwd, ["add", "same.txt", "gone.txt"]); yield* git(cwd, ["commit", "-am", "Change README"]); const pop = yield* driver.execute({ operation: "test.stashPop", @@ -8950,9 +9154,29 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { allowNonZeroExit: true, }); assert.equal(pop.exitCode, 1); + const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); + + // A selected file staged and then reverted has nothing to commit despite the conflict. + const unchangedHead = yield* git(cwd, ["rev-parse", "HEAD"]); + yield* writeTextFile(cwd, "same.txt", "staged\n"); + yield* git(cwd, ["add", "same.txt"]); + yield* git(cwd, ["restore", "--source=HEAD", "--worktree", "--", "same.txt"]); + const empty = yield* driver + .commit(cwd, "Empty", "", { stage: { filePaths: ["same.txt"] } }) + .pipe(Effect.flip); + assert.equal(empty._tag, "GitNothingToCommitError"); + assert.equal(yield* git(cwd, ["rev-parse", "HEAD"]), unchangedHead); + assert.equal(yield* git(cwd, ["ls-files", "--unmerged"]), unmerged); + + yield* (yield* FileSystem.FileSystem).remove((yield* Path.Path).join(cwd, "gone.txt")); + yield* driver.commit(cwd, "Remove gone", "", { stage: { filePaths: ["gone.txt"] } }); + assert.equal( + yield* git(cwd, ["show", "--pretty=", "--name-status", "HEAD"]), + "D\tgone.txt", + ); + yield* writeTextFile(cwd, "other.txt", "other\n"); const head = yield* git(cwd, ["rev-parse", "HEAD"]); - const unmerged = yield* git(cwd, ["ls-files", "--unmerged"]); const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const nested = path.join(cwd, "nested"); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 6e7725833c022..4356de894f0b4 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -94,6 +94,8 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_METADATA_MAX_OUTPUT_BYTES = 16 * 1024 * 1024; // Temporary-index git add scales poorly (50k files took ~30 s); report incomplete totals above this cap. const REVIEW_UNTRACKED_MAX_FILES = 5_000; +const REVIEW_TRACKED_PREVIEW_CAPACITY = 16; +const REVIEW_TRACKED_PREVIEW_TTL_MS = 30_000; // git diff reads every untracked byte (~5 ms/MB), so larger untracked input stays out of the review index. const REVIEW_UNTRACKED_MAX_BYTES = 256 * 1024 * 1024; // The listing walks the whole untracked tree before the cap applies, so a folder whose listing @@ -162,6 +164,7 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze({ isRepo: false, + hasPrimaryRemote: false, defaultBranch: null, isDefaultBranch: false, branch: null, @@ -1841,8 +1844,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), { capacity: 2_048, + // A remote added outside T3 Code must show on the next status read, so only a hit is kept. timeToLive: Exit.match({ - onSuccess: () => STATUS_ORIGIN_EXISTS_CACHE_TTL, + onSuccess: (exists) => (exists ? STATUS_ORIGIN_EXISTS_CACHE_TTL : Duration.zero), onFailure: () => Duration.zero, }), }, @@ -1966,25 +1970,31 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* Effect.orElseSucceed(() => null), ); + // Returns the upstream remote name it read, or undefined when it did not read one. const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* ( cwd: string, + knownHeadRef?: string, ) { - if (Duration.isZero(yield* automaticFetchInterval)) return; - const headRef = yield* runGitStdout( - "GitVcsDriver.refreshStatusUpstreamIfStale.headRef", - cwd, - ["symbolic-ref", "--quiet", "HEAD"], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); - if (headRef.length === 0) return; - const remoteName = yield* runGitStdout( + if (Duration.isZero(yield* automaticFetchInterval)) return undefined; + const headRef = + knownHeadRef ?? + (yield* runGitStdout( + "GitVcsDriver.refreshStatusUpstreamIfStale.headRef", + cwd, + ["symbolic-ref", "--quiet", "HEAD"], + true, + ).pipe(Effect.map((stdout) => stdout.trim()))); + if (headRef.length === 0) return undefined; + const upstreamRemote = yield* executeGit( "GitVcsDriver.refreshStatusUpstreamIfStale.upstreamRemote", cwd, ["for-each-ref", "--format=%(upstream:remotename)", headRef], - true, - ).pipe(Effect.map((stdout) => stdout.trim())); + { allowNonZeroExit: true }, + ); + if (upstreamRemote.exitCode !== 0) return undefined; + const remoteName = upstreamRemote.stdout.trim(); // Empty means no upstream; `.` means the upstream is a local branch. - if (remoteName.length === 0 || remoteName === ".") return; + if (remoteName.length === 0 || remoteName === ".") return remoteName; const gitCommonDir = yield* resolveGitCommonDir(cwd); yield* Cache.get( statusRemoteRefreshCache, @@ -1994,6 +2004,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // The cache returns after five seconds while the fetch keeps running. const pending = statusFetches.get(`${gitCommonDir}\0${remoteName}`); if (pending) yield* Fiber.await(pending.fiber); + return remoteName; }); const resolveDefaultBranchName = ( @@ -2063,9 +2074,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return parsedRemoteRef?.branchName ?? branchName; }); + const hasAnyRemote = (cwd: string) => + resolveRepositoryPaths(cwd).pipe( + Effect.orElseSucceed(() => null), + Effect.flatMap((paths) => + paths === null + ? listRemoteNames(cwd).pipe(Effect.map((remoteNames) => remoteNames.length > 0)) + : Cache.get(primaryRemoteExistsCache, paths.gitCommonDir), + ), + ); + // Local-only repositories are normal and status polls them, so the span succeeds with null. // Callers that need a remote fail in their own span. const findPrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) { + if (!(yield* hasAnyRemote(cwd))) { + return null; + } if (yield* originRemoteExists(cwd)) { return "origin"; } @@ -2513,7 +2537,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return Number.isFinite(parsed) ? Math.max(0, parsed) : 0; }); - const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) { + const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* ( + cwd: string, + refreshUpstream: boolean, + includeAheadOfDefault = true, + ) { const branchResult = yield* executeGitWithStableDiagnostics( "GitVcsDriver.statusDetailsRemote.branch", cwd, @@ -2530,6 +2558,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return NON_REPOSITORY_REMOTE_STATUS_DETAILS; } let branch: string | null; + let headRef: string; if (branchResult.exitCode !== 0) { if (isNonRepositoryGitStderr(branchResult.stderr)) { return NON_REPOSITORY_REMOTE_STATUS_DETAILS; @@ -2554,10 +2583,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ["symbolic-ref", "--quiet", "HEAD"], ); branch = branchNameFromHeadRef(branchValue); + // An unborn branch has no ref, so for-each-ref below cannot report its upstream. + headRef = ""; } else { branch = branchNameFromHeadRef(branchResult.stdout); + headRef = branchResult.stdout.trim(); + } + let upstreamRemoteName: string | undefined; + if (refreshUpstream) { + // A detached HEAD prints `HEAD`, which has no upstream to refresh. + yield* refreshStatusUpstreamIfStale(cwd, headRef.startsWith("refs/") ? headRef : "").pipe( + Effect.map((remoteName) => { + upstreamRemoteName = remoteName; + }), + Effect.catchTags({ + GitCommandError: (error) => + isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), + }), + Effect.ignoreCause({ log: true }), + ); } - const currentUpstreamRef = yield* readCurrentUpstreamRef(cwd); + // `%(upstream:remotename)` is empty exactly when `@{upstream}` does not resolve. + const currentUpstreamRef = + upstreamRemoteName === "" ? null : yield* readCurrentUpstreamRef(cwd); let upstreamRef = currentUpstreamRef; // Trimming a remote that starts with Unicode whitespace can leave a leading slash. if (currentUpstreamRef?.startsWith("/")) { @@ -2586,13 +2634,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); } - const defaultBranch = yield* resolvePrimaryDefaultBranchName(cwd); + const hasPrimaryRemote = yield* hasAnyRemote(cwd); + const defaultBranch = hasPrimaryRemote ? yield* resolvePrimaryDefaultBranchName(cwd) : null; const isDefaultBranch = branch !== null && (branch === defaultBranch || (defaultBranch === null && (branch === "main" || branch === "master"))); const aheadOfDefaultCount = - branch && !isDefaultBranch + branch && !isDefaultBranch && includeAheadOfDefault ? upstreamRef === null ? aheadCount : yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0)) @@ -2600,6 +2649,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { isRepo: true, + hasPrimaryRemote, defaultBranch, isDefaultBranch, branch, @@ -2721,7 +2771,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, ); // diff-index does not read status output, so both spawn together; a non-repository discards it. - const [statusResult, numstatResult, defaultBranch, hasPrimaryRemote] = yield* Effect.all( + const [statusResult, numstatResult, [hasPrimaryRemote, defaultBranch]] = yield* Effect.all( [ readStatus, readNumstat("HEAD").pipe( @@ -2747,17 +2797,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }), Effect.result, ), - statusCacheKey - ? Cache.get(defaultBranchCache, statusCacheKey).pipe(Effect.orElseSucceed(() => null)) - : resolvePrimaryDefaultBranchName(cwd).pipe(Effect.orElseSucceed(() => null)), - statusCacheKey - ? Cache.get(primaryRemoteExistsCache, statusCacheKey).pipe( - Effect.orElseSucceed(() => false), - ) - : listRemoteNames(cwd).pipe( - Effect.map((remoteNames) => remoteNames.length > 0), - Effect.orElseSucceed(() => false), + (statusCacheKey + ? Cache.get(primaryRemoteExistsCache, statusCacheKey) + : listRemoteNames(cwd).pipe(Effect.map((remoteNames) => remoteNames.length > 0)) + ).pipe( + Effect.orElseSucceed(() => false), + Effect.flatMap((hasRemote) => + (hasRemote + ? statusCacheKey + ? Cache.get(defaultBranchCache, statusCacheKey) + : resolvePrimaryDefaultBranchName(cwd) + : Effect.succeed(null) + ).pipe( + Effect.orElseSucceed(() => null), + Effect.map((defaultBranch) => [hasRemote, defaultBranch] as const), ), + ), + ), ], { concurrency: "unbounded" }, ); @@ -2949,31 +3005,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return yield* readStatusDetailsLocal(cwd, options); }); - const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( - "statusDetails", - )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( + const refreshStatusUpstream = (cwd: string) => + refreshStatusUpstreamIfStale(cwd).pipe( Effect.catchTags({ GitCommandError: (error) => isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), }), Effect.ignoreCause({ log: true }), ); + + const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( + "statusDetails", + )(function* (cwd) { + yield* refreshStatusUpstream(cwd); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { - if (options?.refreshUpstream !== false) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), - }), - Effect.ignoreCause({ log: true }), - ); - } - return yield* readStatusDetailsRemote(cwd); + return yield* readStatusDetailsRemote( + cwd, + options?.refreshUpstream !== false, + options?.includeAheadOfDefault !== false, + ); }); const status: GitVcsDriver.GitVcsDriver["Service"]["status"] = (input) => @@ -3353,10 +3407,81 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* body, options?: GitVcsDriver.GitCommitOptions, ) { + const diffCached = [ + "-c", + "diff.relative=false", + "diff", + "--cached", + "--no-ext-diff", + "--no-textconv", + ]; + if (options?.stage?.unverified) { + const indexMatchesHead = + (yield* executeGit("GitVcsDriver.commit.indexChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode === 0; + // Staging an empty result would overwrite what is already staged, so check a scratch index. + if ( + !indexMatchesHead && + (yield* prepareCommitContext(cwd, options.stage.filePaths, { includePatch: false })) === + null + ) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const partialCommitPaths = options?.stage !== undefined ? yield* stageCommitChanges(cwd, options.stage.filePaths) : undefined; + // Preserved unselected conflicts always show as index changes, so only selected paths count. + const selectedPaths = partialCommitPaths && new Set(options?.stage?.filePaths); + const hasStagedChanges = selectedPaths + ? (yield* runGitStdoutWithOptions( + "GitVcsDriver.commit.stagedChanges", + cwd, + [...diffCached, "--no-renames", "--name-only", "-z"], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + )) + .split("\0") + .some((file) => file.length > 0 && selectedPaths.has(file)) + : (yield* executeGit("GitVcsDriver.commit.stagedChanges", cwd, [...diffCached, "--quiet"], { + allowNonZeroExit: true, + })).exitCode !== 0; + if (!hasStagedChanges) { + // Like git commit, a merge resolved to HEAD's tree still records its merge commit. + const mergeHeadPath = yield* runGitStdout("GitVcsDriver.commit.mergeHead", cwd, [ + "rev-parse", + "--git-path", + "MERGE_HEAD", + ]); + const merging = yield* fileSystem.realPath(cwd).pipe( + Effect.orElseSucceed(() => cwd), + Effect.flatMap((physicalCwd) => + fileSystem.exists(path.resolve(physicalCwd, mergeHeadPath.trim())), + ), + Effect.mapError( + (cause) => + new GitCommandError({ + operation: "GitVcsDriver.commit.mergeHead", + command: "git commit", + cwd, + detail: "Could not check whether a merge is in progress.", + cause, + }), + ), + ); + if (!merging) { + return yield* new GitVcsDriver.GitNothingToCommitError({ + operation: "GitVcsDriver.commit", + cwd, + detail: "Staging found no changes.", + }); + } + } const args = ["commit", "-m", subject]; const trimmedBody = body.trim(); if (trimmedBody.length > 0) { @@ -3541,7 +3666,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pushCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pushCurrentBranch"] = Effect.fn( "pushCurrentBranch", )(function* (cwd, fallbackBranch, options) { - const details = yield* statusDetails(cwd); + // Refresh first so the branch, upstream and divergence reads below stay close together. + yield* refreshStatusUpstream(cwd); + const details = yield* readStatusDetailsRemote(cwd, false, false); const branch = details.branch ?? fallbackBranch; if (!branch) { return yield* new GitCommandError({ @@ -3718,8 +3845,34 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const pullCurrentBranch: GitVcsDriver.GitVcsDriver["Service"]["pullCurrentBranch"] = Effect.fn( "pullCurrentBranch", )(function* (cwd) { - const details = yield* readStatusDetailsLocal(cwd); - const refName = details.branch; + const [refName, currentUpstreamRef] = yield* Effect.all( + [ + readCurrentBranch("GitVcsDriver.pullCurrentBranch.branch", cwd), + readCurrentUpstreamRef(cwd), + ], + { concurrency: 2 }, + ); + let upstreamRef = currentUpstreamRef; + // `@{upstream}` needs the tracking ref, which an unborn branch's first pull has not fetched. + if (upstreamRef === null && refName) { + const head = yield* executeGit( + "GitVcsDriver.pullCurrentBranch.head", + cwd, + ["rev-parse", "--verify", "--quiet", "HEAD"], + { allowNonZeroExit: true }, + ); + if (head.exitCode !== 0) { + const [configuredRemote, mergeRef] = yield* Effect.all([ + readConfigValue(cwd, `branch.${refName}.remote`), + readConfigValue(cwd, `branch.${refName}.merge`), + ]); + const mergeBranch = mergeRef?.replace(/^refs\/heads\//, ""); + if (configuredRemote && mergeBranch) { + upstreamRef = + configuredRemote === "." ? mergeBranch : `${configuredRemote}/${mergeBranch}`; + } + } + } if (!refName) { return yield* new GitCommandError({ ...gitCommandContext({ @@ -3730,7 +3883,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* detail: "Cannot pull from detached HEAD.", }); } - if (!details.hasUpstream) { + if (upstreamRef === null) { return yield* new GitCommandError({ ...gitCommandContext({ operation: "GitVcsDriver.pullCurrentBranch", @@ -3846,14 +3999,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* true, ).pipe(Effect.map((stdout) => stdout.trim())); - const refreshed = yield* readStatusDetailsLocal(cwd); return { status: beforeSha.length > 0 && beforeSha === afterSha ? ("skipped_up_to_date" as const) : ("pulled" as const), refName, - upstreamRef: refreshed.upstreamRef, + upstreamRef, }; }, Effect.scoped); @@ -3933,32 +4085,35 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd: string, untrackedPaths: ReadonlyArray, allowPartial: boolean, - knownIndexPath?: string, + knownIndexPath: string | undefined, + isolated: boolean, ) { const [stagedDeletionsStdout, indexValue] = yield* Effect.all( [ - runGitStdoutWithOptions( - "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.stagedDeletions", - cwd, - [ - "diff", - "--cached", - "--no-renames", - "--name-only", - "--diff-filter=D", - "-z", - "HEAD", - "--", - ], - { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, - ), - knownIndexPath === undefined - ? runGitStdout("GitVcsDriver.readUnifiedWorkingTreeReviewDiff.indexPath", cwd, [ + isolated + ? Effect.succeed("") + : runGitStdoutWithOptions( + "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.stagedDeletions", + cwd, + [ + "diff", + "--cached", + "--no-renames", + "--name-only", + "--diff-filter=D", + "-z", + "HEAD", + "--", + ], + { allowNonZeroExit: true, maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + ), + isolated || knownIndexPath !== undefined + ? Effect.succeed(knownIndexPath ?? "") + : runGitStdout("GitVcsDriver.readUnifiedWorkingTreeReviewDiff.indexPath", cwd, [ "rev-parse", "--git-path", "index", - ]) - : Effect.succeed(knownIndexPath), + ]), ], { concurrency: 2 }, ); @@ -4000,20 +4155,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const omitted = pathsToAdd.length < candidates.length; if (pathsToAdd.length === 0 || (omitted && !allowPartial)) return { env: undefined, omitted }; - const indexPath = knownIndexPath ?? path.resolve(cwd, indexValue.replace(/\n$/, "")); - const tempIndexPath = yield* fileSystem.makeTempFileScoped({ - prefix: `t3code-review-index-${process.pid}-`, - }); - const indexExists = yield* fileSystem.exists(indexPath); - if (indexExists) { - const { mtime } = yield* fileSystem.stat(indexPath); - yield* fileSystem.copyFile(indexPath, tempIndexPath); - // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy. - const indexTime = Option.isSome(mtime) - ? Math.max(0, Math.floor(mtime.value.getTime() / 1000)) - : 0; - yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime); - } + const prefix = `t3code-review-index-${process.pid}-`; + // The pathspec excludes every other entry, so an index holding only the added paths diffs + // the same as a copy of the real one. Git reads the missing file as an empty index. + const tempIndexPath = isolated + ? path.join(yield* fileSystem.makeTempDirectoryScoped({ prefix }), "index") + : yield* fileSystem.makeTempFileScoped({ prefix }); const env = { GIT_INDEX_FILE: tempIndexPath } satisfies NodeJS.ProcessEnv; const tempIndexConfig = [ "-c", @@ -4021,15 +4168,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* "-c", "splitIndex.sharedIndexExpire=never", ]; - if (!indexExists) { - yield* executeGit("GitVcsDriver.review.emptyIndex", cwd, ["read-tree", "--empty"], { env }); + if (!isolated) { + const indexPath = knownIndexPath ?? path.resolve(cwd, indexValue.replace(/\n$/, "")); + const indexExists = yield* fileSystem.exists(indexPath); + if (indexExists) { + const { mtime } = yield* fileSystem.stat(indexPath); + yield* fileSystem.copyFile(indexPath, tempIndexPath); + // stat truncates bigint times to ms; floor seconds to avoid making preceding-second files racy. + const indexTime = Option.isSome(mtime) + ? Math.max(0, Math.floor(mtime.value.getTime() / 1000)) + : 0; + yield* fileSystem.utimes(tempIndexPath, indexTime, indexTime); + } else { + yield* executeGit("GitVcsDriver.review.emptyIndex", cwd, ["read-tree", "--empty"], { + env, + }); + } + yield* executeGit( + "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.expandSplitIndex", + cwd, + [...tempIndexConfig, "update-index", "--no-split-index"], + { env }, + ); } - yield* executeGit( - "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.expandSplitIndex", - cwd, - [...tempIndexConfig, "update-index", "--no-split-index"], - { env }, - ); yield* executeGit( "GitVcsDriver.readUnifiedWorkingTreeReviewDiff.addUntracked", cwd, @@ -4069,11 +4230,35 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* allowPartial: boolean, knownIndexPath?: string, ) { - const untracked = yield* executeGit( - "GitVcsDriver.review.listUntracked", - cwd, - ["ls-files", "--others", "--exclude-standard", "-z", "--", ...pathArgs], - { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES }, + // Only the untracked path itself in the pathspec: a rename's tracked previous path needs its + // real index entry. + const isolated = onlyPath !== undefined && pathArgs.length === 1; + const listUntracked = (withTree: boolean) => + executeGit( + "GitVcsDriver.review.listUntracked", + cwd, + [ + "ls-files", + "--others", + "--exclude-standard", + ...(withTree ? ["--with-tree=HEAD"] : []), + "-z", + "--", + ...pathArgs, + ], + { maxOutputBytes: REVIEW_METADATA_MAX_OUTPUT_BYTES, allowNonZeroExit: withTree }, + ); + // An isolated index skips prepareReviewIndex's staged-deletion read, so --with-tree drops them + // here. It fails only without a HEAD, where nothing can be a staged deletion. + const untracked = yield* ( + isolated + ? listUntracked(true).pipe( + Effect.filterOrElse( + (result) => result.exitCode === 0, + () => listUntracked(false), + ), + ) + : listUntracked(false) ).pipe( Effect.catchTags({ GitCommandError: (error) => @@ -4089,7 +4274,13 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* if (paths.length === 0) return { env: undefined, omitted: false }; if (paths.length > REVIEW_UNTRACKED_MAX_FILES) return { unavailable: "Too many untracked files to count." }; - const index = yield* prepareReviewIndex(cwd, paths, allowPartial, knownIndexPath).pipe( + const index = yield* prepareReviewIndex( + cwd, + paths, + allowPartial, + knownIndexPath, + isolated, + ).pipe( Effect.catchTags({ PlatformError: (cause) => Effect.fail( @@ -4439,6 +4630,44 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }; }); + type ReviewTrackedDiff = { + readonly stdout: string; + readonly stdoutTruncated: boolean; + readonly files: ReadonlyArray; + }; + // A trackedOnly read, kept by its completionToken so the complete read that follows it adds + // only the untracked files. Taken once, so a later complete read always reads fresh. + const trackedReviewPreviews = new Map< + string, + { + readonly key: string; + readonly expiresAt: number; + readonly repository: { readonly worktreeRoot: string; readonly currentBranch: string | null }; + readonly review: { readonly baseRef: string | null; readonly mergeBase: string | null }; + readonly dirty: ReviewTrackedDiff; + readonly base: ReviewTrackedDiff; + } + >(); + const trackedReviewPreviewKey = (input: ReviewDiffPreviewInput) => + JSON.stringify([ + input.cwd, + input.baseRef ?? null, + input.sourceKind ?? null, + input.ignoreWhitespace === true, + input.metadataOnly === true, + ]); + const takeTrackedReviewPreview = Effect.fn("takeTrackedReviewPreview")(function* ( + input: ReviewDiffPreviewInput, + ) { + if (input.completionToken === undefined || input.trackedOnly) return undefined; + const entry = trackedReviewPreviews.get(input.completionToken); + if (entry === undefined) return undefined; + trackedReviewPreviews.delete(input.completionToken); + if (entry.key !== trackedReviewPreviewKey(input)) return undefined; + if ((yield* Clock.currentTimeMillis) > entry.expiresAt) return undefined; + return entry; + }); + const getReviewDiffPreview = Effect.fn("getReviewDiffPreview")(function* ( input: ReviewDiffPreviewInput, ) { @@ -4463,16 +4692,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* }); } const sourceKind = input.file?.sourceKind ?? input.sourceKind; + const previewMergeBase = + input.file?.sourceKind === "branch-range" ? input.mergeBase : undefined; const needsCurrentBranch = input.commitSha === undefined && input.file?.sourceKind !== "commit" && - sourceKind !== "working-tree"; - const repository = yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), - }), - ); + sourceKind !== "working-tree" && + previewMergeBase === undefined; + const reusesTracked = input.file === undefined && input.commitSha === undefined; + const tracked = reusesTracked ? yield* takeTrackedReviewPreview(input) : undefined; + const repository = + tracked?.repository ?? + (yield* resolveReviewRepository(input.cwd, needsCurrentBranch).pipe( + Effect.catchTags({ + GitCommandError: (error) => + isMissingGitCwdError(error) ? Effect.succeed(null) : Effect.fail(error), + }), + )); if (!repository?.worktreeRoot) { return { cwd: input.cwd, @@ -4546,9 +4782,12 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const dirtyRef = sourceKind === "branch-range" ? null : "HEAD"; const review = - sourceKind === "working-tree" + tracked?.review ?? + (sourceKind === "working-tree" ? { baseRef: input.baseRef ?? null, mergeBase: null } - : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef); + : previewMergeBase !== undefined + ? { baseRef: input.baseRef ?? null, mergeBase: previewMergeBase } + : yield* resolveReviewMergeBase(cwd, repository.currentBranch, input.baseRef)); const diffArgs = [ ...REVIEW_DIFF_ARGS, @@ -4584,13 +4823,30 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* exitCode: result.exitCode, }); }); + // A file the preview did not list as new is stat-ed against the real index first. `git diff` + // lists an indexed path as anything but deleted, and `ls-files --others` never lists one. + const indexedRef = + input.file && !input.trackedOnly && input.file.changeType && input.file.changeType !== "new" + ? (dirtyRef ?? review.mergeBase) + : null; + const indexedStat = indexedRef === null ? undefined : yield* readStats(indexedRef); + const indexed = + indexedStat?.files.some( + (file) => + file.path === input.file?.path && + file.changeType !== undefined && + file.changeType !== "deleted", + ) === true; const readTrackedDiff = Effect.fn("GitVcsDriver.getReviewDiffPreview.tracked")(function* ( ref: string | null, env?: NodeJS.ProcessEnv, metadataOnly = false, ) { if (ref === null) return { stdout: "", stdoutTruncated: false, files: [] }; - const stat = yield* readStats(ref, env); + const stat = + env === undefined && ref === indexedRef && indexedStat !== undefined + ? indexedStat + : yield* readStats(ref, env); if (metadataOnly || stat.files.length === 0) { return { stdout: "", stdoutTruncated: false, files: stat.files }; } @@ -4603,11 +4859,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return { ...patch, files: stat.files }; }); const [dirtyTrackedResult, baseResult] = yield* Effect.gen(function* () { - const untracked = input.trackedOnly - ? { env: undefined, omitted: false } - : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); + const untracked = + input.trackedOnly || indexed + ? { env: undefined, omitted: false } + : yield* prepareUntrackedReviewIndex(cwd, pathArgs, input.file?.path); // Untracked files left out make the file list partial, so the bounded patch is sent instead. const complete = untracked !== null && !untracked.omitted; + // With no untracked files to add, the tracked read already is the complete diff. + if (tracked !== undefined && complete && untracked.env === undefined) { + return [tracked.dirty, tracked.base] as const; + } const metadataOnly = input.metadataOnly === true && !input.file && complete; const [dirty, base] = review.mergeBase === dirtyRef @@ -4626,6 +4887,22 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ref === null ? result : { ...result, files: undefined, stdoutTruncated: true }; return [incomplete(dirtyRef, dirty), incomplete(review.mergeBase, base)] as const; }).pipe(Effect.scoped); + let completionToken: string | undefined; + if (input.trackedOnly && reusesTracked && dirtyTrackedResult.files && baseResult.files) { + completionToken = yield* random.uuidV4(); + trackedReviewPreviews.set(completionToken, { + key: trackedReviewPreviewKey(input), + expiresAt: (yield* Clock.currentTimeMillis) + REVIEW_TRACKED_PREVIEW_TTL_MS, + repository, + review, + dirty: { ...dirtyTrackedResult, files: dirtyTrackedResult.files }, + base: { ...baseResult, files: baseResult.files }, + }); + if (trackedReviewPreviews.size > REVIEW_TRACKED_PREVIEW_CAPACITY) { + const oldestKey = trackedReviewPreviews.keys().next().value; + if (oldestKey !== undefined) trackedReviewPreviews.delete(oldestKey); + } + } const dirtyFiles = dirtyTrackedResult.files; const baseFiles = baseResult.files; const dirtyDiff = dirtyTrackedResult.stdout; @@ -4656,6 +4933,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* title: review.baseRef ? `Changes vs ${review.baseRef}` : "Changes", baseRef: review.baseRef, headRef: repository.currentBranch ?? "HEAD", + ...(review.mergeBase === null ? {} : { mergeBase: review.mergeBase }), diff: baseDiff, ...(baseFiles === undefined ? {} : { files: baseFiles }), diffHash: baseDiffHash, @@ -4673,6 +4951,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? sources.filter((source) => source.kind === input.sourceKind) : sources, ...(input.trackedOnly ? { incomplete: true } : {}), + ...(completionToken === undefined ? {} : { completionToken }), }; }); @@ -6382,6 +6661,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* timeoutMs: 10_000, fallbackErrorDetail: "git branch rename failed", }, + ).pipe( + // Git exits non-zero after moving the ref when it cannot rewrite the locked config. + Effect.catch((error) => + Effect.all( + [branchExists(input.cwd, input.oldBranch), branchExists(input.cwd, targetBranch)], + { concurrency: "unbounded" }, + ).pipe( + Effect.orElseSucceed(() => [true, false] as const), + Effect.flatMap(([oldExists, newExists]) => + !oldExists && newExists + ? Effect.logWarning( + "GitVcsDriver.renameBranch: renamed the branch but could not move its config entries", + ) + : Effect.fail(error), + ), + ), + ), ); return { branch: targetBranch }; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index d96b91f30d62a..afa030d4d7e9c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3295,7 +3295,8 @@ export const layerWsRpc = ( Effect.flatMap((removed) => removed ? Effect.void : gitWorkflow.removeWorktree(input), ), - Effect.tap(() => refreshGitStatus(input.cwd)), + // No project-root refresh here: the client awaits vcs.refreshStatus right after, and a + // second refresh would queue behind this one and reread an unchanged repository. // Subscribers of the removed checkout learn it is no longer a repository. Effect.tap(() => vcsStatusBroadcaster diff --git a/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx b/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx index 29c217e064adc..d561254290427 100644 --- a/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx +++ b/apps/web/src/browser/ElectronBrowserHost.browser.test.tsx @@ -43,6 +43,7 @@ vi.mock(import("~/components/preview/previewBridge"), async (original) => ({ closeTab: mocks.closeTab, registerWebview: mocks.registerWebview, getPreviewConfig: mocks.getPreviewConfig, + onStateChange: () => () => {}, } as never, })); diff --git a/apps/web/src/browser/HostedBrowserWebview.tsx b/apps/web/src/browser/HostedBrowserWebview.tsx index 023fb03c3aa17..b20d737095116 100644 --- a/apps/web/src/browser/HostedBrowserWebview.tsx +++ b/apps/web/src/browser/HostedBrowserWebview.tsx @@ -159,6 +159,7 @@ export function HostedBrowserWebview(props: { if (!clientSettingsHydrated || !webview || !config || !bridge) return; let disposed = false; let recoveryTimeout: ReturnType | null = null; + let registeredWebContentsId: number | null = null; const register = () => { const lease = tabLeaseRef.current; if (!lease) return; @@ -170,6 +171,7 @@ export function HostedBrowserWebview(props: { const webContentsId = webview.getWebContentsId(); if (Number.isInteger(webContentsId) && webContentsId > 0) { await bridge.registerWebview(runtimeTabId, webContentsId); + registeredWebContentsId = webContentsId; withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, reportedShown())); } } catch {} @@ -198,6 +200,13 @@ export function HostedBrowserWebview(props: { dismissHostPopups(); } }; + // The desktop clears a destroyed guest's id; nothing reattaches this element, so remount it. + const unsubscribeState = bridge.onStateChange((changedTabId, state) => { + if (changedTabId !== runtimeTabId || registeredWebContentsId === null) return; + if (state.webContentsId !== null) return; + registeredWebContentsId = null; + recoverGuest(); + }); webview.addEventListener("did-attach", register); webview.addEventListener("dom-ready", register); webview.addEventListener("render-process-gone", recoverGuest); @@ -207,6 +216,7 @@ export function HostedBrowserWebview(props: { return () => { disposed = true; if (recoveryTimeout !== null) clearTimeout(recoveryTimeout); + unsubscribeState(); webview.removeEventListener("did-attach", register); webview.removeEventListener("dom-ready", register); webview.removeEventListener("render-process-gone", recoverGuest); @@ -374,6 +384,8 @@ export function HostedBrowserWebview(props: { /> ) : null}
{ - async function mountComposer(destinationValue = "") { + async function mountComposer(destinationValue = "", disabled = false) { const initialValue = `Draft A ${formatInlineContextReference(fileContextReference(file))}`; const editorRef = createRef(); let current: { value: string; files: ComposerFileAttachment[] }; @@ -982,7 +982,7 @@ describe("composer context undo lifetime", () => { ]), ), skills: [], - disabled: false, + disabled, placeholder: "", onChange: (value, _cursor, _expandedCursor, _adjacent, contextIds) => { const changes = reconcileAttachmentContextReferences({ @@ -1053,6 +1053,19 @@ describe("composer context undo lifetime", () => { expect(retained.files.size).toBe(0); }); + it.each(["Backspace", "Delete"])( + "removes a focused chip with %s while dictation makes the composer read-only", + async (key) => { + await using composer = await mountComposer("", true); + composer + .getByRole("button", { name: /notes\.txt/ }) + .element() + .focus(); + await userEvent.keyboard(`{${key}}`); + expect(composer.draft()).toEqual({ value: "Draft A ", files: [] }); + }, + ); + it.each(["", "Draft B"])( "releases deleted payloads and prevents undo into the previous draft when switching to %j", async (destinationValue) => { diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 9113a9d76dc78..9b758ee8b6777 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -598,9 +598,27 @@ const ComposerContextReferenceExtension = Node.create({ }, }); -function ComposerContextReferenceNodeView({ node }: NodeViewProps) { +function ComposerContextReferenceNodeView({ node, editor, getPos }: NodeViewProps) { return ( - + ) => { + // Paste and drop still add chips while dictation makes the editor read-only; a focused chip removes itself. + if ( + editor.isEditable || + (event.key !== "Backspace" && event.key !== "Delete") || + !(event.target instanceof globalThis.Node) || + !event.currentTarget.contains(event.target) + ) { + return; + } + const pos = typeof getPos === "function" ? getPos() : null; + if (typeof pos !== "number") return; + event.preventDefault(); + editor.commands.deleteRange({ from: pos, to: pos + node.nodeSize }); + }} + > { + // A read that began after this render, as a thread switch's, is that revalidation. + if (branchDiffPreviewIsPending()) return; if (Date.now() - branchDiffPreview.dataUpdatedAt < LIVE_REFRESH_MIN_INTERVAL_MS) return; refreshBranchDiffPreview(); } diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d1fef4ad5a617..1c42f176d89b4 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1071,12 +1071,11 @@ function CheckoutGitActionsControl({ const ignoreWhitespace = useDiffPanelSessionStore((state) => state.ignoreWhitespace) ?? ignoreWhitespaceSetting; const { canReadFiles } = useFilesystemReadAccess(activeEnvironmentId, messages); - // Same input as the Diff panel's branch query, so both read one cached result. Status - // totals join the revision because edits, pulls and resets outside a turn leave the mutation - // id as is. - const changesRevision = gitStatusForActions + // Same input and workspace revision as the Diff panel's branch query, so both read one + // cached result. Status totals are this reader's own revision because edits, pulls and + // resets outside a turn leave the mutation id as is. + const changesStatusRevision = gitStatusForActions ? JSON.stringify([ - workspaceMutationId, gitStatusForActions.refName, gitStatusForActions.workingTree.insertions, gitStatusForActions.workingTree.deletions, @@ -1089,7 +1088,7 @@ function CheckoutGitActionsControl({ showChanges && isRepo && canReadFiles && - changesRevision !== null && + changesStatusRevision !== null && activeEnvironmentId !== null && gitCwd !== null ? revisionedQuery( @@ -1103,7 +1102,8 @@ function CheckoutGitActionsControl({ sourceKind: "branch-range", }, }), - changesRevision, + workspaceMutationId, + { detail: changesStatusRevision }, ) : null, ); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index f7d1cceff44f7..9038e6717ba0e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -2649,6 +2649,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingIsResponding || (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) || projectSelectionRequired || + speechInput.freezesEditor || (options?.citationCommentAnchor && !composerEditorRef.current) ) { return false; @@ -3115,6 +3116,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) pendingDraftWork.has(attachmentTargetKey), insertTextAtEnd: insertComposerTextAtEndStable, pasteTextAtEnd: (text: string, options) => { + if (speechInput.freezesEditor) return false; const shortcutArmed = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); const bypassAutoAttachment = options?.bypassAutoAttachment === true || shortcutArmed; const promptLength = promptRef.current.length; @@ -3350,6 +3352,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) isLiteralPendingAnswer, pendingUserInputs.length, projectSelectionRequired, + speechInput.freezesEditor, applyPromptReplacementStable, isComposerModelPickerOpen, openModelPickerStable, diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index fb82f9c858d61..d8318b7279e7d 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -5,16 +5,18 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; +import { isSlashCommand } from "@t3tools/shared/composerTrigger"; import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; -import type { - ChatAttachment as ContractChatAttachment, - EnvironmentId, - MessageId, - RunId, - ThreadId, +import { + parseGoalCommand, + type ChatAttachment as ContractChatAttachment, + type EnvironmentId, + type MessageId, + type RunId, + type ThreadId, } from "@t3tools/contracts"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import { Link } from "@tanstack/react-router"; @@ -273,6 +275,9 @@ export function QueuedRunsControl({ replaceComposerContextReferences(item.text, (reference) => reference.label), ).trim(); const isEditing = item.runId !== null && item.runId === props.editingRunId; + // The server decides on the agent's text, and a goal command can stop the turn. + const sentText = { text: item.message?.text ?? item.text, attachments: item.attachments }; + const movesCommandFirst = isSlashCommand(sentText) && parseGoalCommand(sentText) === null; return (
  • diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 22ef904e2c13f..076c78d88d468 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -73,6 +73,8 @@ export function RightPanelSurfaceContent(props: { readonly keybindings: ResolvedKeybindingsConfig; readonly configuredPreviewUrls: ReadonlyArray; readonly workspaceMutationId: string | null; + /** What the diff is read under, as the Changes totals are; see `useWorkspaceRevision`. */ + readonly workspaceRevision: string | null; readonly getShortcutContext: () => ShortcutMatchContext; readonly onSendAnnotation: ( annotation: PreviewAnnotationPayload, @@ -118,7 +120,7 @@ export function RightPanelSurfaceContent(props: { key={scopedThreadKey(threadRef)} mode="embedded" composerDraftTarget={props.composerDraftTarget} - workspaceMutationId={props.workspaceMutationId} + workspaceMutationId={props.workspaceRevision} visible={visible} /> diff --git a/apps/web/src/components/diffs/DiffFileTree.tsx b/apps/web/src/components/diffs/DiffFileTree.tsx index ce48a468f66ec..57bc23b33130c 100644 --- a/apps/web/src/components/diffs/DiffFileTree.tsx +++ b/apps/web/src/components/diffs/DiffFileTree.tsx @@ -7,7 +7,11 @@ import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } fro import { useStableCallback } from "~/hooks/useStableCallback"; import { useTheme } from "~/hooks/useTheme"; import { cn } from "~/lib/utils"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { areAllDirectoriesExpanded, @@ -253,6 +257,7 @@ export function DiffFileTree({ }} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> {footer}
  • diff --git a/apps/web/src/components/diffs/useReviewFilePatches.ts b/apps/web/src/components/diffs/useReviewFilePatches.ts index 4f68b51fb5edd..0c889d501264d 100644 --- a/apps/web/src/components/diffs/useReviewFilePatches.ts +++ b/apps/web/src/components/diffs/useReviewFilePatches.ts @@ -201,10 +201,12 @@ function reviewFileQueries({ cwd, ...(baseRef ? { baseRef } : {}), ...(source.kind === "commit" ? { commitSha: source.id } : {}), + ...(source.mergeBase ? { mergeBase: source.mergeBase } : {}), ignoreWhitespace, file: { path: file.path, previousPath: file.previousPath, + ...(file.changeType ? { changeType: file.changeType } : {}), sourceKind: source.kind, }, }, diff --git a/apps/web/src/components/files/FileBrowserPanel.tsx b/apps/web/src/components/files/FileBrowserPanel.tsx index 1fee7db238727..cd44d99220939 100644 --- a/apps/web/src/components/files/FileBrowserPanel.tsx +++ b/apps/web/src/components/files/FileBrowserPanel.tsx @@ -27,7 +27,11 @@ import { useWorkspaceMutationRefresh } from "~/hooks/useWorkspaceMutationRefresh import { useFileContextMenu, type FileContextMenuAction } from "~/fileContextMenu"; import { readLocalApi } from "~/localApi"; import { T3_PIERRE_ICONS } from "~/pierre-icons"; -import { PIERRE_TREE_UNSAFE_CSS, pierreTreeStyle } from "~/pierre-tree-theme"; +import { + PIERRE_TREE_UNSAFE_CSS, + pierreTreeStyle, + titleClippedPierreTreeRow, +} from "~/pierre-tree-theme"; import { joinHostPath } from "./filePath"; import { createFileTreeDragMentionController } from "./fileTreeDragMention"; @@ -646,6 +650,7 @@ export default function FileBrowserPanel({ aria-label={gt("{projectName} files", { projectName })} className="min-h-0 flex-1 overflow-hidden" style={pierreTreeStyle(resolvedTheme)} + onPointerOver={titleClippedPierreTreeRow} /> )} diff --git a/apps/web/src/components/files/FilePreviewPanel.test.ts b/apps/web/src/components/files/FilePreviewPanel.test.ts index 19db5d24544f1..c02a74868fb0a 100644 --- a/apps/web/src/components/files/FilePreviewPanel.test.ts +++ b/apps/web/src/components/files/FilePreviewPanel.test.ts @@ -158,6 +158,17 @@ describe("document preview contents", () => { "A\tB\u2003C\u2002D\u2005E\u200dF\u200cG\u200bH\u200eI\u200fJ", ], ["a Unicode fallback", String.raw`{\rtf1 Jean\u8209\_Luc}`, "Jean\u2011Luc"], + ["a tracked replacement", String.raw`{\rtf1 aaa{\deleted bbb}{\revised BBB}ccc}`, "aaaBBBccc"], + [ + "text after a deletion reset", + String.raw`{\rtf1 A\deleted old\deleted0 B\deleted old\plain C}`, + "ABC", + ], + [ + "text around a deleted Unicode span", + String.raw`{\rtf1 A{\deleted\uc1\u945\deleted0 old}B}`, + "AB", + ], ])("keeps the text of %s", (_name, source, expected) => { const result = openRtf(bytes(source)); if (result.type !== "document") throw new Error("Expected document"); diff --git a/apps/web/src/components/files/extendedDocumentPreview.ts b/apps/web/src/components/files/extendedDocumentPreview.ts index c61a9207082d2..429e2fc56a4db 100644 --- a/apps/web/src/components/files/extendedDocumentPreview.ts +++ b/apps/web/src/components/files/extendedDocumentPreview.ts @@ -502,7 +502,6 @@ const RTF_CHARACTERS = new Map([ ["_", "\u2011"], ["-", "\u00ad"], ["tab", "\t"], - ["cell", "\t"], ["endash", "–"], // oxlint-disable-next-line t3code/no-em-dash-copy -- Preserve the RTF document's punctuation. ["emdash", "—"], @@ -531,6 +530,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { if (!source.startsWith("{\\rtf")) throw new PreviewError({ code: "rtf-invalid" }); let state = { skip: false, + deleted: false, bold: false, italic: false, underline: false, @@ -553,6 +553,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { }; let run = ""; let fallback = 0; + const hidden = () => state.skip || state.deleted; const encoded = new Uint8Array(bytes.byteLength); let encodedLength = 0; const flush = () => { @@ -572,19 +573,19 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { html += span; run = ""; }; - const emit = (value: string) => { + const emit = (value: string, skip = hidden()) => { if (fallback > 0) { fallback--; return; } - if (state.skip) return; + if (skip) return; run += escape(value); if (completedLength + html.length + run.length > 8 * 1024 * 1024) throw new PreviewError({ code: "rtf-too-much-content" }); }; const emitByte = (value: number) => { if (fallback > 0) fallback--; - else if (!state.skip) encoded[encodedLength++] = value; + else if (!hidden()) encoded[encodedLength++] = value; }; for (let i = 0; i < source.length;) { const char = source[i++]; @@ -624,13 +625,22 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { const character = RTF_CHARACTERS.get(next!); if (character) emit(character); // A backslash before a line break is \par; TextEdit ends paragraphs this way. - else if ((next === "\n" || next === "\r") && !state.skip) html += "
    "; + else if ((next === "\n" || next === "\r") && !hidden()) html += "
    "; i++; continue; } i += match[0].length; const word = match[1]; const arg = match[2] === undefined ? 1 : Number(match[2]); + if (word === "bin") { + if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i) + throw new PreviewError({ code: "rtf-binary-data" }); + i += arg; + } + if (fallback > 0) { + fallback--; + continue; + } if (word === "fonttbl") { state.fontTable = true; state.skip = true; @@ -681,11 +691,7 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { ].includes(word!) ) state.skip = true; - else if (word === "bin") { - if (!Number.isSafeInteger(arg) || arg < 0 || arg > source.length - i) - throw new PreviewError({ code: "rtf-binary-data" }); - i += arg; - } else if (word === "mac") state.decoder = new TextDecoder("macintosh"); + else if (word === "mac") state.decoder = new TextDecoder("macintosh"); else if (word === "ansicpg") { const label = ( @@ -708,15 +714,28 @@ export function openRtf(bytes: ArrayBuffer): OfficeWorkerResult { else if (word === "i") state.italic = arg !== 0; else if (word === "ul") state.underline = arg !== 0; else if (word === "ulnone") state.underline = false; + else if (word === "deleted") state.deleted = arg !== 0; else if (word === "plain") - state = { ...state, bold: false, italic: false, underline: false, font: defaultFont }; + state = { + ...state, + deleted: false, + bold: false, + italic: false, + underline: false, + font: defaultFont, + }; else if (word === "uc") state.uc = Math.max(0, Math.min(10, arg)); else if (word === "u") { fallback = 0; emit(String.fromCharCode(arg < 0 ? arg + 65536 : arg)); fallback = state.uc; - } else if (!state.skip && word === "page") finishPage(); - else if (!state.skip && (word === "par" || word === "line" || word === "row")) html += "
    "; + } else if (!hidden() && word === "page") finishPage(); + else if (word === "cell") emit("\t", state.skip); + else if ( + (!state.skip && word === "row") || + (!hidden() && (word === "par" || word === "line")) + ) + html += "
    "; else { const character = RTF_CHARACTERS.get(word!); if (character) emit(character); diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx index 9bb9e746ea12f..ebf42cc7d563a 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.browser.test.tsx @@ -2,7 +2,12 @@ import "~/index.css"; import { RegistryContext } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { type DeviceServiceState, type EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { + type DeviceServiceState, + type EnvironmentId, + type ScopedThreadRef, + ThreadId, +} from "@t3tools/contracts"; import { AsyncResult, Atom } from "effect/reactivity"; import { useState } from "react"; import { expect, it, vi } from "vite-plus/test"; @@ -27,6 +32,7 @@ vi.mock(import("../device/DeviceStreamView"), () => ({ })); const threadRef = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-1")); +const defaultThreadRef = threadRef; const phone: PreviewMiniPlayerSource = { kind: "device", hostId: "local", @@ -35,7 +41,7 @@ const phone: PreviewMiniPlayerSource = { name: "Phone", }; -function Harness() { +function Harness({ threadRef = defaultThreadRef }: { readonly threadRef?: ScopedThreadRef }) { const [store] = useState(createChatCanvasStore); const miniPlayer = usePreviewMiniPlayerStore((state) => selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef), @@ -119,3 +125,32 @@ it("holds its frame through a source change and stops when the gesture is interr await point(handle("west"), "pointermove", landscape.left - 100, landscape.top + 10, 1); expect(rect()).toEqual(landscape); }); + +it("keeps one stream when switching between threads floating the same device", async () => { + using _state = vi + .spyOn(deviceEnvironment, "state") + .mockReturnValue(Atom.make>(AsyncResult.initial())); + const otherThreadRef = scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-2")); + using _store = { + [Symbol.dispose]: () => { + usePreviewMiniPlayerStore.getState().removeThread(threadRef); + usePreviewMiniPlayerStore.getState().removeThread(otherThreadRef); + }, + }; + usePreviewMiniPlayerStore.getState().open(threadRef, phone); + usePreviewMiniPlayerStore.getState().open(otherThreadRef, phone); + const harness = (ref: ScopedThreadRef) => ( + + + + ); + const container = document.createElement("div"); + container.style.cssText = "display:flex;position:fixed;inset:0;width:1200px;height:800px"; + await using screen = await render(harness(threadRef), { container }); + const viewId = () => screen.getByTestId("stream").element().getAttribute("data-view-id"); + const first = viewId(); + + // The stream session is keyed by view, so a new view id reconnects the device. + await screen.rerender(harness(otherThreadRef)); + expect(viewId()).toBe(first); +}); diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 378bcdd88408f..989f283ad083b 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -121,12 +121,13 @@ const streamedSourceKey = (threadRef: ScopedThreadRef, sourceKey: string) => `${scopedThreadKey(threadRef)}\u0000${sourceKey}`; // The mini player's device stream view, named so the canvas can read the -// screen size that view reports. +// screen size that view reports. Not per thread: only the active thread's player +// mounts, so switching threads that float the same device keeps its stream. const miniPlayerDeviceViewId = ( threadRef: ScopedThreadRef, source: Extract, ) => - `preview-mini-player\u0000${scopedThreadKey(threadRef)}\u0000${deviceScreenKey(threadRef.environmentId, source.hostId, source.deviceId)}`; + `preview-mini-player\u0000${deviceScreenKey(threadRef.environmentId, source.hostId, source.deviceId)}`; function useBrowserMiniPlayerSource(threadRef: ScopedThreadRef | null, tabId: string | null) { const previewState = useThreadPreviewState(threadRef); diff --git a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx index 2e6cbe19390cc..9cc30490f1a36 100644 --- a/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx +++ b/apps/web/src/components/sidebar/SidebarUpdateCapsule.tsx @@ -92,6 +92,10 @@ export function SidebarUpdateCapsule({ const failed = machines.some(({ status }) => status === "failed"); const settled = !hasActiveMachine && run.localVersion === null; const restartSeconds = restartSecondsLeft(run, now); + const expandedControlClassName = + restartSeconds === null + ? "@min-[5rem]/sidebar-update:block" + : "@min-[12rem]/sidebar-update:block"; const actionLabel = view.action === "later" ? gt("Later") : view.action === "retry" ? gt("Retry") : gt("Dismiss"); @@ -105,7 +109,10 @@ export function SidebarUpdateCapsule({
    } /> - +