diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts index a563b6a4ee3a7..470091f334fb7 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.test.ts @@ -555,8 +555,40 @@ describe("parseResolvedPath", () => { // Path.layer joins with POSIX separators here, so the test windir is a POSIX path. const WSL_EXE = "/windows/System32/wsl.exe"; +const STORE_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService"; +const INBOX_SERVICE = "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager"; + +const registrySpawner = (keys: ReadonlyArray) => + ChildProcessSpawner.make((command) => + Effect.succeed( + ChildProcessSpawner.makeHandle({ + pid: ChildProcessSpawner.ProcessId(1), + stdout: Stream.empty, + stderr: Stream.empty, + all: Stream.empty, + exitCode: Effect.succeed( + ChildProcessSpawner.ExitCode( + command._tag === "StandardCommand" && + command.command === "reg.exe" && + keys.some((key) => command.args.includes(key)) + ? 0 + : 1, + ), + ), + isRunning: Effect.succeed(false), + kill: () => Effect.void, + stdin: Sink.drain, + getInputFd: () => Sink.drain, + getOutputFd: () => Stream.empty, + unref: Effect.succeed(Effect.void), + }), + ), + ); -const isAvailable = (policy?: Parameters[0]) => +const isAvailable = ( + policy?: Parameters[0], + serviceKeys: ReadonlyArray = [STORE_SERVICE], +) => makeIsAvailable("win32", "/windows").pipe( Effect.provide( Layer.mergeAll( @@ -565,9 +597,17 @@ const isAvailable = (policy?: Parameters[ DesktopManagedPolicy.layerTest(policy), ), ), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, registrySpawner(serviceKeys)), ); describe("makeIsAvailable", () => { + it.effect("needs a registered WSL service, not just the System32 install stub", () => + Effect.gen(function* () { + assert.isFalse(yield* isAvailable(undefined, [])); + assert.isTrue(yield* isAvailable(undefined, [INBOX_SERVICE])); + }), + ); + it.effect("turns WSL off on a machine with a managed policy, even an invalid one", () => Effect.gen(function* () { assert.isTrue(yield* isAvailable()); diff --git a/apps/desktop/src/wsl/DesktopWslEnvironment.ts b/apps/desktop/src/wsl/DesktopWslEnvironment.ts index f1d2fccde537b..9d9540a65dc7d 100644 --- a/apps/desktop/src/wsl/DesktopWslEnvironment.ts +++ b/apps/desktop/src/wsl/DesktopWslEnvironment.ts @@ -1119,13 +1119,50 @@ const getUserHomeImpl = ( Effect.orElseSucceed(() => Option.none()), ); +// Store/MSI WSL registers WSLService and inbox WSL registers LxssManager; either key means installed. +const WSL_SERVICE_KEYS = [ + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\WSLService", + "HKLM\\SYSTEM\\CurrentControlSet\\Services\\LxssManager", +] as const; +const SERVICE_QUERY_TIMEOUT = Duration.seconds(5); + +const wslServiceRegistered = Effect.scoped( + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const registered = yield* Effect.forEach( + WSL_SERVICE_KEYS, + (key) => + spawner + .spawn( + ChildProcess.make("reg.exe", ["query", key], { + stdin: "ignore", + stdout: "ignore", + stderr: "ignore", + killSignal: "SIGTERM", + forceKillAfter: PROCESS_TERMINATE_GRACE, + }), + ) + .pipe(Effect.flatMap((handle) => handle.exitCode)), + { concurrency: "unbounded" }, + ); + return registered.some((exitCode) => (exitCode as unknown as number) === 0); + }), +).pipe( + Effect.timeoutOption(SERVICE_QUERY_TIMEOUT), + Effect.map(Option.getOrElse(() => false)), + Effect.orElseSucceed(() => false), +); + export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable")(function* ( platform: NodeJS.Platform, windir: string, ): Effect.fn.Return< boolean, never, - FileSystem.FileSystem | Path.Path | DesktopManagedPolicy.DesktopManagedPolicy + | FileSystem.FileSystem + | Path.Path + | DesktopManagedPolicy.DesktopManagedPolicy + | ChildProcessSpawner.ChildProcessSpawner > { if (platform !== "win32") return false; const path = yield* Path.Path; @@ -1134,6 +1171,8 @@ export const makeIsAvailable = Effect.fn("DesktopWslEnvironment.makeIsAvailable" if (!(yield* fileSystem.exists(wslExePath).pipe(Effect.orElseSucceed(() => false)))) { return false; } + // System32\wsl.exe is also an install stub on Windows without WSL, so check for its service. + if (!(yield* wslServiceRegistered)) return false; // A server in WSL reads Linux's policy, never this machine's, so a managed machine runs none. return yield* (yield* DesktopManagedPolicy.DesktopManagedPolicy).read.pipe( Effect.map((found) => found === undefined), @@ -1245,6 +1284,7 @@ export const layer = Layer.effect( // Cache availability so synchronous IPC bootstrap can read it without yielding to filesystem I/O. const wslAvailable = yield* makeIsAvailable(environment.platform, windir).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner), Effect.provideService(Path.Path, environment.path), Effect.provideService( DesktopManagedPolicy.DesktopManagedPolicy, diff --git a/apps/mobile/src/components/ProviderIcon.tsx b/apps/mobile/src/components/ProviderIcon.tsx index 62a64102265de..f4bdf2f388ba6 100644 --- a/apps/mobile/src/components/ProviderIcon.tsx +++ b/apps/mobile/src/components/ProviderIcon.tsx @@ -197,7 +197,8 @@ export function ProviderInstanceIcon(props: { borderRadius: 999, borderWidth: 1, ...(props.surfaceColor ? { borderColor: props.surfaceColor } : {}), - backgroundColor: accentColor, + // An undefined inline key still overrides the className color when styles merge. + ...(accentColor ? { backgroundColor: accentColor } : {}), alignItems: "center", justifyContent: "center", }} @@ -208,7 +209,7 @@ export function ProviderInstanceIcon(props: { fontSize: 7, fontWeight: "600", lineHeight: 9, - color: accentColor ? providerAccentForegroundColor(accentColor) : undefined, + ...(accentColor ? { color: providerAccentForegroundColor(accentColor) } : {}), }} > {providerInstanceInitials(props.displayName)} diff --git a/apps/mobile/src/features/issues/IssueCommentComposer.tsx b/apps/mobile/src/features/issues/IssueCommentComposer.tsx index 75ff1199595a3..901dee46152a4 100644 --- a/apps/mobile/src/features/issues/IssueCommentComposer.tsx +++ b/apps/mobile/src/features/issues/IssueCommentComposer.tsx @@ -170,7 +170,11 @@ export function IssueCommentComposer(props: { /> {/* TalkBack orders siblings by position; outside this row the editor reads after Send. */} { + const host = params.host ? { host: params.host } : {}; + if (target.kind === "issue") { + navigation.dispatch( + StackActions.push("Issue", { + environmentId: params.environmentId, + projectId: params.projectId, + tracker: params.tracker, + ...host, + scope: target.repository, + issueKey: String(target.number), + }), + ); + } else if (sameHost) { + navigation.dispatch( + StackActions.push("PullRequest", { + environmentId: params.environmentId, + projectId: params.projectId, + repository: target.repository, + number: target.number, + ...host, + }), + ); + } else { + void tryOpenExternalUrl(target.url); + } + }; return ( @@ -414,7 +454,21 @@ function IssueEventRow({ event }: { readonly event: IssueEvent }) { {event.actor?.login ?? gt("Someone", { $context: "an unknown person" })} {" "} - {issueEventSentence(event, messages)} + {source === undefined || event.detail === null || at < 0 ? ( + sentence + ) : ( + <> + {sentence.slice(0, at)} + openSource(source)} + > + {event.detail} + + {sentence.slice(at + event.detail.length)} + + )} {relativeTime(event.createdAt, undefined, messages)} @@ -505,7 +559,7 @@ function IssueRoute({ params }: { readonly params: IssueParams }) { ...detail.events.map((event) => ({ key: `e:${event.id}`, at: event.createdAt, - content: , + content: , })), ].sort((left, right) => Date.parse(left.at) - Date.parse(right.at)) : []; diff --git a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx index 5daf5ef20565b..7b904c8e33105 100644 --- a/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx +++ b/apps/mobile/src/features/pull-requests/PullRequestListRow.tsx @@ -122,6 +122,7 @@ export const PullRequestListRow = memo( ), item.title, status.label, + item.visibility === "private" ? gt("Private") : null, conflict ? conflict.label.toLowerCase() : null, gt("by {author}", { author: item.author?.login ?? gt("unknown author") }), review ? review.accessibleLabel : null, @@ -178,6 +179,17 @@ export const PullRequestListRow = memo( {item.repository} #{item.number} + {item.visibility === "private" ? ( + + + + ) : null} {item.stack ? ( {status.label} )} + {"visibility" in pr && pr.visibility === "private" ? ( + + + {gt("Private")} + + ) : null} {"changedFiles" in pr && pr.changedFiles !== undefined ? ( diff --git a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts index fa79d882cc23d..16b84c596d627 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestGlyphs.ts @@ -7,4 +7,5 @@ export const PullRequestGlyph = { merged: "arrow.triangle.merge", stack: "square.3.layers.3d", conflicting: "exclamationmark.triangle", + private: { ios: "lock.fill", android: "lock" }, } as const satisfies Record; diff --git a/apps/mobile/src/features/pull-requests/pullRequestList.ts b/apps/mobile/src/features/pull-requests/pullRequestList.ts index e7c2f5de769c4..3b30c11d65e64 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestList.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestList.ts @@ -190,6 +190,7 @@ export function pullRequestListRowsAreEqual( previous.title === next.title && previous.url === next.url && previous.state === next.state && + previous.visibility === next.visibility && previous.isDraft === next.isDraft && previous.mergeability === next.mergeability && previous.baseBranch === next.baseBranch && diff --git a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx index db2e7169d4930..881f67e86648f 100644 --- a/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx +++ b/apps/mobile/src/features/review/ReviewCommentComposerSheet.tsx @@ -2,7 +2,7 @@ import { useNavigation, type StaticScreenProps } from "@react-navigation/native" import { TextInputWrapper } from "expo-paste-input"; import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; import { T, useGT } from "gt-react-native"; -import { useMemo, useState } from "react"; +import { useEffect, useMemo, useRef, useState } from "react"; import { ScrollView, View, useWindowDimensions } from "react-native"; import * as Dialog from "../../components/ui/Dialog"; import { FilePreviewModal, type FilePreviewSource } from "../../components/ui/FilePreviewModal"; @@ -16,6 +16,7 @@ import { cn } from "../../lib/cn"; import type { DraftComposerImageAttachment } from "../../lib/composerImages"; import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages"; import { useNativePaste } from "../../lib/useNativePaste"; +import { scheduleUnusedComposerAttachmentCleanup } from "../../state/use-composer-drafts"; import { setPendingConnectionError } from "../../state/use-remote-environment-registry"; import { appendReviewCommentToDraft } from "../../state/use-thread-composer-state"; import { @@ -49,6 +50,31 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp const { environmentId, threadId } = props.route.params; const [commentText, setCommentText] = useState(""); const [attachments, setAttachments] = useState>([]); + const attachmentsRef = useRef(attachments); + const isMountedRef = useRef(true); + // Store file references before React commits, so closing the sheet can release them. + const replaceAttachments = (next: ReadonlyArray) => { + attachmentsRef.current = next; + setAttachments(next); + }; + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- releases owned image files when the sheet unmounts + useEffect(() => { + isMountedRef.current = true; + return () => { + isMountedRef.current = false; + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + }; + }, []); + + function appendImages(images: ReadonlyArray): void { + if (!isMountedRef.current) { + scheduleUnusedComposerAttachmentCleanup(images); + return; + } + if (images.length > 0) { + replaceAttachments([...attachmentsRef.current, ...images]); + } + } const [previewFile, setPreviewFile] = useState(null); const { selectedLines, highlightedLinesById } = useMemo(() => { @@ -90,27 +116,25 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp }; const handleNativePaste = useNativePaste((uris) => { void (async () => { - try { - const result = await convertPastedImagesToAttachments({ - uris, - existingCount: attachments.length, - }); - if (result.attachments.length > 0) { - setAttachments((current) => [...current, ...result.attachments]); - } - if (result.error) Dialog.alert(gt("Could not paste image"), result.error); - } catch (error) { + const result = await convertPastedImagesToAttachments({ + uris, + existingCount: attachmentsRef.current.length, + }).catch((error: unknown) => { console.error("[review comment] error converting pasted images", error); + return null; + }); + if (result === null) return; + appendImages(result.attachments); + if (result.error && isMountedRef.current) { + Dialog.alert(gt("Could not paste image"), result.error); } })(); }); async function handlePickImages(): Promise { - const result = await pickComposerImages({ existingCount: attachments.length }); - if (result.images.length > 0) { - setAttachments((current) => [...current, ...result.images]); - } - if (result.error) { + const result = await pickComposerImages({ existingCount: attachmentsRef.current.length }); + appendImages(result.images); + if (result.error && isMountedRef.current) { setPendingConnectionError(result.error); } } @@ -124,9 +148,10 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp environmentId, threadId, text: formatReviewCommentContext(target, commentText), - attachments, + attachments: attachmentsRef.current, }); - setAttachments([]); + scheduleUnusedComposerAttachmentCleanup(attachmentsRef.current); + replaceAttachments([]); dismissComposer(); }; @@ -255,9 +280,12 @@ export function ReviewCommentComposerSheet(props: ReviewCommentComposerSheetProp onPressPreview={setPreviewFile} removeButtonPlacement="gutter" onRemove={(imageId) => { - setAttachments((current) => - current.filter((image) => image.id !== imageId), - ); + const current = attachmentsRef.current; + const removed = current.find((image) => image.id === imageId); + replaceAttachments(current.filter((image) => image.id !== imageId)); + if (removed) { + scheduleUnusedComposerAttachmentCleanup([removed]); + } }} /> diff --git a/apps/mobile/src/features/sharing/incoming-share-model.test.ts b/apps/mobile/src/features/sharing/incoming-share-model.test.ts index 1dea547de53b4..7ca92b23c3208 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.test.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "@effect/vitest"; +import { describe, expect, it, vi } from "vite-plus/test"; import { PROVIDER_SEND_TURN_MAX_ATTACHMENTS, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, @@ -13,6 +13,32 @@ import { selectIncomingShareAttachmentsForServer, } from "./incoming-share-model"; +const nativeImage = vi.hoisted(() => ({ + resize: vi.fn(), +})); + +vi.mock("expo-image-manipulator", () => ({ + SaveFormat: { PNG: "png", JPEG: "jpeg" }, + ImageManipulator: { + manipulate: (source: string | { width: number; height: number }) => { + let size = typeof source === "string" ? { width: 3000, height: 1500 } : source; + const context = { + resize: (next: { width: number; height: number }) => { + nativeImage.resize(next); + size = next; + return context; + }, + renderAsync: async () => ({ + ...size, + release: () => {}, + saveAsync: async () => ({ uri: "file:///cache/resized.png", base64: "YWJj" }), + }), + }; + return context; + }, + }, +})); + describe("incoming native shares", () => { it("converts shared text, URLs, and images into a durable composer draft", async () => { const image: SharePayload = { @@ -35,6 +61,9 @@ describe("incoming native shares", () => { originalName: "Screenshot.png", }; const removeOwnedFile = vi.fn(() => Promise.resolve()); + const readBase64 = vi.fn(async () => "YWJj"); + const persistedUri = "file:///documents/t3-composer-attachments/Screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); const result = await buildIncomingShareDraft({ id: "share-1", @@ -42,7 +71,9 @@ describe("incoming native shares", () => { payloads, resolvedPayloads: [resolvedImage], fileReader: { - readBase64: async () => "YWJj", + readBase64, + persistFile, + readSize: async (uri) => (uri === persistedUri ? 3 : null), removeOwnedFile, }, }); @@ -59,16 +90,95 @@ describe("incoming native shares", () => { name: "Screenshot.png", mimeType: "image/png", sizeBytes: 3, - dataUrl: "data:image/png;base64,YWJj", - previewUri: "data:image/png;base64,YWJj", + fileUri: persistedUri, + previewUri: persistedUri, }, ], warnings: [], }); expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); expect(hasIncomingShareContent(result)).toBe(true); }); + it("persists the resized PNG for a shared image over 2000px", async () => { + const header = Buffer.alloc(24); + header.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + header.set([0x49, 0x48, 0x44, 0x52], 12); + header.writeUInt32BE(3000, 16); + header.writeUInt32BE(1500, 20); + const persistedUri = "file:///documents/t3-composer-attachments/screenshot.png"; + const persistFile = vi.fn(async () => persistedUri); + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + + const draft = await buildIncomingShareDraft({ + id: "share-resize", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [ + { shareType: "image", value: "content://shared/screenshot", mimeType: "image/png" }, + ], + resolvedPayloads: [], + fileReader: { + readBase64: async () => header.toString("base64"), + persistFile, + readSize: async () => 3, + removeOwnedFile, + }, + }); + + expect(nativeImage.resize).toHaveBeenCalledWith({ width: 2000, height: 1000 }); + expect(persistFile).toHaveBeenCalledWith("file:///cache/resized.png", "screenshot"); + expect(draft.attachments).toEqual([ + { + id: "share-resize-image-0", + type: "image", + name: "screenshot", + mimeType: "image/png", + sizeBytes: 3, + fileUri: persistedUri, + previewUri: persistedUri, + }, + ]); + expect(draft.warnings).toEqual([]); + expect(removeOwnedFile).not.toHaveBeenCalledWith(persistedUri); + }); + + it("releases a shared image when its stored size cannot be measured", async () => { + const image: SharePayload = { + shareType: "image", + value: "file:///shared/photo.png", + mimeType: "image/png", + }; + const persistedUri = "file:///documents/t3-composer-attachments/photo.png"; + const removeOwnedFile = vi.fn(async (_uri: string) => undefined); + const result = await buildIncomingShareDraft({ + id: "share-unmeasured", + createdAt: "2026-07-15T10:00:00.000Z", + payloads: [image], + resolvedPayloads: [ + { + ...image, + contentUri: image.value, + contentType: "image", + contentMimeType: "image/png", + contentSize: 3, + originalName: "photo.png", + }, + ], + fileReader: { + readBase64: async () => "unused", + persistFile: async () => persistedUri, + readSize: async () => null, + removeOwnedFile, + }, + }); + + expect(result.attachments).toEqual([]); + expect(result.warnings).toEqual(["'photo.png' is empty or could not be read."]); + expect(removeOwnedFile).toHaveBeenCalledWith(persistedUri); + expect(removeOwnedFile).toHaveBeenCalledWith(image.value); + }); + it("skips oversized images and releases the temporary native file", async () => { const image: SharePayload = { shareType: "image", diff --git a/apps/mobile/src/features/sharing/incoming-share-model.ts b/apps/mobile/src/features/sharing/incoming-share-model.ts index 9bfc2dcca1b29..86c17c6059e0e 100644 --- a/apps/mobile/src/features/sharing/incoming-share-model.ts +++ b/apps/mobile/src/features/sharing/incoming-share-model.ts @@ -412,6 +412,9 @@ export async function buildIncomingShareDraft(input: { continue; } + const name = resolved?.originalName ?? fallbackName(uri, index, mimeType); + let persistedImageUri: string | undefined; + let retainedImageUri: string | undefined; try { const sharedBase64 = await input.fileReader.readBase64(uri); // Use already-read bytes because native image loaders may not read the provider's file. @@ -421,36 +424,54 @@ export async function buildIncomingShareDraft(input: { base64: sharedBase64, }); const base64 = fitted?.base64 ?? sharedBase64; - const sizeBytes = fitted - ? estimateBase64ByteSize(base64) - : (resolved?.contentSize ?? estimateBase64ByteSize(base64)); - if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { - warnings.push( - m( - msg("''{name}'' exceeds the 10 MB attachment limit.", { - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), - }), - ), - ); + const decodedSize = estimateBase64ByteSize(base64); + if (decodedSize <= 0 || decodedSize > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }))); + continue; + } + if (input.fileReader.persistFile) { + persistedImageUri = await input.fileReader.persistFile(fitted?.uri ?? uri, name); + const sizeBytes = (await input.fileReader.readSize?.(persistedImageUri)) ?? null; + if (sizeBytes === null || sizeBytes <= 0) { + warnings.push(m(msg("''{name}'' is empty or could not be read.", { name }))); + continue; + } + if (sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) { + warnings.push(fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES, m)); + continue; + } + attachments.push({ + id: `${input.id}-image-${index}`, + type: "image", + name, + mimeType, + sizeBytes, + fileUri: persistedImageUri, + previewUri: persistedImageUri, + }); + retainedImageUri = persistedImageUri; continue; } const dataUrl = `data:${mimeType};base64,${base64}`; attachments.push({ id: `${input.id}-image-${index}`, type: "image", - name: resolved?.originalName ?? fallbackName(uri, index, mimeType), + name, mimeType, - sizeBytes, + sizeBytes: decodedSize, dataUrl, // Data-backed previews outlive temporary share files and App Group entries. previewUri: dataUrl, }); } catch { - warnings.push( - m(msg("Could not read ''{name}''.", { name: fallbackName(uri, index, mimeType) })), - ); + warnings.push(m(msg("Could not read ''{name}''.", { name }))); } finally { - await releaseOwnedFiles(input.fileReader, [uri, payload.value]); + await releaseOwnedFiles( + input.fileReader, + [uri, payload.value, persistedImageUri].filter( + (candidate) => candidate !== retainedImageUri, + ), + ); } } diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx new file mode 100644 index 0000000000000..748fb333239a0 --- /dev/null +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.test.tsx @@ -0,0 +1,134 @@ +import { expect, it } from "@effect/vitest"; +import { + followLinkedThread, + type LinkedThreadView as LinkedThreadState, +} from "@t3tools/client-runtime/linked-thread"; +import { EnvironmentId, type OrchestrationV2ThreadHistoryPage } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Queue from "effect/Queue"; +import * as Stream from "effect/Stream"; +import { act, type ReactNode } from "react"; +import { createRoot } from "react-dom/client"; +import { vi } from "vite-plus/test"; + +import { v2Projection } from "../../../../../packages/client-runtime/src/state/orchestrationV2TestFixtures"; +import { useLinkedThreadView } from "../../state/linkedThread"; +import { LinkedThreadView } from "./LinkedThreadSheet"; + +vi.mock("@react-navigation/native", () => ({ + StackActions: {}, + useIsFocused: () => true, + useNavigation: () => ({}), +})); +vi.mock("react-native", () => { + const Container = ({ children }: { children: ReactNode }) =>
{children}
; + return { + AppState: { currentState: "active", addEventListener: () => ({ remove() {} }) }, + Platform: { OS: "android" }, + Pressable: Container, + ScrollView: Container, + Text: Container, + View: Container, + }; +}); +vi.mock("react-native-safe-area-context", () => ({ useSafeAreaInsets: () => ({ bottom: 0 }) })); +vi.mock("../../components/ui/AppActivityIndicator", () => ({ AppActivityIndicator: () => null })); +vi.mock("../../components/ui/Button", () => ({ + Button: (props: { label: string; disabled?: boolean; onPress: () => void }) => ( + + ), +})); +vi.mock("../../components/ui/ScreenContent", () => ({ + ScreenContent: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("../../native/SelectableMarkdownText", () => ({ SelectableMarkdownText: () => null })); +vi.mock("../../state/environments", () => ({ useEnvironments: () => ({ environments: [] }) })); +vi.mock("../../state/linkedThread", () => ({ + useConnectLinkedEnvironment: () => ({ state: { phase: "idle" } }), + useLinkedThreadView: vi.fn(), +})); +vi.mock("../../state/peerLinks", () => ({ peerLinkEnvironment: {} })); +vi.mock("../../state/query", () => ({ useEnvironmentQuery: () => ({}) })); +vi.mock("../files/FileMarkdownPreview", () => ({ useMarkdownPreviewStyles: () => ({}) })); +vi.mock("./ReadOnlyComposerBar", () => ({ + ReadOnlyComposerBar: ({ children }: { children: ReactNode }) => children, +})); +vi.mock("./thread-inspector-header", () => ({ ThreadInspectorHeader: () => null })); +vi.mock("./useOpenLinkedThread", () => ({ useOpenLinkedThread: () => undefined })); + +it.effect( + "shows a page error after Load earlier fails on an already disconnected linked chat", + () => + Effect.gen(function* () { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + const root = createRoot(container); + const target = { + viaEnvironmentId: EnvironmentId.make("via"), + environmentId: EnvironmentId.make("linked"), + threadId: v2Projection.thread.id, + label: "Linked test environment", + title: null, + }; + const warning = "Linked test environment is not answering this environment"; + const pageError = "Could not load earlier turns. Try again."; + const loadEarlier = () => + [...container.querySelectorAll("button")].find( + (button) => button.textContent === "Load earlier", + )!; + + try { + const unavailable = { _tag: "PeerLinkThreadReadError", reason: "unreachable" }; + const pages = + yield* Queue.unbounded< + Effect.Effect + >(); + const views = yield* Queue.unbounded(); + yield* followLinkedThread({ + items: Stream.make({ + kind: "snapshot", + snapshotSequence: 1, + projection: v2Projection, + historyCursor: "before-recent", + hasMoreHistory: true, + } as const).pipe(Stream.concat(Stream.fail(unavailable))), + historyPage: () => Queue.take(pages).pipe(Effect.flatten), + }).pipe( + Stream.runForEach((view) => Queue.offer(views, view)), + Effect.forkScoped, + ); + + const renderNext = Effect.gen(function* () { + const view = yield* Queue.take(views); + vi.mocked(useLinkedThreadView).mockReturnValue({ + view, + error: view.error ?? null, + retry() {}, + }); + act(() => root.render()); + }); + + yield* renderNext; // Initial snapshot. + yield* renderNext; // Connection warning. + expect(container.textContent).toContain(warning); + expect(container.textContent).not.toContain(pageError); + + act(() => loadEarlier().click()); + yield* renderNext; + yield* Queue.offer(pages, Effect.fail(unavailable)); + yield* renderNext; + expect(loadEarlier().parentElement?.textContent).toContain(pageError); + expect(container.textContent).toContain(warning); + + act(() => loadEarlier().click()); + yield* renderNext; + expect(container.textContent).not.toContain(pageError); + expect(loadEarlier().disabled).toBe(true); + } finally { + act(() => root.unmount()); + vi.unstubAllGlobals(); + } + }).pipe(Effect.scoped), +); diff --git a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx index 0096c9d576a91..7ec2c4dac2cc8 100644 --- a/apps/mobile/src/features/threads/LinkedThreadSheet.tsx +++ b/apps/mobile/src/features/threads/LinkedThreadSheet.tsx @@ -286,6 +286,9 @@ export function LinkedThreadView(props: { const scroll = useRef>(null); // Follows new items only while the reader is already at the end. const atEnd = useRef(true); + const showHistoryError = + view !== null && view.thread.historyCursor !== null && view.history.failed; + const lastLayoutHadHistoryError = useRef(false); const working = projection !== null && isLinkedThreadWorking(projection); const connection = useConnectLinkedEnvironment(target); const connectState = connection.state; @@ -334,7 +337,12 @@ export function LinkedThreadView(props: { atEnd.current = contentSize.height - layoutMeasurement.height - contentOffset.y < 80; }} onContentSizeChange={() => { - if (atEnd.current) scroll.current?.scrollToEnd({ animated: false }); + // A page error can resize the top of a short feed whose reader is also near the end. + const historyErrorChanged = lastLayoutHadHistoryError.current !== showHistoryError; + lastLayoutHadHistoryError.current = showHistoryError; + if (atEnd.current && !historyErrorChanged) { + scroll.current?.scrollToEnd({ animated: false }); + } }} > {view === null || projection === null ? ( @@ -351,7 +359,7 @@ export function LinkedThreadView(props: { ) : ( <> {view.thread.historyCursor !== null ? ( - + + } + />, + ); + const editor = editorIn(screen.container); + await userEvent.click(editor.view.dom, { position: { x: 12, y: 12 } }); + await vi.waitFor(() => expect(editor.view.hasFocus()).toBe(true)); + await userEvent.click(screen.getByRole("button", { name: "Tab" })); + expect(onClick).toHaveBeenCalledOnce(); +}); diff --git a/apps/web/src/components/ComposerPromptEditorTiptap.tsx b/apps/web/src/components/ComposerPromptEditorTiptap.tsx index 15c6f98525dee..ed397c6dcc31b 100644 --- a/apps/web/src/components/ComposerPromptEditorTiptap.tsx +++ b/apps/web/src/components/ComposerPromptEditorTiptap.tsx @@ -206,6 +206,8 @@ export interface ComposerPromptEditorProps { contextIds: string[], /** False when only the caret or selection moved. */ textChanged: boolean, + /** True when the change came from undo or redo. */ + fromHistory?: boolean, ) => void; onVisibleSelectionChange?: () => void; onCommandKeyDown?: (key: string, event: KeyboardEvent, isTaskItem?: boolean) => boolean; @@ -1113,6 +1115,7 @@ function ComposerPromptEditorTiptapInner( suppressTrigger, contextIds, previousSnapshot.value !== nextValue, + isHistoryTransaction(transaction), ); }; @@ -1953,7 +1956,7 @@ function ComposerPromptEditorTiptapInner( {isEmpty && contextRecords.size === 0 && placeholder ? (
diff --git a/apps/web/src/components/ProjectCloneToastCoordinator.tsx b/apps/web/src/components/ProjectCloneToastCoordinator.tsx index 846644c537a12..778c195e2d29e 100644 --- a/apps/web/src/components/ProjectCloneToastCoordinator.tsx +++ b/apps/web/src/components/ProjectCloneToastCoordinator.tsx @@ -45,6 +45,8 @@ interface TrackedToast { readonly toastId: ReturnType; readonly renderedKey: string; readonly phase: ProjectCloneSnapshot["phase"]; + readonly startedAt: ProjectCloneSnapshot["startedAt"]; + readonly closed?: true; } function renderKey(clone: ProjectCloneSnapshot): string { @@ -98,6 +100,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI seen.add(clone.projectId); const key = renderKey(clone); const tracked = toasts.current.get(clone.projectId); + const sameAttempt = tracked?.startedAt === clone.startedAt; const name = projectCloneDisplayName(clone); const closeToast = () => { const current = toasts.current.get(clone.projectId); @@ -111,7 +114,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } - if (tracked?.renderedKey === key) continue; + if (sameAttempt && tracked.renderedKey === key) continue; if ( isProjectCloneToastSilenced(ref) && (clone.phase === "running" || clone.phase === "done") @@ -119,6 +122,34 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI closeToast(); continue; } + if ( + sameAttempt && + tracked.closed && + (tracked.phase !== "running" || clone.phase !== "failed") + ) { + continue; + } + + const showToast = (options: ReturnType) => { + const rendered = { renderedKey: key, phase: clone.phase, startedAt: clone.startedAt }; + if (tracked && !tracked.closed) { + toastManager.update(tracked.toastId, options); + toasts.current.set(clone.projectId, { toastId: tracked.toastId, ...rendered }); + return; + } + + const toastId = toastManager.add({ + ...options, + // Updates to a closing toast are ignored, even before it has been removed. + onClose: () => { + const current = toasts.current.get(clone.projectId); + if (current?.toastId === toastId) { + toasts.current.set(clone.projectId, { ...current, closed: true }); + } + }, + }); + toasts.current.set(clone.projectId, { toastId, ...rendered }); + }; if (clone.phase === "running") { const options = stackedThreadToast({ @@ -136,13 +167,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "running" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "running" }); - } + showToast(options); continue; } @@ -161,13 +186,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, data: { hideCopyButton: true }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: "done" }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: "done" }); - } + showToast(options); continue; } @@ -199,13 +218,7 @@ function EnvironmentCloneToasts({ environmentId }: { environmentId: EnvironmentI }, }, }); - if (tracked) { - toastManager.update(tracked.toastId, options); - toasts.current.set(clone.projectId, { ...tracked, renderedKey: key, phase: clone.phase }); - } else { - const toastId = toastManager.add(options); - toasts.current.set(clone.projectId, { toastId, renderedKey: key, phase: clone.phase }); - } + showToast(options); } for (const [projectId, tracked] of toasts.current) { diff --git a/apps/web/src/components/Sidebar.motion.browser.test.ts b/apps/web/src/components/Sidebar.motion.browser.test.ts new file mode 100644 index 0000000000000..2eae3d4f83fb9 --- /dev/null +++ b/apps/web/src/components/Sidebar.motion.browser.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from "vite-plus/test"; +import { render } from "../../test/render"; +import { createSidebarListMotion } from "./Sidebar.motion"; + +describe("sidebar list motion", () => { + it("slides rows above a removal at the bottom instead of jumping with the scroll clamp", async () => { + await using screen = await render(null); + const viewport = document.createElement("div"); + viewport.dataset.slot = "scroll-area-viewport"; + viewport.style.cssText = "height: 200px; overflow-y: auto; overflow-anchor: none"; + const list = document.createElement("ul"); + list.style.cssText = "position: relative; margin: 0; padding: 0; list-style: none"; + const rows = Array.from({ length: 10 }, () => { + const row = document.createElement("li"); + row.style.height = "64px"; + list.append(row); + return row; + }); + viewport.append(list); + screen.container.append(viewport); + const motion = createSidebarListMotion(list); + using _motion = { [Symbol.dispose]: () => motion.dispose() }; + motion.update(false); + viewport.scrollTop = viewport.scrollHeight; + viewport.dispatchEvent(new Event("scroll")); + const above = rows[7]!; + const before = above.getBoundingClientRect().top; + + rows[8]!.remove(); + motion.update(true); + for (const animation of above.getAnimations()) animation.pause(); + + expect(above.getBoundingClientRect().top).toBe(before); + }); +}); diff --git a/apps/web/src/components/Sidebar.motion.ts b/apps/web/src/components/Sidebar.motion.ts index 0e86c3c9a0e94..da0e7de3201b2 100644 --- a/apps/web/src/components/Sidebar.motion.ts +++ b/apps/web/src/components/Sidebar.motion.ts @@ -22,6 +22,12 @@ export function createSidebarListMotion(parent: HTMLUListElement) { const entering = new Map(); const exiting = new Map(); let released: Map | null = null; + const scroller = parent.closest('[data-slot="scroll-area-viewport"]'); + let scrollTop = scroller?.scrollTop ?? 0; + const trackScroll = () => { + scrollTop = scroller?.scrollTop ?? 0; + }; + scroller?.addEventListener("scroll", trackScroll, { passive: true }); const remainingOffset = (node: HTMLElement) => { const current = running.get(node); @@ -37,7 +43,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { entering.clear(); exiting.clear(); }; - const fadeOut = (node: HTMLElement, position: RowPosition, travel: number) => { + const fadeOut = (node: HTMLElement, position: RowPosition, travel: number, shift: number) => { if (position.height === 0) return; const clone = node.cloneNode(true) as HTMLElement; for (const element of [clone, ...clone.querySelectorAll("*")]) { @@ -56,7 +62,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { clone.inert = true; Object.assign(clone.style, { position: "absolute", - top: `${position.top + remainingOffset(node)}px`, + top: `${position.top + remainingOffset(node) + shift}px`, left: `${position.left}px`, width: `${position.width}px`, height: `${position.height}px`, @@ -153,6 +159,14 @@ export function createSidebarListMotion(parent: HTMLUListElement) { positions !== null && !reducedMotion?.matches && fadeCount <= MAX_FADED_ROWS_PER_UPDATE; + // A removal near the bottom shrinks the list and the browser clamps scrollTop, moving + // every row on screen; offsets include that shift so those rows slide instead of jump. + let shift = 0; + if (scroller !== null) { + const max = scroller.scrollHeight - scroller.clientHeight; + if (scrollTop > max && scroller.scrollTop >= max - 1) + shift = scroller.scrollTop - scrollTop; + } const movedDelta = new Map(); const nextOrder = [...next.keys()]; const oldOrder = positions === null ? [] : [...positions.keys()]; @@ -173,13 +187,13 @@ export function createSidebarListMotion(parent: HTMLUListElement) { else { for (const [node, position] of next) { const previousTop = positions!.get(node)?.top; - if (previousTop === undefined || previousTop === position.top) continue; - movedDelta.set(node, previousTop + remainingOffset(node) - position.top); + if (previousTop === undefined || previousTop + shift === position.top) continue; + movedDelta.set(node, previousTop + remainingOffset(node) - position.top + shift); } for (const [node, position] of positions!) { if (next.has(node)) continue; const delta = ridingDelta(oldOrder, oldOrder.indexOf(node), (n) => next.has(n)); - fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta); + fadeOut(node, position, delta === undefined ? rowTravel(position.height) : -delta, shift); } } for (const [node, entry] of entering) { @@ -233,6 +247,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { released = null; } positions = next; + if (scroller !== null) scrollTop = scroller.scrollTop; }, release() { suspend(); @@ -246,6 +261,7 @@ export function createSidebarListMotion(parent: HTMLUListElement) { suspend, dispose() { suspend(); + scroller?.removeEventListener("scroll", trackScroll); disposed = true; }, }; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index c210b38d9b7e8..ce05191c7945b 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -172,7 +172,6 @@ import { resolveThreadRouteTarget, } from "../threadRoutes"; import type { SidebarThreadSummary } from "../types"; -import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { cn } from "~/lib/utils"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { ProjectRowActions } from "./ProjectComboboxRow"; @@ -277,7 +276,12 @@ import { type SidebarProviderEntry, type SidebarSweepAction, } from "./sidebar/SidebarThreadRow"; -import { SidebarDraftBlock, useSidebarDrafts } from "./sidebar/SidebarDraftBlock"; +import { + draftTerminalLabel, + SidebarDraftBlock, + useDraftTerminalLabels, + useSidebarDrafts, +} from "./sidebar/SidebarDraftBlock"; import { SidebarProjectFolderHeader, sidebarFolderRowId, @@ -438,6 +442,7 @@ function useSidebarThreads(input: { readonly threads: readonly EnvironmentThreadShell[]; readonly delegatedUnderParent: ReadonlySet; readonly routeRowThreadKey: string | null; + readonly departingThreadKey: string | null; // Set in boring mode: the project groups to fold active threads into, in order. readonly folderGroups: readonly SidebarProjectSnapshot[] | null; // Keeps folders with no active threads, so a project the user filtered to or pinned can start one. @@ -453,9 +458,11 @@ function useSidebarThreads(input: { threads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups, keepEmptyFolders: keepEmpty, } = input; + const shelfRouteThreadKey = routeRowThreadKey === departingThreadKey ? null : routeRowThreadKey; // Folders already separate the work, so boring mode has no Working shelf. const workingShelfEnabled = useClientSettings((s) => s.sidebarWorkingShelfEnabled) && folderGroups === null; @@ -532,11 +539,11 @@ function useSidebarThreads(input: { const visibleSettledThreads = (() => { const visible = listedSettledThreads.slice(0, settledVisibleCount); if ( - routeRowThreadKey !== null && - !visible.some((thread) => threadShellKey(thread) === routeRowThreadKey) + shelfRouteThreadKey !== null && + !visible.some((thread) => threadShellKey(thread) === shelfRouteThreadKey) ) { const routeThread = settledThreads.find( - (thread) => threadShellKey(thread) === routeRowThreadKey, + (thread) => threadShellKey(thread) === shelfRouteThreadKey, ); if (routeThread !== undefined) visible.push(routeThread); } @@ -544,10 +551,10 @@ function useSidebarThreads(input: { })(); const renderedSettledThreads = settledShelfExpanded ? visibleSettledThreads - : routeThreadOnly(visibleSettledThreads, routeRowThreadKey); + : routeThreadOnly(visibleSettledThreads, shelfRouteThreadKey); const visibleSnoozedThreads = snoozedShelfExpanded ? snoozedThreads - : routeThreadOnly(snoozedThreads, routeRowThreadKey); + : routeThreadOnly(snoozedThreads, shelfRouteThreadKey); const visibleWorkingThreads = workingShelfExpanded ? workingThreads : routeThreadOnly(workingThreads, routeRowThreadKey); @@ -1214,20 +1221,14 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve setPersistedProjectScopeKeys([]); }, [clearSelection, revealWidensScope, setPersistedProjectScopeKeys]); const revealActiveRow = useActiveRowReveal(routeReveal, routeRowThreadKey, routeKeyInPlace); + const [departingThreadKey, setDepartingThreadKey] = useState(null); + if (departingThreadKey !== null && departingThreadKey !== routeThreadKey) { + setDepartingThreadKey(null); + } + const departRouteThread = (threadKey: string) => setDepartingThreadKey(threadKey); + const stayOnRouteThread = (threadKey: string) => + setDepartingThreadKey((current) => (current === threadKey ? null : current)); const showProjectEnvironments = projectGroupsSpanEnvironments(projectGroups); - const scratchMachineLabelFor = ( - thread: Pick, - ) => { - if (!showProjectEnvironments) return null; - const project = projectByKey.get(`${thread.environmentId}:${thread.projectId}`); - if ( - !project || - !isScratchProject(project, serverConfigs.get(thread.environmentId)?.scratchWorkspaceRoot) - ) { - return null; - } - return environmentLabelById.get(thread.environmentId) ?? null; - }; // Pinning from a row keeps rows in place while the menu is open. const projectScopeItems = useOrderWhileOpen( lookupProjectScopeItems, @@ -1262,13 +1263,17 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { projectIds: scopedProjectRefs.map((projectRef) => projectRef.projectId) }, ); const routeDraftIdForRows = routeTarget?.kind === "draft" ? routeTarget.draftId : null; + const draftTerminalLabels = useDraftTerminalLabels(); const visibleDraftSessionCount = useComposerDraftStore((store) => { let count = 0; for (const [draftKey, session] of Object.entries(store.draftThreadsByThreadKey)) { if (session.promotedTo != null) { continue; } - if (!composerDraftHasUserContent(store.draftsByThreadKey[draftKey])) { + if ( + draftTerminalLabel(session, draftTerminalLabels) === null && + !composerDraftHasUserContent(store.draftsByThreadKey[draftKey]) + ) { continue; } if ( @@ -1414,6 +1419,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve threads: listedThreads, delegatedUnderParent, routeRowThreadKey, + departingThreadKey, folderGroups: boringSidebarEnabled ? scopedProjectGroups.length === 0 ? // An archived project keeps a folder for its active threads, below the rest. @@ -1503,7 +1509,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve const settledThreadKeysRef = useRef(settledThreadKeys); const snoozedThreadKeysRef = useRef(snoozedThreadKeys); - const { draftIds, routeDraftComposer } = useSidebarDrafts(scopedProjectKeys, routeDraftIdForRows); + const { draftIds, routeDraftComposer } = useSidebarDrafts( + scopedProjectKeys, + routeDraftIdForRows, + draftTerminalLabels, + ); // Draft rows sit above the threads, so jumps and traversal reach them first. // Search hides them, so they drop out while it is open. const listedDraftIds = isSearchingThreads ? EMPTY_DRAFT_IDS : draftIds; @@ -1700,9 +1710,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve if (settlingThreadKeysRef.current.has(threadKey)) return; settlingThreadKeysRef.current.add(threadKey); const navigateAfterSettle = planForwardNavigation(threadKey, opts.coSettlingKeys); + if (navigateAfterSettle) departRouteThread(threadKey); const result = await settleThread(threadRef); settlingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); if (!isAtomCommandInterrupted(result)) { const error = squashAtomCommandFailure(result); toastManager.add( @@ -1725,6 +1737,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSettle?.(); + } else { + stayOnRouteThread(threadKey); } })(); }; @@ -2259,6 +2273,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "settle": { settlingThreadKeysRef.current.add(activeKey); const navigateAfterSettle = planForwardNavigation(activeKey); + if (navigateAfterSettle) departRouteThread(activeKey); const settled = await run(settleThread(threadRef), gt("Failed to settle thread")).finally( () => settlingThreadKeysRef.current.delete(activeKey), ); @@ -2273,6 +2288,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) navigateAfterSettle?.(); + else stayOnRouteThread(activeKey); return; } case "move-active": @@ -2328,9 +2344,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve } snoozingThreadKeysRef.current.add(threadKey); const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys); + if (navigateAfterSnooze) departRouteThread(threadKey); const result = await snoozeThread(threadRef, preset.snoozedUntil); snoozingThreadKeysRef.current.delete(threadKey); if (result._tag === "Failure") { + stayOnRouteThread(threadKey); return isAtomCommandInterrupted(result) ? ({ status: "interrupted" } as const) : ({ status: "failure", error: squashAtomCommandFailure(result) } as const); @@ -2345,6 +2363,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }) ) { navigateAfterSnooze?.(); + } else { + stayOnRouteThread(threadKey); } return { status: "success" } as const; }; @@ -3605,14 +3625,12 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve jumpLabel={ showJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null } - currentEnvironmentId={primaryEnvironmentId} environmentLabel={ environmentLabelById.get(thread.environmentId) ?? null } environmentMachine={ environmentMachineById.get(thread.environmentId) ?? "server" } - scratchMachineLabel={scratchMachineLabelFor(thread)} project={ projectByKey.get(`${thread.environmentId}:${thread.projectId}`) ?? null @@ -3653,6 +3671,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve key="draft-sessions" draftIds={draftIds} routeDraftComposer={routeDraftComposer} + terminalLabels={draftTerminalLabels} jumpLabelByDraftId={draftJumpLabelById} projectByKey={projectByKey} projectDisplayNameByKey={projectDisplayNameByKey} diff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsx index 9c5e7fa3d830d..905d9cb2131fe 100644 --- a/apps/web/src/components/ThreadStatusIndicators.tsx +++ b/apps/web/src/components/ThreadStatusIndicators.tsx @@ -19,7 +19,7 @@ import { type VcsStatusResult, } from "@t3tools/contracts"; import { msg, T, useGT, useMessages } from "gt-react"; -import { FolderGit2Icon, TerminalIcon } from "lucide-react"; +import { TerminalIcon } from "lucide-react"; import { m, type MessageResolver } from "../i18n/messages"; import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments"; import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; @@ -53,7 +53,6 @@ import { } from "./Sidebar.logic"; import type { SidebarThreadSummary } from "../types"; -import { formatWorktreePathForDisplay } from "../worktreeCleanup"; import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip"; import { PULL_REQUEST_STATE_PRESENTATION, @@ -770,41 +769,6 @@ export function ThreadTerminalStatusButton({ ); } -export function ThreadWorktreeIndicator({ - thread, -}: { - thread: Pick; -}) { - const gt = useGT(); - const worktreePath = thread.worktreePath?.trim(); - if (!worktreePath) { - return null; - } - - const displayPath = formatWorktreePathForDisplay(worktreePath); - const tooltip = thread.branch - ? gt("Worktree: {path} ({branch})", { path: displayPath, branch: thread.branch }) - : gt("Worktree: {path}", { path: displayPath }); - - return ( - - - } - > - - - {tooltip} - - ); -} - function ThreadStatusLabel({ status, compact = false, diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index ac4fd905260a8..775b7faf9d51a 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -24,6 +24,7 @@ import { import type { KeybindingCommand, AssistantCitation, + ComposerContextId, ResponseContextRecord, ChatAttachment as ContractChatAttachment, ChatFileAttachment, @@ -128,6 +129,7 @@ import { useComposerTriggerState } from "./useComposerTriggerState"; import { useComposerMenuItems } from "./useComposerMenuItems"; import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; import { + type QueuedAttachmentContextBinding, reconcileAttachmentContextReferences, useRetainedContextPayloads, } from "./composerContextUndo"; @@ -142,7 +144,8 @@ import { fileAttachmentCapabilityBlockReason, fileAttachmentStagingLimit, isPreviewableComposerVideo, - isImageOnlyClipboardHtml, + clipboardHtmlImageContent, + imagesToAttachBesidePastedText, shouldHandleComposerAttachmentPaste, } from "./composerAttachmentFiles"; import { @@ -318,6 +321,7 @@ import { useComposerImageGroups } from "./useComposerImageGroups"; import { useComposerStash } from "./useComposerStash"; import { useComposerContextImport } from "./useComposerContextImport"; import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; +import { isQueuedFileAttachment, isQueuedImageAttachment } from "./queuedMessageEdit"; import { cancelHeldComposerSend, countPreparingComposerImages, @@ -507,8 +511,11 @@ export interface ChatComposerProps { editingQueuedAttachments: ReadonlyArray<{ readonly attachment: ContractChatAttachment; readonly url: string | null; + readonly contextIds?: ReadonlyArray | undefined; }> | null; + removedEditingQueuedAttachments?: ReadonlyArray | undefined; onRemoveEditingQueuedAttachment: (attachmentId: string) => void; + onRestoreEditingQueuedAttachment?: ((attachment: ContractChatAttachment) => void) | undefined; onCompactContext: () => void; onSend: ( @@ -663,7 +670,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) onExpandImage, onFileOpen, editingQueuedAttachments, + removedEditingQueuedAttachments, onRemoveEditingQueuedAttachment, + onRestoreEditingQueuedAttachment, } = props; const activeContextWindow = deriveLatestContextWindowSnapshot( contextWindowEntries, @@ -726,6 +735,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) activePendingProgress.activeQuestion.id, ) : null; + const queuedEditOwnsComposer = + questionAttachmentTarget === null && pendingUserInputs.length === 0; + const activeEditingQueuedAttachments = queuedEditOwnsComposer ? editingQueuedAttachments : null; + const activeRemovedEditingQueuedAttachments = queuedEditOwnsComposer + ? removedEditingQueuedAttachments + : undefined; const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); const questionTakesSnapShots = @@ -829,33 +844,55 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cwd: gitCwd ?? undefined, projectId: activeProjectId ?? undefined, expandImage: (imageId: string) => { - const preview = buildExpandedImagePreview( - composerImages, - imageId, - copyComposerSnapshotStable, - ); + const preview = + buildExpandedImagePreview(composerImages, imageId, copyComposerSnapshotStable) ?? + buildExpandedImagePreview( + (activeEditingQueuedAttachments ?? []).flatMap(({ attachment, url }) => + isQueuedImageAttachment(attachment) && url ? [{ ...attachment, previewUrl: url }] : [], + ), + imageId, + ); if (preview) onExpandImage(preview); }, - openFile: setPreviewFileId, + openFile: (fileId: string) => { + if (composerFiles.some((file) => file.id === fileId)) { + setPreviewFileId(fileId); + return; + } + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (queuedFile && isQueuedFileAttachment(queuedFile)) onFileOpen(queuedFile); + }, openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), expandVideo: (fileId: string) => { const file = composerFiles.find((candidate) => candidate.id === fileId); - if (!file || !isVideoAttachment(file)) return; - const localPreview = buildExpandedImagePreview([file], file.id); - if (localPreview) { - onExpandImage(localPreview); + if (file && isVideoAttachment(file)) { + const localPreview = buildExpandedImagePreview([file], file.id); + if (localPreview) { + onExpandImage(localPreview); + return; + } + if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + return; + } + const persistedPreview = buildAttachmentVideoPreview(environmentId, { + type: "file", + id: file.uploadedAttachmentId, + name: file.name, + mimeType: file.mimeType, + sizeBytes: file.sizeBytes, + }); + if (persistedPreview) onExpandImage(persistedPreview); return; } - if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { + const queuedFile = activeEditingQueuedAttachments?.find( + ({ attachment }) => isQueuedFileAttachment(attachment) && attachment.id === fileId, + )?.attachment; + if (!queuedFile || !isQueuedFileAttachment(queuedFile) || !isVideoAttachment(queuedFile)) { return; } - const persistedPreview = buildAttachmentVideoPreview(environmentId, { - type: "file", - id: file.uploadedAttachmentId, - name: file.name, - mimeType: file.mimeType, - sizeBytes: file.sizeBytes, - }); + const persistedPreview = buildAttachmentVideoPreview(environmentId, queuedFile); if (persistedPreview) onExpandImage(persistedPreview); }, openPullRequest: (event: React.MouseEvent, url: string) => { @@ -871,6 +908,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) environmentContexts: composerEnvironmentContexts, images: composerImages, files: composerFiles, + existingAttachments: activeEditingQueuedAttachments ?? undefined, + environmentId, uploadsByImageId, }); const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; @@ -1504,12 +1543,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) : null); if (!record) return []; if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); - return [ - record.kind === "image" && attachment.type === "image" && attachment.source - ? { ...record, source: attachment.source } - : record, - ]; + return [record]; }), + ...(activeEditingQueuedAttachments ?? []).flatMap(({ attachment, contextIds }) => { + if (!isQueuedImageAttachment(attachment) && !isQueuedFileAttachment(attachment)) return []; + return (contextIds ?? []) + .filter((contextId) => wanted.has(contextId)) + .map((contextId) => + attachmentContextRecord({ + attachment, + attachmentId: attachment.id, + contextId, + }), + ); + }), ]; if (records.length === 0) return null; const fragment = encodeComposerContextFragment({ @@ -1558,6 +1605,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) promptRef, pendingThreadImportsRef, addComposerFilesToDraft, + removedQueuedAttachments: activeRemovedEditingQueuedAttachments, + onRestoreQueuedAttachment: onRestoreEditingQueuedAttachment, }); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers @@ -1763,6 +1812,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) cursorAdjacentToMention: boolean, contextIds: string[], textChanged: boolean, + fromHistory = false, ) => { refreshWorkspaceSnapshotOnTyping(); const trigger = cursorAdjacentToMention @@ -1883,6 +1933,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const attachmentChanges = reconcileAttachmentContextReferences({ referencedContextIds: referenced, files: composerFiles, + queuedAttachments: (activeEditingQueuedAttachments ?? []).map( + ({ attachment, contextIds }) => ({ + attachment, + contextIds: contextIds ?? [], + }), + ), + removedQueuedAttachments: activeRemovedEditingQueuedAttachments ?? [], + fromHistory, images: composerImages, previewAnnotations: composerPreviewAnnotations, retained: retainedContextPayloads, @@ -1902,6 +1960,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) if (attachmentChanges.filesToRestore.length > 0) { addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); } + for (const attachmentId of attachmentChanges.queuedAttachmentIdsToRemove) { + onRemoveEditingQueuedAttachment(attachmentId); + } + for (const attachment of attachmentChanges.queuedAttachmentsToRestore) { + onRestoreEditingQueuedAttachment?.(attachment); + } setComposerCursor(nextCursor); updateTrigger(trigger); }; @@ -3110,18 +3174,19 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const pastedContext = !isLiteralPendingAnswer && (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; + const canAttachFiles = !pastedContext && activeThreadId !== null && files.length > 0; + const htmlImageContent = + canAttachFiles && plainText.length > 0 + ? clipboardHtmlImageContent(event.clipboardData.getData("text/html")) + : "none"; if ( folders.length > 0 || - (!pastedContext && - activeThreadId && - files.length > 0 && + (canAttachFiles && shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment, - htmlIsOnlyImage: - plainText.length > 0 && - isImageOnlyClipboardHtml(event.clipboardData.getData("text/html")), + htmlIsOnlyImage: htmlImageContent === "only-image", })) ) { event.preventDefault(); @@ -3134,6 +3199,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) } if (pastedContext) return; + const imagesBesideText = imagesToAttachBesidePastedText({ + files, + plainText, + bypassAutoAttachment, + htmlHasImageAndText: htmlImageContent === "image-and-text", + }); + if (imagesBesideText.length > 0) void addComposerAttachments(imagesBesideText); if (!foldPastedText(plainText, bypassAutoAttachment)) { return; } @@ -3991,11 +4063,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) )} {!isComposerCollapsedMobile && - pendingUserInputs.length === 0 && - editingQueuedAttachments !== null && - editingQueuedAttachments.length > 0 && ( + activeEditingQueuedAttachments !== null && + activeEditingQueuedAttachments.length > 0 && ( )} diff --git a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx index 3d704b5209305..c3691e80f2710 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.browser.test.tsx @@ -123,3 +123,27 @@ it("draws an agent's reasoning as bars and keeps its mode out of the levels", as .toBeInTheDocument(); await expect.element(page.getByRole("menuitemradio")).not.toBeInTheDocument(); }); + +it("focuses a reasoning level by its first letter without selecting it", async () => { + await using screen = await render(, { router: false }); // no routes involved + await userEvent.tab(); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("l"); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + await expect + .element(screen.getByRole("radio", { name: "Medium" })) + .toHaveAttribute("aria-checked", "true"); + for (const key of ["{Control>}h{/Control}", "{Meta>}h{/Meta}", "{Alt>}h{/Alt}", "{Delete}"]) { + await userEvent.keyboard(key); + await expect.element(screen.getByRole("radio", { name: "Low" })).toHaveFocus(); + } + await userEvent.keyboard("H"); + await expect.element(screen.getByRole("radio", { name: "High" })).toHaveFocus(); + // Wraps past the last level back to the first match. + await userEvent.keyboard("m"); + await expect.element(screen.getByRole("radio", { name: "Medium" })).toHaveFocus(); + await userEvent.keyboard("h{Enter}"); + await expect + .element(screen.getByRole("radio", { name: "High" })) + .toHaveAttribute("aria-checked", "true"); +}); diff --git a/apps/web/src/components/chat/ComposerModelEffort.tsx b/apps/web/src/components/chat/ComposerModelEffort.tsx index 1d0227c0f6482..b5d5a519a3410 100644 --- a/apps/web/src/components/chat/ComposerModelEffort.tsx +++ b/apps/web/src/components/chat/ComposerModelEffort.tsx @@ -206,8 +206,8 @@ function ColumnRow(props: { "aria-checked": props.selected, disabled: props.disabled, "data-effort-row": true, - // Focus lands on a level after a model pick. - "data-effort-level": true, + // Focus lands on a level after a model pick, and a typed letter finds one by its label. + "data-effort-level": props.label, // Up and Down move between rows. tabIndex: props.tabStop ? 0 : -1, className: COLUMN_ROW, @@ -244,15 +244,28 @@ function ColumnRow(props: { } function moveBetweenRows(event: KeyboardEvent) { - if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; + const arrow = event.key === "ArrowDown" || event.key === "ArrowUp"; + if ( + !arrow && + (event.key.length !== 1 || + event.key.trim() === "" || + event.ctrlKey || + event.altKey || + event.metaKey || + event.nativeEvent.isComposing) + ) + return; // An option's side menu is a React child here, but it moves through its own items. if (!event.currentTarget.contains(event.target as Node)) return; const rows = Array.from( event.currentTarget.querySelectorAll("[data-effort-row]:not(:disabled)"), ); const index = rows.findIndex((row) => row === document.activeElement); - const next = - rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))]; + const next = arrow + ? rows[Math.min(rows.length - 1, Math.max(0, index + (event.key === "ArrowDown" ? 1 : -1)))] + : [...rows.slice(index + 1), ...rows.slice(0, index + 1)].find((row) => + row.dataset.effortLevel?.toLowerCase().startsWith(event.key.toLowerCase()), + ); if (!next) return; event.preventDefault(); event.stopPropagation(); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index c55d843510080..46e3fec307bf1 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -3,6 +3,7 @@ import { BookmarkIcon, FileIcon, FileTextIcon } from "lucide-react"; import { memo, useEffect, useEffectEvent, useRef, useState, type RefObject } from "react"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { RelativeTime } from "../RelativeTime"; import { m, type MessageResolver } from "~/i18n/messages"; @@ -18,7 +19,9 @@ function missingImageCount(entry: PromptStashEntry): number { export function stashEntrySnippet(entry: PromptStashEntry, resolve: MessageResolver = m): string { const trimmed = assistantCitationsToPlainText( - replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(entry.prompt, (reference) => reference.label), + ), ) .trim() .replace(/\s+/g, " "); diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 0a703a675f0ac..76dc0aa6471bf 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -4744,7 +4744,29 @@ describe("failed turn transcript", () => { ); expect(work.at(-1)?.detail).toBe("The provider stopped this turn.\nRetry later."); expect(work.at(-1)?.createdAt).toBe("2026-09-20T12:00:00.000Z"); - if (isLatest) return; + if (isLatest) { + // The recovery notice hides the failure row; the run's work stays grouped. + const noticeRows = deriveMessagesTimelineRows({ + timelineEntries: deriveTimelineEntriesFromVisibleTurnItems({ + visibleTurnItems: items.filter((row) => row.item.type !== "error"), + optimisticMessages: [], + }), + latestRun: { + runId, + status: "failed", + startedAt: DateTime.formatIso(at), + completedAt: DateTime.formatIso(at), + }, + usageLimitRunId: runId, + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(noticeRows.find((row) => row.kind === "work-toggle")).toEqual( + expect.objectContaining({ hiddenCount: 3, expanded: false }), + ); + return; + } const entriesWithoutTools = deriveTimelineEntriesFromVisibleTurnItems({ visibleTurnItems: items.filter((row) => row.item.type !== "command_execution"), optimisticMessages: [], diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index 6559f85af24ce..9158dca59d06c 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -1056,8 +1056,9 @@ function failedTimelineRunIds( function itemizedFailedRunIds( entries: ReadonlyArray, failedRunIds: ReadonlySet, + usageLimitRunId: RunId | null, ) { - const usageLimited = new Set(); + const usageLimited = new Set(usageLimitRunId ? [usageLimitRunId] : []); const otherFailures = new Set(); for (const entry of entries) { const item = timelineEntryFailedItem(entry); @@ -1612,6 +1613,8 @@ export function deriveMessagesTimelineRows( timelineEntries: ReadonlyArray; pendingApprovalRequestIds?: ReadonlySet; latestRun?: TimelineLatestRun | null; + /** The usage-limited run whose failure row the recovery notice replaces. */ + usageLimitRunId?: RunId | null; runningRunId?: RunId | null; expandedRunIds?: ReadonlySet; expandedAttemptIds?: ReadonlySet; @@ -1665,7 +1668,11 @@ export function deriveMessagesTimelineRows( const nextRows: MessagesTimelineRow[] = []; const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(timelineEntries); const failedRunIds = failedTimelineRunIds(timelineEntries, input.latestRun ?? null); - const itemizedRunIds = itemizedFailedRunIds(timelineEntries, failedRunIds); + const itemizedRunIds = itemizedFailedRunIds( + timelineEntries, + failedRunIds, + input.usageLimitRunId ?? null, + ); const liveSubagentEntryIds = liveSubagentCardEntryIds(timelineEntries); const retainedAssistantReplyIds = retainedAssistantReplyEntryIds(timelineEntries); const supersededFoldsByAnchorEntryId = deriveSupersededAttemptFolds( diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 8393d725d9ee1..acc965b981b05 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -258,6 +258,7 @@ interface MessagesTimelineProps { listRef: React.RefObject; timelineEntries: ReadonlyArray; latestRun: TimelineLatestRun | null; + usageLimitRunId?: RunId | null; /** The run the screen reader announcer follows; see announcedRun. */ announcedRun?: { readonly runId: RunId; readonly status: TimelineLatestRun["status"] } | null; /** See isDetailBehindShell. */ @@ -384,6 +385,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ activeFindMatch = null, findNavigationId = 0, latestRun, + usageLimitRunId = null, announcedRun = null, detailBehindShell = false, runningRunId = null, @@ -755,6 +757,7 @@ const ConversationTimeline = memo(function ConversationTimeline({ timelineEntries, pendingApprovalRequestIds, latestRun, + usageLimitRunId, runningRunId, expandedRunIds: visibleExpandedRunIds, expandedAttemptIds: visibleExpandedAttemptIds, diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx index d8318b7279e7d..20ea71f88adcd 100644 --- a/apps/web/src/components/chat/QueuedRunsControl.tsx +++ b/apps/web/src/components/chat/QueuedRunsControl.tsx @@ -10,6 +10,7 @@ import { isAttachmentOnlyBootstrapPrompt, replaceComposerContextReferences, } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { parseGoalCommand, type ChatAttachment as ContractChatAttachment, @@ -272,7 +273,9 @@ export function QueuedRunsControl({ const previewText = isAttachmentOnlyBootstrapPrompt(item.text) ? "" : assistantCitationsToPlainText( - replaceComposerContextReferences(item.text, (reference) => reference.label), + composerFileLinksToPlainText( + 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. diff --git a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx index 076c78d88d468..8b4bb6232287b 100644 --- a/apps/web/src/components/chat/RightPanelSurfaceContent.tsx +++ b/apps/web/src/components/chat/RightPanelSurfaceContent.tsx @@ -141,9 +141,14 @@ export function RightPanelSurfaceContent(props: { getShortcutContext={props.getShortcutContext} shortcutsEnabled={visible && props.activeSurfaceId === surface.id} key={`${scopedThreadKey(threadRef)}:${surface.id}`} - environmentId={props.environmentId} + environmentId={ + (surface.environmentId as EnvironmentId | undefined) ?? props.environmentId + } onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, @@ -205,12 +210,24 @@ export function RightPanelSurfaceContent(props: { threadRef={threadRef} onSelectPullRequest={(reference) => { useRightPanelStore.getState().openPullRequest(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), projectId: reference.projectId, repository: reference.repository, number: reference.number, ...(reference.host ? { host: reference.host } : {}), }); }} + onSelectIssue={({ host, ...reference }) => { + useRightPanelStore.getState().openIssue(threadRef, { + ...(surface.environmentId === undefined + ? {} + : { environmentId: surface.environmentId }), + ...reference, + ...(host ? { host } : {}), + }); + }} /> ); case "pull-requests": diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx index 052a5742b7aab..666ce784b3afc 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.browser.test.tsx @@ -236,6 +236,48 @@ it("opens an idle child beside the thread, and in its place with the modifier", expect(panel().surfaces).toHaveLength(1); }); +it("keeps focus on the list when Show more pages reveal the last rows", async () => { + setup(); + const projection = makeThreadProjectionFixture(); + const environmentId = EnvironmentId.make("local"); + const { updatedAt } = projection.thread; + state.projection = { + ...projection, + subagents: Array.from({ length: 7 }, (_, index) => ({ + id: NodeId.make(`agent-${index}`), + threadId: projection.thread.id, + runId: null, + parentNodeId: NodeId.make("parent"), + origin: "app_owned", + createdBy: "agent", + driver: "codex", + providerInstanceId: projection.thread.providerInstanceId, + providerThreadId: null, + childThreadId: ThreadId.make(`omitted-child-${index}`), + nativeTaskRef: null, + prompt: `Inspect the change part ${index}`, + title: `Agent ${index}`, + model: null, + status: "completed", + result: null, + startedAt: null, + completedAt: updatedAt, + updatedAt, + })), + }; + await using screen = await render( + , + ); + await screen.getByRole("button", { name: /Previous agents/ }).click(); + await screen.getByRole("button", { name: "Show 1 more" }).click(); + await expect.element(screen.getByRole("list", { name: "Related threads" })).toHaveFocus(); +}); + it("shows a lineage thread's full title in its tooltip", async () => { setup(); const longTitle = "Compare the lineage tooltip against a title that the row truncates"; diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index 93feaf0178f26..a754fa7500745 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -122,19 +122,28 @@ function ThreadLineageRowList(props: { readonly children: ReactNode; }) { const gt = useGT(); + const listRef = useRef(null); + const showMore = () => { + const exhausting = props.hiddenCount <= THREAD_LINEAGE_PAGE_COUNT; + props.onShowMore(); + // The button unmounts on the final page; focus the list so focus isn't dropped. + if (exhausting) listRef.current?.focus({ preventScroll: true }); + }; return ( <> {/* ScrollArea's max-height viewport measures badly inside this scrolling panel. */}
    {props.children}
{props.hiddenCount > 0 ? ( ) : ( diff --git a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx index 4cd0c045560c2..2a2764301013d 100644 --- a/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx +++ b/apps/web/src/components/settings/LinkedEnvironmentsSettings.tsx @@ -668,7 +668,7 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu const forget = async () => { const confirmed = await (requestConfirmDialog( gt( - "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", { label: link.label }, ), { variant: "destructive" }, @@ -677,7 +677,18 @@ export function useForgetPeerLink(environmentId: EnvironmentId, link: PeerLinkSu setBusy(true); const result = await unlink({ environmentId, input: { environmentId: link.environmentId } }); setBusy(false); - if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { + if (result._tag === "Success") { + if (result.value.removed && result.value.endedThere !== true) { + toastManager.add({ + type: "warning", + title: gt("{label} did not answer", { label: link.label }), + description: gt( + "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + { label: link.label }, + ), + }); + } + } else if (!isAtomCommandInterrupted(result)) { failureToast(gt("Could not forget the link"), String(squashAtomCommandFailure(result))); } }; diff --git a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx index ea6868ed3dc93..6ea4694620c23 100644 --- a/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx +++ b/apps/web/src/components/settings/ProjectRepositoriesSettings.tsx @@ -338,7 +338,9 @@ function AddTrackedFolderDialog(props: { key={entry.fullPath} type="button" className={rowClassName} - onClick={() => setQuery(appendBrowsePathSegment(query, entry.name))} + onClick={() => + setQuery(appendBrowsePathSegment(browsePath.directoryPath, entry.name)) + } > {entry.name} diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx index 7ba2d17d7291d..417868799a18d 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.browser.test.tsx @@ -279,4 +279,18 @@ describe("ScheduledTasksSettings", () => { await expect.element(dialog.getByRole("heading", { name: "New task" })).toBeInTheDocument(); await expect.element(name).toHaveValue("My draft"); }); + + it("keeps a new task's draft when the user clicks outside the editor", async () => { + setup(); + await using _screen = await render(); + await userEvent.click(page.getByRole("button", { name: "New task" })); + const dialog = page.getByRole("dialog"); + const name = dialog.getByRole("textbox", { name: "Name" }); + await userEvent.fill(name, "My draft"); + + await userEvent.click(document.body, { position: { x: 1, y: 1 } }); + + await expect.element(dialog).toHaveAttribute("data-open"); + await expect.element(name).toHaveValue("My draft"); + }); }); diff --git a/apps/web/src/components/settings/ScheduledTasksSettings.tsx b/apps/web/src/components/settings/ScheduledTasksSettings.tsx index 8b43576b7a5aa..6792a7cd1d515 100644 --- a/apps/web/src/components/settings/ScheduledTasksSettings.tsx +++ b/apps/web/src/components/settings/ScheduledTasksSettings.tsx @@ -1271,6 +1271,8 @@ function ScheduledTaskEditorDialog({ return ( { if (!open && !saving) onClose(); }} diff --git a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx index 8eecf79f5d33a..fd5b90f9c6c19 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.browser.test.tsx @@ -157,6 +157,58 @@ it("sizes an oversized theme file just under 1 MB as 1.00 MB", async () => { ); }); +it.each(["failed read", "batch install"])( + "keeps the oversized replacement warning after a superseded %s", + async (earlierImport) => { + using _themes = isolateThemes(); + await using _screen = await render( + {}} + onImported={() => true} + onImportedMany={() => {}} + />, + ); + const earlierRead = Promise.withResolvers(); + const readStarted = Promise.withResolvers(); + const earlierFile = Object.assign(themeFile("Dusk"), { + text() { + readStarted.resolve(); + return earlierRead.promise; + }, + }); + const input = document.querySelector('input[type="file"]')!; + const files = new DataTransfer(); + if (earlierImport === "batch install") files.items.add(themeFile("Dawn")); + files.items.add(earlierFile); + await act(async () => { + input.files = files.files; + input.dispatchEvent(new Event("change", { bubbles: true })); + await readStarted.promise; + }); + await expect.element(page.getByRole("button", { name: "Reading…" })).toBeDisabled(); + await userEvent.upload( + input, + new File([" ".repeat(256 * 1024 + 1)], earlierFile.name, { type: "application/json" }), + ); + const warning = page.getByText(/^That file is/); + await expect.element(warning).toBeVisible(); + + await act(async () => { + if (earlierImport === "batch install") { + earlierRead.resolve(JSON.stringify(theme("Dusk"))); + } else { + earlierRead.reject(new Error("Could not read Dusk")); + } + await earlierRead.promise.catch(() => {}); + }); + + expect(getCustomThemes().map((theme) => theme.label)).toEqual([]); + expect(page.getByRole("alert").element().textContent).toMatch(/^That file is/); + await expect.element(page.getByRole("button", { name: "Choose files" })).toBeEnabled(); + }, +); + function themeJsonc(name: string, background: string) { return `{ // VS Code themes use JSONC even with a .json extension. diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsx index 189560efdee9e..aeac23821884f 100644 --- a/apps/web/src/components/settings/ThemeImportDialog.tsx +++ b/apps/web/src/components/settings/ThemeImportDialog.tsx @@ -233,19 +233,20 @@ function ThemeImportBody({ const [isReading, setIsReading] = useState(false); const [isDropTarget, setIsDropTarget] = useState(false); const [conflicts, setConflicts] = useState | null>(null); - // A newer read supersedes an older one still in flight. + // A new file selection supersedes a pending import even if the selection is rejected. const importRequestRef = useRef(0); const isCurrentRequest = (requestId: number) => requestId === importRequestRef.current && !signal.aborted; const readThemeFile = async (file: ImportableThemeFile) => { + const requestId = ++importRequestRef.current; const oversized = describeOversizedThemeFile(file.size); if (oversized) { + setIsReading(false); setError(oversized); return; } - const requestId = ++importRequestRef.current; setIsReading(true); const fileText = await settlePromise(() => file.text()); if (!isCurrentRequest(requestId)) return; diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index 7b7adf7a31ea5..9e2e6a058f220 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -8,16 +8,24 @@ import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock, useSidebarDrafts } from "./SidebarDraftBlock"; -function DraftBlock() { - const { draftIds, routeDraftComposer } = useSidebarDrafts(null, null); +const NO_TERMINAL_LABELS: ReadonlyMap = new Map(); + +function DraftBlock(props: { + routeDraftId?: string | null; + terminalLabels?: ReadonlyMap; +}) { + const routeDraftId = props.routeDraftId ?? null; + const terminalLabels = props.terminalLabels ?? NO_TERMINAL_LABELS; + const { draftIds, routeDraftComposer } = useSidebarDrafts(null, routeDraftId, terminalLabels); return ( @@ -91,3 +99,42 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.clearDraftThread(nextDraftId)); await expect.element(row).not.toBeInTheDocument(); }); + +it("lists empty drafts by terminal label while their terminal exists, active or not", async () => { + const initial = useComposerDraftStore.getState(); + using _store = { + [Symbol.dispose]: () => useComposerDraftStore.setState(initial, true), + }; + useComposerDraftStore.setState({ + draftsByThreadKey: {}, + draftThreadsByThreadKey: {}, + logicalProjectDraftThreadKeyByLogicalProjectKey: {}, + }); + const environmentId = EnvironmentId.make("draft-terminal-environment"); + const terminalDraftId = DraftId.make("draft-with-terminal"); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("terminal-project")), + terminalDraftId, + { threadId: ThreadId.make("terminal-thread") }, + ); + initial.setProjectDraftThreadId( + scopeProjectRef(environmentId, ProjectId.make("idle-project")), + DraftId.make("draft-without-terminal"), + { threadId: ThreadId.make("idle-thread") }, + ); + + const terminalLabels = new Map([[`${environmentId}:terminal-thread`, "dev"]]); + const block = (routeDraftId: string | null) => ( +
    + +
+ ); + await using screen = await render(block(terminalDraftId)); + const rows = screen.getByTestId("sidebar-draft-row"); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); + + await screen.rerender(block(null)); + await expect.element(rows).toHaveAccessibleName("dev, Unsent draft"); + expect(rows.elements()).toHaveLength(1); +}); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index 3a4a74bb64f18..e0b0d92a764ac 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -3,6 +3,7 @@ import type { ContextMenuSource } from "@t3tools/contracts"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { T, useGT } from "gt-react"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -12,8 +13,10 @@ import { type MouseEvent as ReactMouseEvent, } from "react"; import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; +import type { EnvironmentId } from "@t3tools/contracts"; import { useShallow } from "zustand/react/shallow"; import { cn } from "~/lib/utils"; +import { useTerminalLabelsByThreadKey } from "~/state/terminalSessions"; import { resolveSidebarRowAccessibility } from "../Sidebar.logic"; import { ProjectFavicon, type ProjectFaviconProject } from "../ProjectFavicon"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -31,9 +34,41 @@ import { JumpHintBadge, } from "./SidebarThreadRow"; +const EMPTY_COMPOSER_PARTS = { + prompt: "", + images: [], + persistedAttachments: [], + files: [], + terminalContexts: [], + previewAnnotations: [], + reviewComments: [], +} as const; + +/** Terminal labels for draft threads; an unsent draft stays listed while it has a terminal. */ +export function useDraftTerminalLabels(): ReadonlyMap { + const environmentIds = useComposerDraftStore((store) => { + const ids = new Set(); + for (const session of Object.values(store.draftThreadsByThreadKey)) { + if (session.promotedTo == null) ids.add(session.environmentId); + } + return [...ids].toSorted().join("\n"); + }); + return useTerminalLabelsByThreadKey( + environmentIds === "" ? [] : (environmentIds.split("\n") as EnvironmentId[]), + ); +} + +export function draftTerminalLabel( + session: DraftSessionState, + terminalLabels: ReadonlyMap, +): string | null { + return terminalLabels.get(`${session.environmentId}:${session.threadId}`) ?? null; +} + const SidebarDraftRow = memo(function SidebarDraftRow(props: { draftId: DraftId; - composer: ComposerThreadDraftState; + composer: ComposerThreadDraftState | null; + terminalLabel: string | null; project: ProjectFaviconProject | null; projectDisplayName: string | null; isActive: boolean; @@ -46,11 +81,14 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { source: ContextMenuSource, ) => void; }) { - const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; + const { draftId, onContextMenu, onDiscard, onNavigate } = props; + const composer = props.composer ?? EMPTY_COMPOSER_PARTS; const gt = useGT(); const promptPreview = assistantCitationsToPlainText( - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + composerFileLinksToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ), ) .trim() .split("\n", 1)[0] ?? ""; @@ -65,9 +103,11 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { const preview = promptPreview.length > 0 ? promptPreview - : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { - count: attachmentCount, - }); + : attachmentCount === 0 && props.terminalLabel !== null + ? props.terminalLabel + : gt("{count, plural, one {{count} attachment} other {{count} attachments}}", { + count: attachmentCount, + }); const accessibility = resolveSidebarRowAccessibility({ title: preview, statusLabel: gt("Unsent draft"), @@ -174,6 +214,7 @@ function listedDraftComposer(draftId: string | null): ComposerThreadDraftState | export function useSidebarDrafts( scopedProjectKeys: ReadonlySet | null, routeDraftId: string | null, + terminalLabels: ReadonlyMap, ): { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null } { const [frozenRoute, setFrozenRoute] = useState<{ routeDraftId: string | null; @@ -195,10 +236,12 @@ export function useSidebarDrafts( ) { continue; } + // Composer edits stay frozen while open; terminals come and go live. const isListed = - draftKey === routeDraftId + draftTerminalLabel(session, terminalLabels) !== null || + (draftKey === routeDraftId ? routeDraftComposer !== null - : composerDraftHasUserContent(store.draftsByThreadKey[draftKey]); + : composerDraftHasUserContent(store.draftsByThreadKey[draftKey])); if (isListed) listed.push([draftKey, session]); } listed.sort(([, left], [, right]) => right.createdAt.localeCompare(left.createdAt)); @@ -211,6 +254,7 @@ export function useSidebarDrafts( export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { draftIds: readonly DraftId[]; routeDraftComposer: ComposerThreadDraftState | null; + terminalLabels: ReadonlyMap; jumpLabelByDraftId: ReadonlyMap | null; projectByKey: ReadonlyMap; projectDisplayNameByKey: ReadonlyMap; @@ -233,8 +277,10 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { const drafts = props.draftIds.flatMap((draftId) => { const session = draftThreadsByThreadKey[draftId]; const composer = - draftId === props.routeDraftId ? props.routeDraftComposer : draftsByThreadKey[draftId]; - return session && composer ? [{ draftId, session, composer }] : []; + (draftId === props.routeDraftId ? props.routeDraftComposer : null) ?? + draftsByThreadKey[draftId] ?? + null; + return session ? [{ draftId, session, composer }] : []; }); if (drafts.length === 0) { return null; @@ -248,6 +294,7 @@ export const SidebarDraftBlock = memo(function SidebarDraftBlock(props: { key={draftId} draftId={draftId} composer={composer} + terminalLabel={draftTerminalLabel(session, props.terminalLabels)} project={props.projectByKey.get(projectKey) ?? null} projectDisplayName={props.projectDisplayNameByKey.get(projectKey) ?? null} isActive={draftId === props.routeDraftId} diff --git a/apps/web/src/components/sidebar/SidebarThreadRow.tsx b/apps/web/src/components/sidebar/SidebarThreadRow.tsx index 878cbc894bb88..2aa9be4c244a6 100644 --- a/apps/web/src/components/sidebar/SidebarThreadRow.tsx +++ b/apps/web/src/components/sidebar/SidebarThreadRow.tsx @@ -3,6 +3,7 @@ import { asLaunchingThread } from "@t3tools/client-runtime/state/thread-inbox"; import { ThreadHoverCard, ThreadHoverCardPopup } from "../ThreadHoverCard"; import { ThreadTerminalStatusButton } from "../ThreadStatusIndicators"; import { discardComposerDraft } from "../../lib/discardComposerDraft"; +import { formatWorktreePathForDisplay } from "../../worktreeCleanup"; import { contextMenuSourceOf } from "../../contextMenuSource"; import { requestCustomSnooze } from "../CustomSnoozeDialog"; import { useSupportsMultiplePullRequests } from "~/hooks/useSupportsMultiplePullRequests"; @@ -47,6 +48,7 @@ import { CircleDashedIcon, CircleDotDashedIcon, ClockIcon, + FolderGit2Icon, GitBranchIcon, MessageCircleQuestionIcon, PinIcon, @@ -105,7 +107,6 @@ import { resolveLocalCheckoutBranchMismatch } from "../BranchToolbar.logic"; import { ThreadPullRequestBadgeControl, ThreadPullRequestsMiniList, - ThreadWorktreeIndicator, prStatusIndicator, resolveThreadPullRequestBadge, terminalStatusFromRunningIds, @@ -285,6 +286,7 @@ function SidebarThreadTooltip({ terminalProcessCount: number; }) { const driverKind = providerEntry?.driverKind ?? null; + const worktreePath = thread.worktreePath?.trim(); const previousProviderNames = thread.providerInstanceHistory .filter((instanceId) => instanceId !== modelInstanceId) .map((instanceId) => providerEntryByInstanceId.get(instanceId)?.displayName ?? instanceId); @@ -324,6 +326,12 @@ function SidebarThreadTooltip({
) : null} + {worktreePath ? ( +
+ + +
+ ) : null} {branchMismatch ? (
@@ -575,7 +583,7 @@ function TopStatusIcon(props: { icon: keyof typeof TOP_STATUS_ICONS; className: type SidebarThreadRowProps = { thread: SidebarThreadSummary; // "folder" is a one-line row inside a boring sidebar project folder; - // "folder-multiline" adds the card's branch and PR line under it. + // "folder-multiline" adds the card's environment and PR line under it. variant: "card" | "slim" | "folder" | "folder-multiline"; navigationParent?: string | undefined; variantAction: SidebarSweepAction; @@ -598,10 +606,8 @@ type SidebarThreadRowProps = { // Read at click time; a prop would re-render every row on entering or leaving a thread route. readOpensPullRequestsInRightPanel: () => boolean; jumpLabel: string | null; - currentEnvironmentId: string | null; environmentLabel: string | null; environmentMachine: EnvironmentMachineKind; - scratchMachineLabel: string | null; project: EnvironmentProject | null; projectDisplayName: string | null; providerEntryByInstanceId: ReadonlyMap; @@ -863,9 +869,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP ? getTriggerDisplayModelName(selectedModel, providerEntry?.driverKind) : thread.modelSelection.model; - const isRemote = thread.environmentId !== props.currentEnvironmentId; - const showsScratchMachine = !checkoutThread.branch && props.scratchMachineLabel !== null; - const detailsTooltip = ( - - - ) : null; const diff = latestRunDiff(thread); // Only the trailing icons would remain, so the row moves them to the title line instead. const metaLineEmpty = - !checkoutThread.branch && - !showsScratchMachine && + props.environmentLabel === null && prBadge === null && issueBadge === null && diff === null && runningTerminalIds.length === 0; const metaLine = metaLineEmpty ? null : (
- {checkoutThread.branch ? ( - <> - - - - - - ) : showsScratchMachine ? ( + {props.environmentLabel !== null ? ( <> - {props.scratchMachineLabel} + {props.environmentLabel} ) : ( @@ -1305,7 +1294,6 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: SidebarThreadRowP aria-hidden className="pointer-events-none ml-auto inline-flex shrink-0 items-center gap-1" > - {remoteMachineIcon} - {remoteMachineIcon} - {children} + {observeContent ? ( + // Base UI only observes content resizes through Content; minWidth overrides its fit-content default. + + {children} + + ) : ( + children + )} {!hideScrollbars && ( <> diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsx index adb05afb92ebb..326b592e823db 100644 --- a/apps/web/src/components/usage/UsagePage.tsx +++ b/apps/web/src/components/usage/UsagePage.tsx @@ -519,7 +519,7 @@ export function UsagePage() { - + {selectedEnvironments.length === 0 ? (

diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 0e46547eb77ed..044ecb5d6f618 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} konnte keine WebSocket-Verbindung herstellen.", "d9ce6c142a485959": "{host} hat {seconds} s lang nicht geantwortet.", "d6bdce8f4e6101a4": "{host} wurde getrennt.", + "8450a95e5214d199": "{host} hat ein Update der Serverkonfiguration gesendet, das dieser Client nicht lesen konnte.", + "56b4ff3993c93eca": "{host} hat eine inkompatible Serverkonfiguration gesendet.", + "368c4d4f99c66bfb": "Aktualisiere Client und Server auf kompatible Versionen.", "e5fd422e445391fc": "Upload fehlgeschlagen. Zum Wiederholen tippen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2769,8 +2772,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal-Prozess läuft", "fc2c9a91f498ad6b": "{count, plural, one {{count} Terminal-Prozess läuft. Terminal öffnen} other {{count} Terminal-Prozesse laufen. Terminal öffnen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "Stack", "6831e9a46cbd8939": "Kette", "9aa9e74a3b7eee91": "Zum Chat hinzufügen", @@ -9604,7 +9605,9 @@ "fb71127e5746a6bc": "Unter „Freigabe & Zugriff“ dort oder mit t3 pair", "1e3fee7084791773": "Auch {target} zurück mit {source} verknüpfen", "ea34a190b0bd804c": "Agenten auf {target} können dann auch auf {source} arbeiten.", - "ad5ed0ce61b966eb": "{label} vergessen? Agenten von hier arbeiten dort nicht mehr. Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", + "974f8c65e8b5f492": "{label} vergessen? Agenten hier arbeiten dort nicht mehr, und ihre Sitzung auf {label} endet ebenfalls, wenn es antwortet.", + "6cf9e3083b15614f": "{label} hat nicht geantwortet", + "34ccbdf619b83be3": "Widerrufe „T3 Code · …“ unter „Freigabe & Zugriff“ auf {label}, um die Sitzung auch dort zu beenden.", "81c9796bf61b306a": "Verknüpfung konnte nicht vergessen werden", "130e51beb6cf5aad": "Umgebung verknüpfen", "122c3e355699e69d": "Agenten hier können dort dann Threads starten, ihnen Nachrichten senden und auf sie warten. Sie erscheint unter „Autorisierte Clients“ in „Freigabe & Zugriff“ dieser Umgebung und kann dort widerrufen werden.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f77263e4c8386..53e225d85d6bf 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} could not establish a WebSocket connection.", "d9ce6c142a485959": "{host} stopped responding for {seconds}s.", "d6bdce8f4e6101a4": "{host} disconnected.", + "8450a95e5214d199": "{host} sent a server configuration update this client could not read.", + "56b4ff3993c93eca": "{host} sent an incompatible server configuration.", + "368c4d4f99c66bfb": "Update the client and server to compatible versions.", "e5fd422e445391fc": "Upload failed. Tap to retry.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminal process running", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminal process running. Open terminal} other {{count} terminal processes running. Open terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "chain", "9aa9e74a3b7eee91": "Add to chat", @@ -9612,7 +9613,9 @@ "fb71127e5746a6bc": "From Sharing & access there, or t3 pair", "1e3fee7084791773": "Also link {target} back to {source}", "ea34a190b0bd804c": "Agents on {target} can then work on {source} too.", - "ad5ed0ce61b966eb": "Forget {label}? Agents here stop working there. Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", + "974f8c65e8b5f492": "Forget {label}? Agents here stop working there, and their session on {label} ends too if it answers.", + "6cf9e3083b15614f": "{label} did not answer", + "34ccbdf619b83be3": "Revoke \"T3 Code · …\" in {label}''s Sharing & access to end the session there too.", "81c9796bf61b306a": "Could not forget the link", "130e51beb6cf5aad": "Link an environment", "122c3e355699e69d": "Agents here can then launch, message and wait on threads there. It appears under Authorized clients in that environment's Sharing & access, where it can be revoked.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index c6e4cb1801464..075e7c62dc826 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} no pudo establecer una conexión WebSocket.", "d9ce6c142a485959": "{host} dejó de responder durante {seconds} s.", "d6bdce8f4e6101a4": "{host} se desconectó.", + "8450a95e5214d199": "{host} envió una actualización de la configuración del servidor que este cliente no pudo leer.", + "56b4ff3993c93eca": "{host} envió una configuración del servidor incompatible.", + "368c4d4f99c66bfb": "Actualiza el cliente y el servidor a versiones compatibles.", "e5fd422e445391fc": "Error al subir. Toca para reintentar.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Proceso de terminal en ejecución", "fc2c9a91f498ad6b": "{count, plural, one {{count} proceso de terminal en ejecución. Abrir terminal} other {{count} procesos de terminal en ejecución. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pila", "6831e9a46cbd8939": "cadena", "9aa9e74a3b7eee91": "Añadir al chat", @@ -9602,7 +9603,9 @@ "fb71127e5746a6bc": "Desde Compartir y acceso allí, o t3 pair", "1e3fee7084791773": "Vincular también {target} de vuelta a {source}", "ea34a190b0bd804c": "Los agentes de {target} podrán trabajar también en {source}.", - "ad5ed0ce61b966eb": "¿Olvidar {label}? Los agentes de aquí dejarán de trabajar allí. Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", + "974f8c65e8b5f492": "¿Olvidar {label}? Los agentes de aquí dejan de trabajar allí, y su sesión en {label} también termina si responde.", + "6cf9e3083b15614f": "{label} no respondió", + "34ccbdf619b83be3": "Revoca \"T3 Code · …\" en Compartir y acceso de {label} para cerrar también la sesión allí.", "81c9796bf61b306a": "No se pudo olvidar el vínculo", "130e51beb6cf5aad": "Vincular un entorno", "122c3e355699e69d": "Así los agentes de aquí podrán iniciar hilos allí, enviarles mensajes y esperarlos. Aparece en Clientes autorizados, en Compartir y acceso de ese entorno, donde se puede revocar.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index a839eff0a3eae..bdf2610262cae 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} n’a pas pu établir de connexion WebSocket.", "d9ce6c142a485959": "{host} ne répond plus depuis {seconds} s.", "d6bdce8f4e6101a4": "{host} est déconnecté.", + "8450a95e5214d199": "{host} a envoyé une mise à jour de la configuration du serveur que ce client n’a pas pu lire.", + "56b4ff3993c93eca": "{host} a envoyé une configuration de serveur incompatible.", + "368c4d4f99c66bfb": "Mettez à jour le client et le serveur vers des versions compatibles.", "e5fd422e445391fc": "Échec de l’envoi. Touchez pour réessayer.", "b2bc6bd92ea24e5c": "{size} Mo", "88f84178edbb7f57": "{size} Ko", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead} : {title}", "feac8e54b30c5a03": "Processus du terminal en cours", "fc2c9a91f498ad6b": "{count, plural, one {{count} processus de terminal en cours. Ouvrir le terminal} other {{count} processus de terminal en cours. Ouvrir le terminal}}", - "643c4b50feadc874": "Worktree : {path} ({branch})", - "fb7c44da0f0825ea": "Worktree : {path}", "56f37ff8ca568059": "pile", "6831e9a46cbd8939": "chaîne", "9aa9e74a3b7eee91": "Ajouter à la discussion", @@ -9604,7 +9605,9 @@ "fb71127e5746a6bc": "Depuis Partage et accès sur cette machine, ou t3 pair", "1e3fee7084791773": "Associer aussi {target} en retour à {source}", "ea34a190b0bd804c": "Les agents de {target} pourront alors aussi travailler sur {source}.", - "ad5ed0ce61b966eb": "Oublier {label} ? Les agents d’ici cessent d’y travailler. Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", + "974f8c65e8b5f492": "Oublier {label} ? Les agents d’ici cessent d’y travailler, et leur session sur {label} prend fin aussi s’il répond.", + "6cf9e3083b15614f": "{label} n’a pas répondu", + "34ccbdf619b83be3": "Révoquez « T3 Code · … » dans Partage et accès sur {label} pour y fermer aussi la session.", "81c9796bf61b306a": "Impossible d’oublier l’association", "130e51beb6cf5aad": "Associer un environnement", "122c3e355699e69d": "Les agents d’ici pourront alors lancer des fils là-bas, leur envoyer des messages et les attendre. L’association apparaît sous Clients autorisés dans Partage et accès de cet environnement, où elle peut être révoquée.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 74a0cded46144..b9c735dc82ada 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} は WebSocket 接続を確立できませんでした。", "d9ce6c142a485959": "{host} は {seconds} 秒間応答していません。", "d6bdce8f4e6101a4": "{host} の接続が切断されました。", + "8450a95e5214d199": "{host} から、このクライアントで読み取れないサーバー設定の更新が送信されました。", + "56b4ff3993c93eca": "{host} から互換性のないサーバー設定が送信されました。", + "368c4d4f99c66bfb": "クライアントとサーバーを互換性のあるバージョンに更新してください。", "e5fd422e445391fc": "アップロードに失敗しました。タップして再試行してください。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2766,8 +2769,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "ターミナルのプロセスが実行中", "fc2c9a91f498ad6b": "{count, plural, other {{count} 個のターミナルプロセスが実行中。ターミナルを開く}}", - "643c4b50feadc874": "ワークツリー: {path} ({branch})", - "fb7c44da0f0825ea": "ワークツリー: {path}", "56f37ff8ca568059": "スタック", "6831e9a46cbd8939": "チェーン", "9aa9e74a3b7eee91": "チャットに追加", @@ -9559,7 +9560,9 @@ "fb71127e5746a6bc": "リンク先の「共有とアクセス」、または t3 pair から", "1e3fee7084791773": "{target} から {source} へも逆方向にリンクする", "ea34a190b0bd804c": "{target} のエージェントも {source} で作業できるようになります。", - "ad5ed0ce61b966eb": "{label} を削除しますか?ここのエージェントはそこで作業できなくなります。そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", + "974f8c65e8b5f492": "{label} を削除しますか?ここのエージェントはそこで作業できなくなり、{label} が応答すればそこでのセッションも終了します。", + "6cf9e3083b15614f": "{label} が応答しませんでした", + "34ccbdf619b83be3": "そこでのセッションも終了するには、{label} の「共有とアクセス」で \"T3 Code · …\" を取り消してください。", "81c9796bf61b306a": "リンクを削除できませんでした", "130e51beb6cf5aad": "環境をリンク", "122c3e355699e69d": "これで、ここのエージェントがそこでスレッドを起動し、メッセージを送り、完了を待てるようになります。リンクはその環境の「共有とアクセス」の「承認済みクライアント」に表示され、そこで取り消せます。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index ed90871441a9d..b02a37c8718be 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host}에서 WebSocket 연결을 설정할 수 없습니다.", "d9ce6c142a485959": "{host}이(가) {seconds}초 동안 응답하지 않습니다.", "d6bdce8f4e6101a4": "{host} 연결이 끊어졌습니다.", + "8450a95e5214d199": "{host}에서 이 클라이언트가 읽을 수 없는 서버 구성 업데이트를 보냈습니다.", + "56b4ff3993c93eca": "{host}에서 호환되지 않는 서버 구성을 보냈습니다.", + "368c4d4f99c66bfb": "클라이언트와 서버를 호환되는 버전으로 업데이트하세요.", "e5fd422e445391fc": "업로드에 실패했습니다. 탭하여 다시 시도하세요.", "b2bc6bd92ea24e5c": "{size}MB", "88f84178edbb7f57": "{size} KB", @@ -2767,8 +2770,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "터미널 프로세스 실행 중", "fc2c9a91f498ad6b": "{count, plural, other {터미널 프로세스 {count}개 실행 중. 터미널 열기}}", - "643c4b50feadc874": "워크트리: {path}({branch})", - "fb7c44da0f0825ea": "워크트리: {path}", "56f37ff8ca568059": "스택", "6831e9a46cbd8939": "체인", "9aa9e74a3b7eee91": "채팅에 추가", @@ -9562,7 +9563,9 @@ "fb71127e5746a6bc": "그곳의 공유 및 액세스 또는 t3 pair에서", "1e3fee7084791773": "{target}에서 {source}(으)로도 반대 방향 연결", "ea34a190b0bd804c": "그러면 {target}의 에이전트도 {source}에서 작업할 수 있습니다.", - "ad5ed0ce61b966eb": "{label}을(를) 삭제할까요? 이곳의 에이전트가 그곳에서 더 이상 작업하지 않습니다. 그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", + "974f8c65e8b5f492": "{label}을(를) 잊을까요? 여기의 에이전트는 그곳에서 더 이상 작업하지 않으며, {label}이(가) 응답하면 그곳의 세션도 종료됩니다.", + "6cf9e3083b15614f": "{label}이(가) 응답하지 않았습니다", + "34ccbdf619b83be3": "그곳의 세션도 끝내려면 {label}의 공유 및 액세스에서 \"T3 Code · …\"를 취소하세요.", "81c9796bf61b306a": "링크를 삭제할 수 없습니다", "130e51beb6cf5aad": "환경 연결", "122c3e355699e69d": "그러면 이곳의 에이전트가 그곳에서 스레드를 시작하고, 메시지를 보내고, 기다릴 수 있습니다. 해당 환경의 공유 및 액세스에서 승인된 클라이언트에 표시되며 그곳에서 취소할 수 있습니다.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6e342433dd275..3e5b049433362 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} não conseguiu estabelecer uma conexão WebSocket.", "d9ce6c142a485959": "{host} parou de responder por {seconds} s.", "d6bdce8f4e6101a4": "{host} desconectou.", + "8450a95e5214d199": "{host} enviou uma atualização da configuração do servidor que este cliente não conseguiu ler.", + "56b4ff3993c93eca": "{host} enviou uma configuração de servidor incompatível.", + "368c4d4f99c66bfb": "Atualize o cliente e o servidor para versões compatíveis.", "e5fd422e445391fc": "Falha no envio. Toque para tentar novamente.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Processo do terminal em execução", "fc2c9a91f498ad6b": "{count, plural, one {{count} processo do terminal em execução. Abrir terminal} other {{count} processos do terminal em execução. Abrir terminal}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "pilha", "6831e9a46cbd8939": "cadeia", "9aa9e74a3b7eee91": "Adicionar ao chat", @@ -9603,7 +9604,9 @@ "fb71127e5746a6bc": "Em Compartilhamento e acesso de lá, ou t3 pair", "1e3fee7084791773": "Vincular também {target} de volta a {source}", "ea34a190b0bd804c": "Os agentes de {target} poderão trabalhar também em {source}.", - "ad5ed0ce61b966eb": "Esquecer {label}? Os agentes daqui deixam de funcionar lá. Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", + "974f8c65e8b5f492": "Esquecer {label}? Os agentes daqui param de trabalhar lá, e a sessão deles em {label} também termina se ele responder.", + "6cf9e3083b15614f": "{label} não respondeu", + "34ccbdf619b83be3": "Revogue \"T3 Code · …\" em Compartilhamento e acesso de {label} para encerrar a sessão lá também.", "81c9796bf61b306a": "Não foi possível esquecer o vínculo", "130e51beb6cf5aad": "Vincular um ambiente", "122c3e355699e69d": "Os agentes daqui poderão então iniciar threads lá, enviar mensagens e aguardá-las. Ele aparece em Clientes autorizados em Compartilhamento e acesso daquele ambiente, onde pode ser revogado.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index c959f426c8836..81846ba91a390 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} не удалось установить WebSocket-соединение.", "d9ce6c142a485959": "{host} не отвечает уже {seconds} с.", "d6bdce8f4e6101a4": "{host} отключён.", + "8450a95e5214d199": "{host} отправил обновление конфигурации сервера, которое этот клиент не смог прочитать.", + "56b4ff3993c93eca": "{host} отправил несовместимую конфигурацию сервера.", + "368c4d4f99c66bfb": "Обновите клиент и сервер до совместимых версий.", "e5fd422e445391fc": "Ошибка загрузки. Нажмите, чтобы повторить.", "b2bc6bd92ea24e5c": "{size} МБ", "88f84178edbb7f57": "{size} КБ", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Процесс в терминале запущен", "fc2c9a91f498ad6b": "{count, plural, one {Запущен {count} процесс в терминале. Открыть терминал} few {Запущено {count} процесса в терминале. Открыть терминал} many {Запущено {count} процессов в терминале. Открыть терминал} other {Запущено {count} процесса в терминале. Открыть терминал}}", - "643c4b50feadc874": "Рабочее дерево: {path} ({branch})", - "fb7c44da0f0825ea": "Рабочее дерево: {path}", "56f37ff8ca568059": "стек", "6831e9a46cbd8939": "цепочка", "9aa9e74a3b7eee91": "Добавить в чат", @@ -9604,7 +9605,9 @@ "fb71127e5746a6bc": "Из раздела «Общий доступ» там или через t3 pair", "1e3fee7084791773": "Также привязать {target} в ответ к {source}", "ea34a190b0bd804c": "Тогда агенты на {target} смогут работать и на {source}.", - "ad5ed0ce61b966eb": "Забыть {label}? Агенты отсюда перестанут там работать. Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", + "974f8c65e8b5f492": "Забыть {label}? Агенты отсюда перестанут там работать, а их сеанс на {label} тоже завершится, если он ответит.", + "6cf9e3083b15614f": "{label} не ответил", + "34ccbdf619b83be3": "Чтобы завершить сеанс и там, отзовите «T3 Code · …» в разделе «Общий доступ» на {label}.", "81c9796bf61b306a": "Не удалось забыть привязку", "130e51beb6cf5aad": "Привязать окружение", "122c3e355699e69d": "После этого агенты отсюда смогут запускать треды там, писать в них и ждать их. Связь появится в разделе «Авторизованные клиенты» в «Общем доступе» того окружения, где её можно отозвать.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index 49f22d7bc33a3..8fffba53b90db 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} kunde inte upprätta en WebSocket-anslutning.", "d9ce6c142a485959": "{host} slutade svara i {seconds} s.", "d6bdce8f4e6101a4": "{host} kopplades från.", + "8450a95e5214d199": "{host} skickade en uppdatering av serverkonfigurationen som den här klienten inte kunde läsa.", + "56b4ff3993c93eca": "{host} skickade en inkompatibel serverkonfiguration.", + "368c4d4f99c66bfb": "Uppdatera klienten och servern till kompatibla versioner.", "e5fd422e445391fc": "Uppladdningen misslyckades. Tryck för att försöka igen.", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} kB", @@ -2768,8 +2771,6 @@ "3260b22f72f7effb": "{tooltipLead}: {title}", "feac8e54b30c5a03": "Terminalprocess körs", "fc2c9a91f498ad6b": "{count, plural, one {{count} terminalprocess körs. Öppna terminalen} other {{count} terminalprocesser körs. Öppna terminalen}}", - "643c4b50feadc874": "Worktree: {path} ({branch})", - "fb7c44da0f0825ea": "Worktree: {path}", "56f37ff8ca568059": "stack", "6831e9a46cbd8939": "kedja", "9aa9e74a3b7eee91": "Lägg till i chatten", @@ -9610,7 +9611,9 @@ "fb71127e5746a6bc": "Från Delning och åtkomst där, eller t3 pair", "1e3fee7084791773": "Länka även {target} tillbaka till {source}", "ea34a190b0bd804c": "Agenter på {target} kan då också arbeta på {source}.", - "ad5ed0ce61b966eb": "Glöm {label}? Agenter här slutar arbeta där. Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", + "974f8c65e8b5f492": "Glöm {label}? Agenter här slutar arbeta där, och deras session på {label} avslutas också om den svarar.", + "6cf9e3083b15614f": "{label} svarade inte", + "34ccbdf619b83be3": "Återkalla ”T3 Code · …” under Delning och åtkomst på {label} för att avsluta sessionen där också.", "81c9796bf61b306a": "Kunde inte glömma länken", "130e51beb6cf5aad": "Länka en miljö", "122c3e355699e69d": "Agenter här kan sedan starta, skicka meddelanden till och vänta på trådar där. Den visas under Auktoriserade klienter i miljöns Delning och åtkomst, där den kan återkallas.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 6edb1253288ce..768f976cac946 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -761,6 +761,9 @@ "fc2020db8a3804c0": "{host} 无法建立 WebSocket 连接。", "d9ce6c142a485959": "{host} 已 {seconds} 秒无响应。", "d6bdce8f4e6101a4": "{host} 已断开连接。", + "8450a95e5214d199": "{host} 发送了此客户端无法读取的服务器配置更新。", + "56b4ff3993c93eca": "{host} 发送了不兼容的服务器配置。", + "368c4d4f99c66bfb": "请将客户端和服务器更新到兼容的版本。", "e5fd422e445391fc": "上传失败。点按以重试。", "b2bc6bd92ea24e5c": "{size} MB", "88f84178edbb7f57": "{size} KB", @@ -2772,8 +2775,6 @@ "3260b22f72f7effb": "{tooltipLead}:{title}", "feac8e54b30c5a03": "终端进程正在运行", "fc2c9a91f498ad6b": "{count, plural, other {{count} 个终端进程正在运行。打开终端}}", - "643c4b50feadc874": "工作树:{path}({branch})", - "fb7c44da0f0825ea": "工作树:{path}", "56f37ff8ca568059": "堆叠", "6831e9a46cbd8939": "链", "9aa9e74a3b7eee91": "添加到对话", @@ -9620,7 +9621,9 @@ "fb71127e5746a6bc": "从远端“共享与访问”页面或 t3 pair 获取", "1e3fee7084791773": "同时将 {target} 反向关联到 {source}", "ea34a190b0bd804c": "之后 {target} 上的智能体也能在 {source} 上工作。", - "ad5ed0ce61b966eb": "忘记 {label}?此处的智能体将停止在那里工作。在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", + "974f8c65e8b5f492": "忘记 {label}?此处的代理将不再在那里工作;如果 {label} 有响应,它们在那里的会话也会结束。", + "6cf9e3083b15614f": "{label} 没有响应", + "34ccbdf619b83be3": "在 {label} 的“共享与访问”中撤销“T3 Code · …”,以同时结束那里的连接。", "81c9796bf61b306a": "无法移除关联", "130e51beb6cf5aad": "关联环境", "122c3e355699e69d": "这里的智能体随后就能在该环境中启动会话、发送消息并等待结果。此连接将显示在该环境“共享与访问”的“已授权客户端”中,可在那里撤销。", diff --git a/apps/web/src/lib/chunkReloadGuard.ts b/apps/web/src/lib/chunkReloadGuard.ts index 10f4dc8be191c..43034ccb578b3 100644 --- a/apps/web/src/lib/chunkReloadGuard.ts +++ b/apps/web/src/lib/chunkReloadGuard.ts @@ -34,3 +34,15 @@ export function isChunkLoadError(error: unknown): boolean { message !== undefined && CHUNK_LOAD_ERROR_PREFIXES.some((prefix) => message.startsWith(prefix)) ); } + +export const chunkLoadState = { reloadScheduled: false }; + +// Registered from the entry before main loads, so main-chunk and route-chunk failures share one decision. +export function handleChunkLoadErrors() { + window.addEventListener("vite:preloadError", (event) => { + if (reloadOnceForChunkLoadError()) { + chunkLoadState.reloadScheduled = true; + event.preventDefault(); + } + }); +} diff --git a/apps/web/src/lib/composerContextRecords.ts b/apps/web/src/lib/composerContextRecords.ts index dc4d6e2351c5d..c74ee9e421708 100644 --- a/apps/web/src/lib/composerContextRecords.ts +++ b/apps/web/src/lib/composerContextRecords.ts @@ -10,6 +10,8 @@ import { COMPOSER_CONTEXT_TERMINAL_TEXT_MAX_CHARS, } from "@t3tools/contracts"; import type { + ChatFileAttachment, + ChatImageAttachment, ComposerContextId, ComposerContextRecord, EnvironmentContextRecord, @@ -489,39 +491,59 @@ export function fileContextReference(file: ComposerFileAttachment): ComposerCont }; } +export type ComposerContextAttachment = + | ComposerImageAttachment + | ComposerFileAttachment + | (Omit & { + readonly file: File | null; + readonly uploadedAttachmentId?: string | undefined; + }) + | ChatImageAttachment + | ChatFileAttachment; + export interface BoundComposerAttachment { - attachment: ComposerImageAttachment | ComposerFileAttachment; + attachment: ComposerContextAttachment; attachmentId: string; + contextId?: ComposerContextId | undefined; } /** Returns null until the attachment has a server id. */ export function uploadedAttachmentContextRecord( - attachment: ComposerImageAttachment | ComposerFileAttachment, + attachment: ComposerContextAttachment, upload: AttachmentUploadState | undefined, + contextId?: ComposerContextId, ): ImageContextRecord | FileContextRecord | null { const attachmentId = - attachment.type === "file" && attachment.uploadedAttachmentId !== undefined + "uploadedAttachmentId" in attachment && attachment.uploadedAttachmentId !== undefined ? attachment.uploadedAttachmentId : upload?.status === "ready" ? upload.attachmentId : undefined; - return attachmentId === undefined ? null : attachmentContextRecord({ attachment, attachmentId }); + return attachmentId === undefined + ? null + : attachmentContextRecord({ attachment, attachmentId, contextId }); } export function attachmentContextRecord( bound: BoundComposerAttachment, ): ImageContextRecord | FileContextRecord { - const { attachment, attachmentId } = bound; + const { attachment, attachmentId, contextId } = bound; const base = { version: 1 as const, - contextId: toKindScopedComposerContextId(attachment.type, attachment.id), + contextId: contextId ?? toKindScopedComposerContextId(attachment.type, attachment.id), label: sanitizeComposerContextLabel(attachment.name, attachment.type), attachmentId, name: attachment.name, mimeType: attachment.mimeType, sizeBytes: attachment.sizeBytes, }; - return attachment.type === "image" ? { ...base, kind: "image" } : { ...base, kind: "file" }; + return attachment.type === "image" + ? { + ...base, + kind: "image", + ...(attachment.source !== undefined ? { source: attachment.source } : {}), + } + : { ...base, kind: "file" }; } export function buildMessageContext(input: { diff --git a/apps/web/src/lib/discardComposerDraft.test.ts b/apps/web/src/lib/discardComposerDraft.test.ts index 6c63482dfe52b..340ed6b2606e3 100644 --- a/apps/web/src/lib/discardComposerDraft.test.ts +++ b/apps/web/src/lib/discardComposerDraft.test.ts @@ -80,6 +80,23 @@ describe("discardComposerDraft", () => { } }); + it("discards and restores a draft session that has no composer record", async () => { + useComposerDraftStore.getState().setProjectDraftThreadId(projectRef, draftId); + const before = useComposerDraftStore.getState(); + expect(before.draftsByThreadKey).toEqual({}); + + discardComposerDraft(draftId); + expect(useComposerDraftStore.getState().getDraftSession(draftId)).toBeNull(); + + await undoNotice().undo(); + const after = useComposerDraftStore.getState(); + expect(after.getDraftSession(draftId)).toEqual(before.getDraftSession(draftId)); + expect(after.draftsByThreadKey).toEqual({}); + expect(after.logicalProjectDraftThreadKeyByLogicalProjectKey).toEqual( + before.logicalProjectDraftThreadKeyByLogicalProjectKey, + ); + }); + it("releases a discarded existing-thread preview when Undo is committed", async () => { using preview = imagePreview(); useComposerDraftStore.getState().addImage(threadRef, preview.image); diff --git a/apps/web/src/lib/discardComposerDraft.ts b/apps/web/src/lib/discardComposerDraft.ts index bd52b0a02879f..f1847a737dc0a 100644 --- a/apps/web/src/lib/discardComposerDraft.ts +++ b/apps/web/src/lib/discardComposerDraft.ts @@ -19,8 +19,9 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { const store = useComposerDraftStore.getState(); const key = resolveComposerDraftKey(store, target); const draft = key === null ? undefined : store.draftsByThreadKey[key]; - if (key === null || !draft) return; + if (key === null) return; const session = store.draftThreadsByThreadKey[key]; + if (!draft && !session) return; const logicalProjectKeys = Object.entries(store.logicalProjectDraftThreadKeyByLogicalProjectKey) .filter(([, draftKey]) => draftKey === key) .map(([logicalProjectKey]) => logicalProjectKey); @@ -38,6 +39,7 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { } const releaseDiscardedDraft = () => { + if (!draft) return; releaseDraftAttachments([...draft.images, ...draft.files]); // Draft-session removal already revoked these previews. if (!discardsSession) { @@ -65,19 +67,21 @@ export function discardComposerDraft(target: ComposerThreadTarget): void { logicalProjectDraftThreadKeyByLogicalProjectKey[logicalProjectKey] ??= key; } return { - draftsByThreadKey: { - ...state.draftsByThreadKey, - [key]: discardsSession - ? { - ...draft, - images: draft.images.map((image) => - image.previewUrl.startsWith("blob:") - ? { ...image, previewUrl: URL.createObjectURL(image.file) } - : image, - ), - } - : draft, - }, + draftsByThreadKey: draft + ? { + ...state.draftsByThreadKey, + [key]: discardsSession + ? { + ...draft, + images: draft.images.map((image) => + image.previewUrl.startsWith("blob:") + ? { ...image, previewUrl: URL.createObjectURL(image.file) } + : image, + ), + } + : draft, + } + : state.draftsByThreadKey, draftThreadsByThreadKey: session ? { ...state.draftThreadsByThreadKey, [key]: session } : state.draftThreadsByThreadKey, diff --git a/apps/web/src/lib/pageTranslationGuard.browser.test.tsx b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx new file mode 100644 index 0000000000000..40d7e7597ccf8 --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.browser.test.tsx @@ -0,0 +1,42 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { render } from "../../test/render"; +import { guardDomAgainstPageTranslation } from "./pageTranslationGuard"; + +// What Chrome's page translator does: swap each text node for translation. +function translatePage(root: Element) { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + const textNodes: Text[] = []; + while (walker.nextNode()) textNodes.push(walker.currentNode as Text); + for (const text of textNodes) { + if (!text.nodeValue?.trim()) continue; + const outer = document.createElement("font"); + const inner = document.createElement("font"); + inner.textContent = `译:${text.nodeValue}`; + outer.append(inner); + text.replaceWith(outer); + } +} + +function Status({ running }: { running: boolean }) { + return ( +

+ {running ? "Working" : } + {"for 2s"} +
+ ); +} + +describe("guardDomAgainstPageTranslation", () => { + it("keeps React committing after page translation replaced its text nodes", async () => { + guardDomAgainstPageTranslation(); + await using screen = await render(, { router: false }); + translatePage(screen.container); + + // Removing "Working" hits removeChild; placing the icon before "for 2s" hits insertBefore. + await screen.rerender(); + await expect.element(screen.getByTestId("done")).toBeInTheDocument(); + await screen.rerender(); + await expect.element(screen.getByTestId("done")).not.toBeInTheDocument(); + }); +}); diff --git a/apps/web/src/lib/pageTranslationGuard.ts b/apps/web/src/lib/pageTranslationGuard.ts new file mode 100644 index 0000000000000..de8dbceb8e2bf --- /dev/null +++ b/apps/web/src/lib/pageTranslationGuard.ts @@ -0,0 +1,20 @@ +// Browser page translation (Chrome, Edge) swaps text nodes for wrappers React does not +// know about, so a later removeChild or insertBefore on the original node throws NotFoundError +// and takes down the whole tree. See facebook/react#11538. +export function guardDomAgainstPageTranslation(): void { + const proto = Node.prototype; + const removeChild = proto.removeChild; + const insertBefore = proto.insertBefore; + + proto.removeChild = function (this: Node, child: T): T { + // Already detached by the translator: nothing left to remove. + if (child.parentNode !== this) return child; + return removeChild.call(this, child) as T; + }; + + proto.insertBefore = function (this: Node, node: T, reference: Node | null): T { + // The anchor was replaced; append so the new node still shows. + const anchor = reference && reference.parentNode !== this ? null : reference; + return insertBefore.call(this, node, anchor) as T; + }; +} diff --git a/apps/web/src/main.test.ts b/apps/web/src/main.test.ts index 56be08671e331..11b9b68c867d1 100644 --- a/apps/web/src/main.test.ts +++ b/apps/web/src/main.test.ts @@ -5,7 +5,7 @@ vi.mock("./AppRoot", () => ({ AppRoot: () => null })); vi.mock("./i18n/runtime", () => ({ whenLocaleReady: async () => {} })); vi.mock("react-dom/client", () => ({ default: { createRoot: () => ({ render: () => {} }) } })); -// Boots main in a fresh page that shares the tab's sessionStorage, as a reload does. +// Boots the entry in a fresh page that shares the tab's sessionStorage, as a reload does. async function bootThenFailLazyChunk(sessionStorage: Map) { vi.resetModules(); const reload = vi.fn().mockName("location.reload"); @@ -20,8 +20,8 @@ async function bootThenFailLazyChunk(sessionStorage: Map) { vi.stubGlobal("window", page); vi.stubGlobal("document", { getElementById: () => ({}) }); try { - const { startup } = await import("./main"); - await startup; + const { boot } = await import("./bootstrap"); + await boot; page.dispatchEvent(new Event("vite:preloadError", { cancelable: true })); return reload; } finally { diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 112de4848170c..51aeeade6863d 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -9,20 +9,12 @@ import { isElectron } from "./env"; import { startAppServices } from "./appInit"; import { AppRoot } from "./AppRoot"; import { whenLocaleReady } from "./i18n/runtime"; -import { reloadOnceForChunkLoadError } from "./lib/chunkReloadGuard"; +import { chunkLoadState } from "./lib/chunkReloadGuard"; const router = startAppServices(); const clerkPublishableKey = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY as string | undefined; -let reloadScheduled = false; -window.addEventListener("vite:preloadError", (event) => { - if (reloadOnceForChunkLoadError()) { - reloadScheduled = true; - event.preventDefault(); - } -}); - const app = ; // Split by runtime to keep Clerk out of local startup and clerk-js out of browser builds. @@ -40,7 +32,7 @@ export const startup = Promise.all([ ]) .then(([ManagedAuthShell]) => { // Route chunk failures resolve router.load() and surface later through the error boundary. - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render( {ManagedAuthShell && clerkPublishableKey ? ( @@ -52,6 +44,6 @@ export const startup = Promise.all([ ); }) .catch((error: unknown) => { - if (reloadScheduled) return; + if (chunkLoadState.reloadScheduled) return; throw error; }); diff --git a/apps/web/src/session-logic.test.ts b/apps/web/src/session-logic.test.ts index 9e62e9d7a2bc8..36ef0f09ec970 100644 --- a/apps/web/src/session-logic.test.ts +++ b/apps/web/src/session-logic.test.ts @@ -290,7 +290,10 @@ describe("V2 session presentation", () => { }, }; }); - const checkpoint = (ordinal: number, status: "ready" | "missing" | "stale" = "ready") => ({ + const checkpoint = ( + ordinal: number, + status: "ready" | "missing" | "stale" | "error" = "ready", + ) => ({ runId: runId(ordinal), checkpointTurnCount: ordinal, checkpointRef: `checkpoint-${ordinal}` as never, @@ -326,6 +329,11 @@ describe("V2 session presentation", () => { "user-1": 0, "user-2": 1, }); + // A failed snapshot capture still pins the conversation; only file restore needs one. + expect(targets([1, 2], [checkpoint(1, "error")])).toEqual({ + "user-1": 0, + "user-2": 1, + }); }); it("preserves a notification-only wake run while ignoring inherited and unrelated work", () => { diff --git a/apps/web/src/session-logic.ts b/apps/web/src/session-logic.ts index 360131de27c40..3e229b621a4e4 100644 --- a/apps/web/src/session-logic.ts +++ b/apps/web/src/session-logic.ts @@ -1222,10 +1222,10 @@ export function deriveRevertTurnCountByUserMessageId(input: { return byUserMessageId; } -// A missing snapshot (no git, or a side chat) still pins a conversation position; only -// restoring files needs a ready one. +// A missing or failed snapshot (no git, a side chat, a capture error) still pins a +// conversation position; only restoring files needs a ready one. function isRewindableCheckpoint(checkpoint: Pick) { - return checkpoint.status === "ready" || checkpoint.status === "missing"; + return checkpoint.status !== "stale"; } export function findRevertCheckpoint( diff --git a/apps/web/src/state/linkedThreadView.ts b/apps/web/src/state/linkedThreadView.ts index adeb858c23cab..4194e07834811 100644 --- a/apps/web/src/state/linkedThreadView.ts +++ b/apps/web/src/state/linkedThreadView.ts @@ -11,7 +11,7 @@ import { useNavigate, useRouter } from "@tanstack/react-router"; import { AsyncResult, Atom } from "effect/reactivity"; import type { TurnItemSource } from "../components/chat/timelineRowContext"; -import { useRightPanelStore } from "../rightPanelStore"; +import { selectThreadRightPanelState, useRightPanelStore } from "../rightPanelStore"; import { connectPairing, reachesEnvironment } from "../connection/onboarding"; import { openLinkedThreadRead } from "../lib/sideChatPane"; import type { LinkedThreadSurface } from "../linkedThreadSurface"; @@ -107,14 +107,17 @@ const tabViewAtom = Atom.family((key: string) => { const view = peerLinkEnvironment.threadView( targetOf({ viaEnvironmentId, environmentId, threadId }), ); - return Atom.make((get) => { - const live = get(view); - const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; - if (title && panelRef !== null) { - useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(view); + const title = AsyncResult.getOrElse(live, () => null)?.thread.projection?.thread.title; + if (title && panelRef !== null) { + useRightPanelStore.getState().setLinkedThreadTitle(panelRef, surfaceId, title); + } + return live; + }, + (refresh) => refresh(view), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`linked-thread-tab-view:${key}`)); }); /** @@ -203,8 +206,17 @@ export function useConnectLinkedEnvironment( const connect = async () => { setState({ phase: "connecting" }); const startedOn = router.state.location.href; + let tabClosed = false; + // A tab can close and reopen with the same ID while pairing is in flight. + const stopWatchingTab = + panelRef === null + ? undefined + : useRightPanelStore.subscribe((state) => { + const { surfaces } = selectThreadRightPanelState(state.byThreadKey, panelRef); + if (!surfaces.some((tab) => tab.id === surface.id)) tabClosed = true; + }); // Pairing takes a moment; a user who has gone elsewhere since is not moved again. - const stayed = () => router.state.location.href === startedOn; + const stayed = () => !tabClosed && router.state.location.href === startedOn; const outcome = await connectLinkedEnvironment({ label: surface.label, requestPairing: async () => { @@ -228,13 +240,14 @@ export function useConnectLinkedEnvironment( }); return result._tag === "Success"; }, - }); + }).finally(stopWatchingTab); if (outcome.type === "unreachable") { setState({ phase: "unreachable", label: outcome.label }); return outcome; } if (outcome.type === "connected") { setState({ phase: "idle" }); + if (tabClosed) return outcome; // The thread opens where every thread on a connected environment does, so its tab is done. if (panelRef !== null) useRightPanelStore.getState().closeSurface(panelRef, surface.id); if (!stayed()) return outcome; diff --git a/apps/web/src/state/terminalSessions.ts b/apps/web/src/state/terminalSessions.ts index 8eaca1b774c85..0915810b47fed 100644 --- a/apps/web/src/state/terminalSessions.ts +++ b/apps/web/src/state/terminalSessions.ts @@ -22,7 +22,13 @@ import { AsyncResult, Atom } from "effect/reactivity"; import { formatEnvironmentQueryError } from "./query"; import { terminalEnvironment } from "./terminal"; -import { environmentSession, sessionHasScope, useEnvironmentScope } from "./session"; +import { environmentAtomList, environmentIdsKey } from "./environmentAtomList"; +import { + environmentSession, + sessionHasScope, + useEnvironmentScope, + useEnvironmentsWithScope, +} from "./session"; import { msg } from "gt-react"; import { m } from "../i18n/messages"; @@ -274,3 +280,43 @@ export function useThreadRunningTerminalIds(input: { const sessions = useKnownTerminalSessions(input); return selectRunningSubprocessTerminalIds(sessions ?? []); } + +// A string so status updates that keep every label notify no one. +const terminalLabelsFamily = Atom.family((environmentId: EnvironmentId) => + Atom.make((get) => { + const metadata = get(terminalEnvironment.metadata({ environmentId, input: null })); + if (metadata._tag !== "Success") return "[]"; + return JSON.stringify( + Array.from(terminalMetadataIndex(metadata.value).byThreadId, ([threadId, summaries]) => [ + threadId, + summaries[0]!.label, + ]), + ); + }).pipe(Atom.withLabel(`web-terminal-labels:${environmentId}`)), +); +const terminalLabelsListAtom = environmentAtomList("web-terminal-labels", terminalLabelsFamily); +const terminalLabelsByResults = new WeakMap, ReadonlyMap>(); + +/** First terminal label of each thread that has one, keyed `${environmentId}:${threadId}`. */ +export function useTerminalLabelsByThreadKey( + environmentIds: ReadonlyArray, +): ReadonlyMap { + const readable = useEnvironmentsWithScope( + environmentIds.map((environmentId) => ({ environmentId })), + AuthTerminalReadScope, + ); + const readableIds = environmentIds.filter((environmentId) => readable.has(environmentId)); + const results = useAtomValue(terminalLabelsListAtom(environmentIdsKey(readableIds))); + let labels = terminalLabelsByResults.get(results); + if (!labels) { + const next = new Map(); + results.forEach((encoded, index) => { + for (const [threadId, label] of JSON.parse(encoded) as Array<[string, string]>) { + next.set(`${readableIds[index]}:${threadId}`, label); + } + }); + labels = next; + terminalLabelsByResults.set(results, labels); + } + return labels; +} diff --git a/apps/web/src/workspaceBasenameLookup.test.ts b/apps/web/src/workspaceBasenameLookup.test.ts index 4e11917a0aeff..7c1d17587813e 100644 --- a/apps/web/src/workspaceBasenameLookup.test.ts +++ b/apps/web/src/workspaceBasenameLookup.test.ts @@ -129,6 +129,21 @@ describe("chat file links into another project", () => { ).toBeNull(); }); + it("opens nothing when a project left ambiguous by case also has the name", () => { + expect( + pickProjectLinkMatch("handoff.txt", [ + { root: "/reports", entries: [{ path: "notes/HANDOFF.txt", kind: "file" }] }, + { + root: "/support", + entries: [ + { path: "current/Handoff.txt", kind: "file" }, + { path: "archive/HANDOFF.txt", kind: "file" }, + ], + }, + ]), + ).toBeNull(); + }); + it("opens nothing when overlapping projects also list a second suffix match", () => { expect( pickProjectLinkMatch("docs/handoff.txt", [ diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 354e10df8d7ab..7acd081da7fa3 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -111,6 +111,9 @@ const browserTestProject = { include: [ "vite-plus/test/browser", "@base-ui/react/autocomplete", + "@effect/vitest", + "@pierre/diffs/ssr", + "effect/testing", "saxes", "@betteroffice/docx/editor", "@betteroffice/docx/layout", diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index baa9cc60230a1..efab9a105f0cb 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -110,8 +110,8 @@ When you return to a large thread after Claude's prompt cache expires, a **Compact** chip with the thread's token count shows next to the send button. While it is on, Enter summarizes the history first, then sends your message. Click the chip to switch it to **Keep** and keep the full -history for that message. The mobile app shows no chip: an eligible message sent -from it summarizes first. The cache lasts about an hour on a Claude +history for that message. The mobile app shows the same chip, labelled with the +token count: tap it to keep the full history for that message. The cache lasts about an hour on a Claude subscription and 5 minutes with an API key, Bedrock, or Vertex. See [commands and skills](./composer.md#commands-and-skills) for using composer commands. diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md index 1b3c21c6c037e..aa994009bb95c 100644 --- a/docs/user/remote-access.md +++ b/docs/user/remote-access.md @@ -537,8 +537,11 @@ an address you trust: the code is sent there. machine's own threads, projects or settings, and they skip its project setup scripts. - The link shows up in that machine's **Settings → Sharing & access** like any - outside agent. Revoke it there to end it. **Forget** on this machine only - removes it here. On mobile, open **Settings → Environments**, select the source machine, + outside agent, and can be revoked there. **Forget** on this machine also ends + it there when that machine confirms it. If it can't, such as when it is + offline or on an older T3 Code, Forget says so; revoke it in that machine's + Sharing & access. + On mobile, open **Settings → Environments**, select the source machine, and choose **Forget link** under its linked environments. - A link stays valid while agents use it. One unused for 30 days expires, as does one to a machine on an older T3 Code after 30 days; link again with a diff --git a/docs/user/source-control.md b/docs/user/source-control.md index 65f21f202e60c..1789407b22bf9 100644 --- a/docs/user/source-control.md +++ b/docs/user/source-control.md @@ -160,7 +160,9 @@ Alternatively, open **Settings → Source control & issues**, expand **TanStack from `https://source.tanstack.com/settings/tokens`. A saved token is used before `SRC_TOKEN`, which is used before the `src` login. With several `src` logins, pick the account there too. -Pull requests show the runs of TanStack Source CI with their logs, and update live while open. Issues +Pull requests show the runs of TanStack Source CI with their logs, and update live while open. An +agent can open a private pull request on a public repository when you ask for one: its branch goes +to the repository's private companion and never to the repository itself. Issues can be listed, filed, edited, commented on and closed. Reactions and picking reviewers or assignees from a list are not available yet. diff --git a/packages/client-runtime/src/linkedThread.test.ts b/packages/client-runtime/src/linkedThread.test.ts index 2004f514df4a4..dc98322c225da 100644 --- a/packages/client-runtime/src/linkedThread.test.ts +++ b/packages/client-runtime/src/linkedThread.test.ts @@ -1,3 +1,5 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off - The probe fixture uses a Node macrotask boundary. +import * as NodeTimersPromises from "node:timers/promises"; import { EnvironmentId, EventId, @@ -254,16 +256,22 @@ describe("connectLinkedEnvironment", () => { credential: "ONE-TIME", expiresAt: DateTime.makeUnsafe(0), }; + const unsupported: PeerLinkClientPairingResult = { + type: "unsupported", + reason: "link_access", + ...target, + }; const connect = ( pairing: PeerLinkClientPairingResult | null, - reachable: ReadonlyArray, + reachable: ReadonlyArray | ((host: string) => Promise), paired = true, ) => { const pairs: Array<{ host: string; pairingCode: string }> = []; return connectLinkedEnvironment({ label: "vm (saved name)", requestPairing: async () => pairing, - reaches: async (host) => reachable.includes(host), + reaches: + typeof reachable === "function" ? reachable : async (host) => reachable.includes(host), pair: async (input) => { pairs.push(input); return paired; @@ -279,6 +287,42 @@ describe("connectLinkedEnvironment", () => { expect((await connect(credential, [tailnet, lan])).pairs[0]?.host).toBe(lan); }); + it.each([ + { + name: "redeems at an alternate after the preferred probe fails", + pairing: credential, + preferredReachable: false, + expected: { + outcome: { type: "connected" }, + pairs: [{ host: tailnet, pairingCode: "ONE-TIME" }], + }, + }, + { + name: "prefills the preferred address even when an alternate answers first", + pairing: unsupported, + preferredReachable: true, + expected: { outcome: { type: "manual", label: "VM", host: lan }, pairs: [] }, + }, + ])("$name without waiting for a silent last address", async (row) => { + const last = "https://other.example.test"; + const preferred = Promise.withResolvers(); + const silent = Promise.withResolvers(); + const connecting = connect({ ...row.pairing, urls: [lan, tailnet, last] }, (host) => { + if (host === lan) return preferred.promise; + if (host === last) return silent.promise; + queueMicrotask(() => preferred.resolve(row.preferredReachable)); + return Promise.resolve(true); + }); + try { + // oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- Let the already runnable probe continuations finish while the last probe stays pending. + const pending = NodeTimersPromises.setImmediate("still waiting for an address"); + expect(await Promise.race([connecting, pending])).toEqual(row.expected); + } finally { + silent.resolve(false); + preferred.resolve(false); + } + }); + it("says the machine is out of reach, and spends nothing, when no address answers", async () => { expect(await connect(credential, [])).toEqual({ outcome: { type: "unreachable", label: "VM" }, @@ -287,11 +331,6 @@ describe("connectLinkedEnvironment", () => { }); it("leaves pairing to the user when the link cannot do it, with an address filled in", async () => { - const unsupported: PeerLinkClientPairingResult = { - type: "unsupported", - reason: "link_access", - ...target, - }; const manual = (host: string | null) => ({ outcome: { type: "manual", label: "VM", host }, pairs: [], diff --git a/packages/client-runtime/src/linkedThread.ts b/packages/client-runtime/src/linkedThread.ts index 69b179e08f671..9e2b4487f59b4 100644 --- a/packages/client-runtime/src/linkedThread.ts +++ b/packages/client-runtime/src/linkedThread.ts @@ -89,8 +89,17 @@ export async function connectLinkedEnvironment(options: { if (pairing === null) return { type: "manual", label: options.label, host: null }; const { label, urls } = pairing; // Asked together, taken in the linking environment's order of preference. - const answers = await Promise.all(urls.map((url) => options.reaches(url))); - const host = urls.find((_, index) => answers[index]) ?? null; + const probes = urls.map((url) => + options.reaches(url).then( + (reached) => (reached ? url : null), + () => null, + ), + ); + let host: string | null = null; + for (const probe of probes) { + host = await probe; + if (host !== null) break; + } if (pairing.type === "unsupported") { return { type: "manual", label, host: host ?? urls[0] ?? null }; } diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index ad7d30325e628..8c5206af16fd2 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -635,6 +639,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index c0a0c280a1fad..1cc46756712ee 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -321,28 +321,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -371,6 +355,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -790,6 +798,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -821,7 +830,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -840,10 +849,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -875,7 +884,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.groupAudience === undefined ? {} : { groupAudience: input.groupAudience }), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -907,7 +916,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1073,9 +1082,9 @@ export const revertThreadCheckpoint = Effect.fn("EnvironmentCommands.revertThrea ); if ( checkpoint === undefined || - // Missing snapshots support conversation rewind only. + // Missing or failed snapshots support conversation rewind only. (checkpoint.status !== "ready" && - !(input.restoreFiles === false && checkpoint.status === "missing")) + !(input.restoreFiles === false && checkpoint.status !== "stale")) ) { const target = input.checkpointId === undefined @@ -1164,25 +1173,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* ( diff --git a/packages/client-runtime/src/operations/threadTitle.ts b/packages/client-runtime/src/operations/threadTitle.ts index 0f57de34036a5..bb1fcd7648dbf 100644 --- a/packages/client-runtime/src/operations/threadTitle.ts +++ b/packages/client-runtime/src/operations/threadTitle.ts @@ -3,6 +3,7 @@ import type { MFunctionType } from "gt-i18n/types"; import type { ChatAttachment } from "@t3tools/contracts"; import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; +import { composerFileLinksToPlainText } from "@t3tools/shared/composerInlineTokens"; import { truncate } from "@t3tools/shared/String"; import { collectComposerModelMentions } from "../composerModelMentions.ts"; @@ -45,7 +46,7 @@ export function threadTitleTextFromPrompt( return reference.label; }); return ( - normalizeTitleSeed(modelMentionsAsSlugs(prose)) || + normalizeTitleSeed(modelMentionsAsSlugs(composerFileLinksToPlainText(prose))) || (imageIds.size > 0 ? attachedImagesTitle(imageIds.size, resolve) : "") ); } diff --git a/packages/client-runtime/src/rpc/client.ts b/packages/client-runtime/src/rpc/client.ts index 47abda57a7e0b..fbbac3322f651 100644 --- a/packages/client-runtime/src/rpc/client.ts +++ b/packages/client-runtime/src/rpc/client.ts @@ -299,6 +299,7 @@ function subscribeDynamicMapped( makeInput: (session: RpcSession) => Effect.Effect>, mapStream: ( session: RpcSession, + input: EnvironmentRpcInput, stream: Stream.Stream, EnvironmentRpcStreamFailure>, ) => Stream.Stream>, options?: SubscriptionOptions, @@ -351,6 +352,7 @@ function subscribeDynamicMapped( }); const stream = mapStream( session, + input, Stream.suspend(() => method(input)), ).pipe( Stream.onFirst(() => @@ -485,7 +487,7 @@ export function subscribeDynamic( EnvironmentRpcStreamFailure, EnvironmentSupervisor.EnvironmentSupervisor > { - return subscribeDynamicMapped(tag, makeInput, (_session, stream) => stream, options); + return subscribeDynamicMapped(tag, makeInput, (_session, _input, stream) => stream, options); } /** Tags each value before `switchMap` can buffer it across a session change. */ @@ -501,7 +503,29 @@ export function subscribeDynamicWithSession stream.pipe(Stream.map((value) => [session, value] as const)), + (session, _input, stream) => stream.pipe(Stream.map((value) => [session, value] as const)), + options, + ); +} + +/** + * Tags each value with the input of the attempt that produced it. Every + * `makeInput` call starts an attempt, including a resubscribe on the same + * session; `makeInput` must return a fresh object so the input identifies it. + */ +export function subscribeDynamicWithInput( + tag: TTag, + makeInput: (session: RpcSession) => Effect.Effect>, + options?: SubscriptionOptions, +): Stream.Stream< + readonly [input: EnvironmentRpcInput, value: EnvironmentRpcStreamValue], + EnvironmentRpcStreamFailure, + EnvironmentSupervisor.EnvironmentSupervisor +> { + return subscribeDynamicMapped( + tag, + makeInput, + (_session, input, stream) => stream.pipe(Stream.map((value) => [input, value] as const)), options, ); } @@ -524,7 +548,7 @@ export const subscribeVcsBranch = ( subscribeDynamicMapped( WS_METHODS.subscribeVcsBranch, () => Effect.succeed(input), - (session, stream) => + (session, _input, stream) => Stream.unwrap( session.initialConfig.pipe( Effect.mapError( diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index 1162ccfc91f0e..0b160e0bd32fb 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -291,6 +291,59 @@ const publishConfigEvents = Effect.fn("TestRpcSessionFactory.publishConfigEvents }); describe("RpcSessionFactory", () => { + it.effect.each([ + { established: false, closedWith: { _tag: "ConnectionBlockedError", reason: "unsupported" } }, + { + established: true, + closedWith: { _tag: "ConnectionTransientError", reason: "remote-unavailable" }, + }, + ])( + "ends the session when config fails to decode, after readiness=$established", + ({ established, closedWith }) => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* session.ready.pipe(Effect.exit, Effect.forkChild); + const socket = yield* awaitSocket(sockets); + socket.open(); + if (established) { + yield* completeInitialConfig(socket); + yield* Fiber.join(ready); + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + } else { + yield* completeInitialConfig(socket, { ...ENCODED_SERVER_CONFIG, cwd: 42 }); + expect(yield* Fiber.join(ready)).toMatchObject({ + _tag: "Failure", + cause: { reasons: [{ _tag: "Fail", error: { reason: "unsupported" } }] }, + }); + } + + expect(yield* Effect.flip(session.closed)).toMatchObject({ ...closedWith, hop: "server" }); + }).pipe(Effect.scoped), + ); + + it.effect( + "fails readiness with the disconnect when the socket closes before its first config", + () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const ready = yield* Effect.forkChild(Effect.flip(session.ready)); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* awaitRequest(socket); + socket.close(1012, "service restart"); + + for (const error of [yield* Fiber.join(ready), yield* Effect.flip(session.closed)]) { + expect(error).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "transport", + detail: "Test environment disconnected.", + }); + } + }).pipe(Effect.scoped), + ); + it.effect("connects while a large config snapshot downloads at 4000 bytes per second", () => Effect.gen(function* () { const { factory, sockets } = yield* makeFactory(); @@ -822,6 +875,33 @@ describe("RpcSessionFactory", () => { }), ); + it.effect("closes the session when the server interrupts the config stream", () => + Effect.gen(function* () { + const { factory, sockets } = yield* makeFactory(); + const session = yield* factory.connect(PREPARED); + const readyFiber = yield* Effect.forkChild(session.ready); + const socket = yield* awaitSocket(sockets); + socket.open(); + yield* completeInitialConfig(socket); + yield* Fiber.join(readyFiber); + + const closedFiber = yield* Effect.forkChild(Effect.flip(session.closed)); + const request = yield* awaitRequest(socket); + socket.serverMessage( + encodeJson({ + _tag: "Exit", + requestId: request.id, + exit: { _tag: "Failure", cause: [{ _tag: "Interrupt", fiberId: null }] }, + }), + ); + + expect(yield* Fiber.join(closedFiber)).toMatchObject({ + reason: "remote-unavailable", + detail: "Test environment config subscription ended.", + }); + }), + ); + it.effect.each([{ failure: "defect" as const }, { failure: "typed" as const }])( "keeps durable config state alive after an owned $failure failure", ({ failure }) => diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 409169ff1e345..91160a60941db 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -139,11 +139,14 @@ const isSocketErrorReason = Schema.is(Socket.SocketErrorReason); const PING_TIMEOUT_SECONDS = Duration.toSeconds(PING_TIMEOUT); function mapSessionRpcError( - error: InitialConfigError | ProbeError | ServerConfigSubscriptionError, - networkHint: string, + error: InitialConfigError | ProbeError | ServerConfigSubscriptionError | ConnectionAttemptError, via: "relay" | "direct", + socketFailure: () => ConnectionTransientError, ): ConnectionAttemptError { switch (error._tag) { + case "ConnectionBlockedError": + case "ConnectionTransientError": + return error; case "EnvironmentAuthorizationError": return new ConnectionBlockedError({ reason: "permission", @@ -160,11 +163,13 @@ function mapSessionRpcError( via, }); case "RpcClientError": - return new ConnectionTransientErrorClass({ - reason: "transport", - detail: `${error.message}${isSocketErrorReason(error.reason) ? networkHint : ""}`, - ...socketFailureLocation(via), - }); + return isSocketErrorReason(error.reason) + ? socketFailure() + : new ConnectionTransientErrorClass({ + reason: "transport", + detail: error.message, + ...socketFailureLocation(via), + }); } } @@ -194,47 +199,42 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( const connect = Effect.fnUntraced(function* (connection: PreparedConnection) { const via = connection.target._tag === "RelayConnectionTarget" ? "relay" : "direct"; - const networkHint = via === "relay" ? ` ${NETWORK_BLOCKING_HINT}` : ""; - const mapRpcError = (error: Parameters[0]) => - mapSessionRpcError(error, networkHint, via); yield* Effect.annotateCurrentSpan({ "connection.environment.id": connection.environmentId, }); const connected = yield* Deferred.make(); const disconnected = yield* Deferred.make(); - const pingTimedOut = yield* Ref.make(false); + let pingTimedOut = false; + const socketFailure = () => + new ConnectionTransientErrorClass({ + reason: "transport", + // The network hint only fits a socket that never opened. Once it + // opened, the path worked, and a host that goes quiet is more + // often overloaded or asleep than blocked. + ...(!Deferred.isDoneUnsafe(connected) + ? translatableDetail( + msg("{host} could not establish a WebSocket connection.", { + host: connection.label, + }), + ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), + ) + : pingTimedOut + ? translatableDetail( + msg("{host} stopped responding for {seconds}s.", { + host: connection.label, + seconds: String(PING_TIMEOUT_SECONDS), + }), + UNRESPONSIVE_HOST_HINT, + ) + : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), + ...socketFailureLocation(via), + }); + const mapRpcError = (error: Parameters[0]) => + mapSessionRpcError(error, via, socketFailure); const hooks = RpcClient.ConnectionHooks.of({ onConnect: Deferred.succeed(connected, undefined).pipe(Effect.asVoid), - onDisconnect: Effect.all([Deferred.isDone(connected), Ref.get(pingTimedOut)]).pipe( - Effect.flatMap(([wasConnected, timedOut]) => - Deferred.fail( - disconnected, - new ConnectionTransientErrorClass({ - reason: "transport", - // The network hint only fits a socket that never opened. Once it - // opened, the path worked, and a host that goes quiet is more - // often overloaded or asleep than blocked. - ...(!wasConnected - ? translatableDetail( - msg("{host} could not establish a WebSocket connection.", { - host: connection.label, - }), - ...(via === "relay" ? [NETWORK_BLOCKING_HINT] : []), - ) - : timedOut - ? translatableDetail( - msg("{host} stopped responding for {seconds}s.", { - host: connection.label, - seconds: String(PING_TIMEOUT_SECONDS), - }), - UNRESPONSIVE_HOST_HINT, - ) - : translatableDetail(msg("{host} disconnected.", { host: connection.label }))), - ...socketFailureLocation(via), - }), - ), - ), + onDisconnect: Effect.suspend(() => Deferred.fail(disconnected, socketFailure())).pipe( Effect.asVoid, ), }); @@ -267,7 +267,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( pingTimeout: PING_TIMEOUT, retryTransientErrors: false, retryPolicy: Schedule.recurs(0), - onPingTimeout: Ref.set(pingTimedOut, true), + // RpcClient runs this before it fails the open requests. + onPingTimeout: Effect.sync(() => { + pingTimedOut = true; + }), }).pipe( // Teardown sends an interrupt per open stream, and a write to a closed // socket waits out the client's 1s interrupt timeout before reconnecting. @@ -302,7 +305,10 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ); const protocolClient = yield* makeWsRpcProtocolClient.pipe(Effect.provide(protocolContext)); const initialConfigDeferred = yield* Deferred.make(); - const serverConfigExit = yield* Deferred.make(); + const serverConfigExit = yield* Deferred.make< + void, + ServerConfigSubscriptionError | ConnectionAttemptError + >(); const configSubscriptionClosed = yield* Deferred.make(); const serverConfigState = yield* Ref.make(Option.none()); const serverConfigUpdates = yield* PubSub.sliding(64); @@ -310,6 +316,8 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( reason: "remote-unavailable", detail: `${connection.label} config subscription ended.`, }); + // An interrupt while the session is not closing came from the server; it ends the subscription. + let closingSession = false; const configRequestedAtMs = yield* Clock.currentTimeMillis; const serverConfigSource = protocolClient[WS_METHODS.subscribeServerConfig]( onDemandSnapshots(serverConfigInput), @@ -362,8 +370,46 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( } }), ), + // An unreadable first snapshot means the versions are incompatible. A later + // unreadable update ends the session, and the reconnect's snapshot decides. + Effect.catchDefect((defect) => + Schema.isSchemaError(defect) + ? Effect.logWarning("Server configuration failed to decode.", { + environmentId: connection.environmentId, + issue: defect.message, + }).pipe( + Effect.andThen( + Effect.fail( + Deferred.isDoneUnsafe(initialConfigDeferred) + ? new ConnectionTransientErrorClass({ + reason: "remote-unavailable", + ...translatableDetail( + msg( + "{host} sent a server configuration update this client could not read.", + { host: connection.label }, + ), + ), + hop: "server", + via, + }) + : new ConnectionBlockedError({ + reason: "unsupported", + ...translatableDetail( + msg("{host} sent an incompatible server configuration.", { + host: connection.label, + }), + msg("Update the client and server to compatible versions."), + ), + hop: "server", + via, + }), + ), + ), + ) + : Effect.die(defect), + ), Effect.onExit((exit) => { - if (Exit.isSuccess(exit)) { + if (Exit.isSuccess(exit) || (Cause.hasInterruptsOnly(exit.cause) && !closingSession)) { return Effect.all([ Deferred.succeed(serverConfigExit, undefined), Deferred.fail(configSubscriptionClosed, configSubscriptionEndedError), @@ -379,6 +425,12 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( }), ); yield* serverConfigSource.pipe(Effect.forkScoped); + // Finalizers run in reverse, so this is set before the fork above is interrupted. + yield* Effect.addFinalizer(() => + Effect.sync(() => { + closingSession = true; + }), + ); const initialConfig = Effect.raceFirst( Deferred.await(initialConfigDeferred), Deferred.await(serverConfigExit).pipe( @@ -424,7 +476,9 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ).pipe( Stream.catchCause((cause) => { if (Cause.hasInterruptsOnly(cause)) { - return Stream.failCause(cause); + return Stream.failCause( + Cause.fromReasons(cause.reasons.filter(Cause.isInterruptReason)), + ); } // The supervisor keeps the original cause. Shared durable consumers // need a transport-shaped failure so they wait for its replacement. @@ -471,17 +525,11 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( client: protocolClient, initialConfig, subscribeServerConfig, - ready: Deferred.await(connected).pipe( - Effect.andThen(initialConfig), - Effect.asVoid, - Effect.raceFirst(Deferred.await(disconnected)), - ), + ready: initialConfig.pipe(Effect.asVoid), probe, inboundFrames: Effect.sync(() => inboundFrames), - closed: Effect.raceFirst( - Deferred.await(disconnected), - Deferred.await(configSubscriptionClosed), - ), + // The config stream also fails on disconnect, and only it can report a decode failure. + closed: Deferred.await(configSubscriptionClosed), } satisfies RpcSession; }); diff --git a/packages/client-runtime/src/state/filesystem.test.ts b/packages/client-runtime/src/state/filesystem.test.ts index f0c87f7c7f447..4b4547490f41c 100644 --- a/packages/client-runtime/src/state/filesystem.test.ts +++ b/packages/client-runtime/src/state/filesystem.test.ts @@ -78,6 +78,13 @@ describe("filesystem browse model", () => { parentPath: "~/", canBrowseUp: true, }); + expect(getFilesystemBrowsePath("D:", "Win32")).toEqual({ + isBrowsing: true, + directoryPath: "D:\\", + filterQuery: "", + parentPath: null, + canBrowseUp: false, + }); expect(getFilesystemBrowsePath("C:\\Users\\test", "MacIntel").isBrowsing).toBe(false); expect(getFilesystemBrowsePath("~/projects/", "", false).isBrowsing).toBe(false); }); diff --git a/packages/client-runtime/src/state/filesystem.ts b/packages/client-runtime/src/state/filesystem.ts index 1ee87c85d5507..d2bddeeb75ad4 100644 --- a/packages/client-runtime/src/state/filesystem.ts +++ b/packages/client-runtime/src/state/filesystem.ts @@ -70,9 +70,13 @@ export function resolveFilesystemReadAccess( export function getFilesystemBrowsePath(query: string, platform = "", enabled = true) { const isBrowsing = enabled && isFilesystemBrowseQuery(query, platform); - const directoryPath = isBrowsing ? getBrowseDirectoryPath(query) : ""; + // A bare drive has no separator, so it would otherwise filter its own listing by "D:". + const browseQuery = /^[a-zA-Z]:$/.test(query) ? `${query}\\` : query; + const directoryPath = isBrowsing ? getBrowseDirectoryPath(browseQuery) : ""; const filterQuery = - isBrowsing && !hasTrailingPathSeparator(query) ? getBrowseLeafPathSegment(query) : ""; + isBrowsing && !hasTrailingPathSeparator(browseQuery) + ? getBrowseLeafPathSegment(browseQuery) + : ""; const parentPath = isBrowsing ? getBrowseParentPath(directoryPath) : null; return { diff --git a/packages/client-runtime/src/state/peerLinks.test.ts b/packages/client-runtime/src/state/peerLinks.test.ts index 75430e340fbff..dd39162df8a4c 100644 --- a/packages/client-runtime/src/state/peerLinks.test.ts +++ b/packages/client-runtime/src/state/peerLinks.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + PeerLinkThreadReadError, WS_METHODS, type OrchestrationV2ThreadHistoryPage, type OrchestrationV2ThreadStreamItem, @@ -15,6 +16,7 @@ import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { TestClock } from "effect/testing"; import { EnvironmentRegistry } from "../connection/registry.ts"; import { EnvironmentSupervisor } from "../connection/supervisor.ts"; @@ -25,7 +27,7 @@ import { createPeerLinkEnvironmentAtoms, linkThroughRoutes } from "./peerLinks.t // regression: #40544 earlier messages vanished when a linked thread's view opened again it.effect( - "keeps loaded messages when a linked thread's view opens again on the same snapshot", + "keeps loaded messages when a linked thread retries and reopens on the same snapshot", () => Effect.gen(function* () { const recent = v2MessageRow("Recent message", 2); @@ -38,7 +40,7 @@ it.effect( hasMoreHistory: true, }); const subscriptions = yield* Queue.unbounded<{ - items: Queue.Queue; + items: Queue.Queue; stopped: Deferred.Deferred; }>(); const requested: string[] = []; @@ -46,7 +48,10 @@ it.effect( [WS_METHODS.peerLinksSubscribeThread]: () => Stream.unwrap( Effect.gen(function* () { - const items = yield* Queue.unbounded(); + const items = yield* Queue.unbounded< + OrchestrationV2ThreadStreamItem, + PeerLinkThreadReadError + >(); const stopped = yield* Deferred.make(); yield* Effect.addFinalizer(() => Deferred.succeed(stopped, undefined)); yield* Queue.offer(subscriptions, { items, stopped }); @@ -102,8 +107,26 @@ it.effect( older.sourceItemId, recent.sourceItemId, ]); + const unreachable = new PeerLinkThreadReadError({ + reason: "unreachable", + label: "Linked", + message: "The linked machine is temporarily unreachable.", + }); + yield* Queue.fail(first.items, unreachable); + expect((yield* Queue.take(views)).error).toBe(unreachable); + + registry.refresh(links.threadView(target)); + yield* TestClock.adjust(0); + const retry = yield* Queue.poll(subscriptions); + if (Option.isNone(retry)) throw new Error("Refresh did not start a new linked thread read"); + yield* Queue.offer(retry.value.items, snapshot("before-recent")); + const recovered = yield* Queue.take(views).pipe( + Effect.repeat({ until: (view) => view.error === null }), + ); + expect(visibleMessages(recovered)).toEqual([older.sourceItemId, recent.sourceItemId]); + unmount(); - yield* Deferred.await(first.stopped); + yield* Deferred.await(retry.value.stopped); open(); const reopened = yield* Queue.take(subscriptions); diff --git a/packages/client-runtime/src/state/peerLinks.ts b/packages/client-runtime/src/state/peerLinks.ts index fd9d269bfd726..a7af1ac15b4c9 100644 --- a/packages/client-runtime/src/state/peerLinks.ts +++ b/packages/client-runtime/src/state/peerLinks.ts @@ -87,13 +87,16 @@ export function createPeerLinkEnvironmentAtoms( ), ) .pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-stream:${key}`)); - return Atom.make((get) => { - const live = get(stream); - if (AsyncResult.isSuccess(live)) { - get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); - } - return live; - }).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); + return Atom.readable( + (get) => { + const live = get(stream); + if (AsyncResult.isSuccess(live)) { + get.set(kept, keepLinkedThreadView(get.once(kept), live.value)); + } + return live; + }, + (refresh) => refresh(stream), + ).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-data:peer-links:thread-view:${key}`)); }); return { list, diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index a4049c7169163..fd8092a996a66 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -6,6 +6,7 @@ import { deriveThreadQueueWorkflowState, getUserQueuedThreadRuns, resolveLatestMergeBackRun, + threadCanSteer, threadSupportsProviderHandoff, } from "./threadWorkflows.ts"; @@ -13,6 +14,7 @@ const capabilities = (input?: { readonly queued?: boolean; readonly steer?: boolean; readonly restartSteer?: boolean; + readonly interrupt?: boolean; readonly nativeFork?: boolean; readonly portableFork?: boolean; }) => @@ -21,6 +23,7 @@ const capabilities = (input?: { supportsQueuedMessages: input?.queued ?? false, supportsActiveSteering: input?.steer ?? false, supportsSteeringByInterruptRestart: input?.restartSteer ?? false, + supportsInterrupt: input?.interrupt ?? false, }, threads: { canForkThread: input?.nativeFork ?? false, @@ -31,6 +34,35 @@ const capabilities = (input?: { }) as never; describe("thread workflows", () => { + it.each([ + ["queue only", { queued: true }, false, false], + ["session still attaching", undefined, false, true], + ["native steering", { steer: true }, false, true], + ["interrupt and restart", { interrupt: true, restartSteer: true }, false, true], + ["restart without interrupt", { restartSteer: true }, false, false], + ["explicit compaction", { steer: true }, true, false], + ] as const)("gates composer steering for %s", (_, turns, compactCommandIsActive, expected) => { + const projection = { + thread: { id: "thread", activeProviderThreadId: "provider-thread" }, + runs: [{ id: "active", status: "running", providerThreadId: "provider-thread" }], + providerThreads: [{ id: "provider-thread", providerSessionId: "session" }], + providerSessions: [ + ...(turns === undefined + ? [] + : [{ id: "session", status: "running", capabilities: capabilities(turns) }]), + { id: "other", status: "ready", capabilities: capabilities({ steer: true }) }, + ], + messages: [], + } as unknown as OrchestrationV2ThreadProjection; + expect( + threadCanSteer(projection, { + compactCommandIsActive, + compactionRunning: false, + activeRunId: projection.runs[0]!.id, + }), + ).toBe(expected); + }); + it("skips message history classification when no runs are queued", () => { let metadataReads = 0; const message = { @@ -139,7 +171,7 @@ describe("thread workflows", () => { { id: "provider-session", status: "running", - capabilities: capabilities({ queued: true, restartSteer: true }), + capabilities: capabilities({ queued: true, interrupt: true, restartSteer: true }), }, ], } as never); diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 7dbbcf1e80c57..9e3d1eb4512b2 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -8,6 +8,7 @@ import { copySorted } from "@t3tools/shared/Array"; import { mFallback, msg } from "gt-i18n"; import type { MFunctionType } from "gt-i18n/types"; +import { compactionBlocksSteering } from "./composerDispatch.ts"; import type { ThreadStructure } from "./models.ts"; type Projection = ThreadStructure; @@ -102,6 +103,33 @@ export function threadSteersDuringCompaction(projection: Projection | null | und ); } +function supportsSteering(turns: OrchestrationV2ProviderCapabilities["turns"]): boolean { + return ( + turns.supportsActiveSteering || + (turns.supportsInterrupt && turns.supportsSteeringByInterruptRestart) + ); +} + +export function threadCanSteer( + projection: Projection | null, + input: { + readonly compactCommandIsActive: boolean; + readonly compactionRunning: boolean; + readonly activeRunId: Run["id"] | null | undefined; + }, +): boolean { + const turns = projection && resolveThreadProviderSession(projection)?.capabilities.turns; + // A steer submitted before the session attaches can wait for its provider turn. + if (turns && !supportsSteering(turns)) return false; + return !compactionBlocksSteering({ + compactCommandIsActive: input.compactCommandIsActive, + compactionRunning: input.compactionRunning, + steersDuringCompaction: turns?.activeSteeringDuringCompaction === true, + run: projection?.runs.find((run) => run.id === input.activeRunId), + messages: projection?.messages, + }); +} + export function threadSupportsProviderHandoff(projection: Projection | null | undefined): boolean { if (projection == null) return false; const session = resolveThreadProviderSession(projection); @@ -147,6 +175,7 @@ export function deriveThreadQueueWorkflowState( const activeRun = resolveActiveThreadRun(projection); const session = resolveThreadProviderSession(projection); const capabilities = session?.capabilities.turns; + const canSteer = capabilities !== undefined && supportsSteering(capabilities); const activeMessage = projection.messages.find( (message) => message.id === activeRun?.userMessageId, ); @@ -187,12 +216,8 @@ export function deriveThreadQueueWorkflowState( canPromoteToSteer: promoteSkipsCompaction || ((activeRun?.status === "preparing" || activeRun?.status === "starting") && - (capabilities === undefined || - capabilities.supportsActiveSteering || - capabilities.supportsSteeringByInterruptRestart)) || - (hasSteerableProviderTurn && - (capabilities?.supportsActiveSteering === true || - capabilities?.supportsSteeringByInterruptRestart === true)), + (capabilities === undefined || canSteer)) || + (hasSteerableProviderTurn && canSteer), promoteSkipsCompaction, }; } diff --git a/packages/client-runtime/src/state/threads-atoms.test.ts b/packages/client-runtime/src/state/threads-atoms.test.ts index 3ccb7b2c07c68..ddc7c58459209 100644 --- a/packages/client-runtime/src/state/threads-atoms.test.ts +++ b/packages/client-runtime/src/state/threads-atoms.test.ts @@ -306,6 +306,8 @@ describe("createEnvironmentThreadStateAtoms", () => { }); const unmount = h.registry.mount(h.stateAtom); const first = yield* Queue.take(h.subscriptions); + yield* Queue.offer(first.events, { kind: "synchronized" }); + yield* observeState(h.registry, h.stateAtom, (state) => state.status === "live"); const loading = yield* h.loadEarlier().pipe(Effect.forkScoped); const older = yield* Queue.take(h.olderLoads); expect(h.registry.get(h.stateAtom).history.loading).toBe(true); diff --git a/packages/client-runtime/src/state/threads-sync.test.ts b/packages/client-runtime/src/state/threads-sync.test.ts index 80d0569a43788..be50082cce87c 100644 --- a/packages/client-runtime/src/state/threads-sync.test.ts +++ b/packages/client-runtime/src/state/threads-sync.test.ts @@ -23,8 +23,8 @@ import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; import * as Scheduler from "effect/Scheduler"; +import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; @@ -133,6 +133,9 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o readonly getTurnItem?: (input: { readonly itemId: TurnItemId; }) => Effect.Effect<{ readonly item: OrchestrationV2TurnItem | null }>; + readonly streamFor?: ( + subscription: number, + ) => Stream.Stream | undefined; }) { const inputs = yield* Queue.unbounded(); const observed = yield* Queue.unbounded(); @@ -168,17 +171,19 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o readonly acceptCompactTurnItems?: true; }) => Stream.unwrap( - Ref.set(lastSubscribeAfterSequence, input.afterSequence).pipe( - Effect.andThen( - Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true), - ), - Effect.andThen(Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot)), - Effect.andThen(Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems)), - Effect.andThen(SubscriptionRef.update(subscriptionCount, (count) => count + 1)), - Effect.as( - options?.completionMarker === true - ? streamFrom(inputs) - : Stream.concat(Stream.make(synchronized()), streamFrom(inputs)), + Effect.all([ + Ref.set(lastSubscribeAfterSequence, input.afterSequence), + Ref.set(lastRequestCompletionMarker, input.requestCompletionMarker === true), + Ref.set(lastAcceptBoundedSnapshot, input.acceptBoundedSnapshot), + Ref.set(lastAcceptCompactTurnItems, input.acceptCompactTurnItems), + ]).pipe( + Effect.andThen(SubscriptionRef.updateAndGet(subscriptionCount, (count) => count + 1)), + Effect.map( + (count) => + options?.streamFor?.(count) ?? + (options?.completionMarker === true + ? streamFrom(inputs) + : Stream.concat(Stream.make(synchronized()), streamFrom(inputs))), ), ), ), @@ -317,6 +322,15 @@ const makeHarness = Effect.fn("TestEnvironmentThreads.makeHarness")(function* (o }; }); +const awaitSubscriptionCount = ( + harness: { readonly subscriptionCount: SubscriptionRef.SubscriptionRef }, + count: number, +) => + SubscriptionRef.changes(harness.subscriptionCount).pipe( + Stream.filter((current) => current >= count), + Stream.runHead, + ); + const snapshot = ( projection: OrchestrationV2ThreadProjection, snapshotSequence = 1, @@ -2531,34 +2545,30 @@ describe("EnvironmentThreads", () => { }), ); - it.effect("keeps replayed updates synchronizing until the completion marker arrives", () => + it.effect("publishes a 20-event catch-up as one state change at its marker", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); - yield* awaitThreadState( - harness.observed, - (value) => value.status === "synchronizing" && Option.isSome(value.data), - ); + yield* awaitSubscriptionCount(harness, 1); expect(yield* Ref.get(harness.lastRequestCompletionMarker)).toBe(true); - - yield* Queue.offer( - harness.inputs, - titleUpdated("Caught-up title", CACHED_SNAPSHOT_SEQUENCE + 1), - ); - const catchingUp = yield* awaitThreadState( - harness.observed, - (value) => - value.status === "synchronizing" && - Option.isSome(value.data) && - value.data.value.thread.title === "Caught-up title", - ); - expect(catchingUp.status).toBe("synchronizing"); - + // The observer replays the current state when it starts; take it so clearing drops it. + yield* Queue.take(harness.observed); + yield* Queue.clear(harness.observed); + // Separate frames, as the server sends a replay. + for (let index = 1; index <= 20; index += 1) { + yield* Queue.offer( + harness.inputs, + titleUpdated(`Title ${index}`, CACHED_SNAPSHOT_SEQUENCE + index), + ); + yield* Effect.yieldNow; + } yield* Queue.offer(harness.inputs, synchronized()); - const live = yield* awaitThreadState( - harness.observed, - (value) => value.status === "live" && Option.isSome(value.data), - ); - expect(Option.getOrThrow(live.data).thread.title).toBe("Caught-up title"); + const live = yield* Queue.take(harness.observed); + expect(live.status).toBe("live"); + expect(Option.getOrThrow(live.data).thread.title).toBe("Title 20"); + + yield* Queue.offer(harness.inputs, titleUpdated("Live title", CACHED_SNAPSHOT_SEQUENCE + 21)); + const next = yield* Queue.take(harness.observed); + expect(Option.getOrThrow(next.data).thread.title).toBe("Live title"); }), ); @@ -2594,6 +2604,107 @@ describe("EnvironmentThreads", () => { }), ); + // A long batch yields to the scheduler while it applies, so the next attempt + // can start while the replaced attempt's batch and items are still landing. + const LONG_BATCH = 1000; + + it.effect( + "does not apply a replaced attempt's snapshot after the next attempt reads its cursor", + () => + Effect.gen(function* () { + const sent = yield* Deferred.make(); + const harness = yield* makeHarness({ + cached: BASE_PROJECTION, + streamFor: (subscription) => + subscription === 1 + ? Stream.fromArray([ + synchronized(), + snapshot(BASE_PROJECTION, 8), + ...Array.from({ length: LONG_BATCH }, (_, index) => + titleUpdated(`Title ${index + 9}`, index + 9), + ), + snapshot({ + ...BASE_PROJECTION, + thread: { ...BASE_PROJECTION.thread, title: "Stale" }, + }), + ]).pipe( + Stream.rechunk(1), + Stream.concat( + Stream.fromEffect(Deferred.succeed(sent, undefined)).pipe(Stream.drain), + ), + Stream.concat(Stream.never), + ) + : undefined, + }); + yield* Deferred.await(sent); + yield* Queue.offer(harness.wakeups, "application-active"); + yield* awaitSubscriptionCount(harness, 2); + yield* Queue.offer(harness.inputs, titleUpdated("Live", LONG_BATCH + 9)); + const titles: Array = []; + yield* awaitThreadState(harness.observed, (value) => { + titles.push(Option.getOrNull(value.data)?.thread.title); + return Option.getOrNull(value.data)?.thread.title === "Live"; + }); + // The next attempt started with the snapshot still buffered: its cursor + // is past the replaced snapshot's sequence but short of the batch end. + const cursor = yield* Ref.get(harness.lastSubscribeAfterSequence); + expect(cursor).toBeGreaterThan(8); + expect(cursor).toBeLessThan(LONG_BATCH + 8); + expect(titles).not.toContain("Stale"); + }).pipe( + // A small budget lets the next attempt start between the consumer's + // batches, before it takes the queued snapshot. + Effect.provideService(Scheduler.MaxOpsBeforeYield, 50), + ), + ); + + it.effect("does not apply a replaced attempt's late marker without its dropped prefix", () => + Effect.gen(function* () { + const sent = yield* Deferred.make(); + const replay = [ + questionResolved(CACHED_SNAPSHOT_SEQUENCE + 1), + ...Array.from({ length: 40 }, (_, index) => + titleUpdated(`Title ${index}`, CACHED_SNAPSHOT_SEQUENCE + 2 + index), + ), + synchronized(), + ]; + const harness = yield* makeHarness({ + cached: PROJECTION_WITH_QUESTION, + completionMarker: true, + streamFor: (subscription) => + subscription === 1 + ? Stream.fromArray(replay).pipe( + Stream.rechunk(1), + Stream.concat( + Stream.fromEffect(Deferred.succeed(sent, undefined)).pipe(Stream.drain), + ), + Stream.concat(Stream.never), + ) + : undefined, + }); + yield* Deferred.await(sent); + yield* Queue.offer(harness.wakeups, "application-active"); + yield* awaitSubscriptionCount(harness, 2); + // The next attempt started before the replaced attempt's buffered marker landed. + expect(yield* Ref.get(harness.lastSubscribeAfterSequence)).toBe(CACHED_SNAPSHOT_SEQUENCE); + yield* Queue.offerAll(harness.inputs, [ + ...replay, + titleUpdated("Live", CACHED_SNAPSHOT_SEQUENCE + 42), + ]); + const live = yield* awaitThreadState( + harness.observed, + (value) => Option.getOrNull(value.data)?.thread.title === "Live", + ); + expect(Option.getOrThrow(live.data).runtimeRequests.map((request) => request.status)).toEqual( + ["resolved"], + ); + }).pipe( + // The replaced attempt's items fill the switch buffer, and a small budget + // lets the next attempt start while the consumer still drains them. + Effect.provideService(Scheduler.MaxOpsBeforeYield, 5), + ), + ); + it.effect("skips an unknown event type and resumes after it", () => Effect.gen(function* () { const harness = yield* makeHarness({ cached: BASE_PROJECTION, completionMarker: true }); diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.ts index 7ea4b72e4779f..4882df1a6836e 100644 --- a/packages/client-runtime/src/state/threads.ts +++ b/packages/client-runtime/src/state/threads.ts @@ -37,7 +37,7 @@ import * as ManagedRelay from "../relay/managedRelay.ts"; import { isAuthorizationFailure, request, - subscribeDynamic, + subscribeDynamicWithInput, subscriptionRetryDelay, } from "../rpc/client.ts"; import { parseThreadKey, threadKey } from "./entities.ts"; @@ -665,10 +665,13 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make ) { if (item.kind === "synchronized") { yield* Ref.set(awaitingCompletion, false); - yield* SubscriptionRef.update(state, (current) => - Option.isSome(current.data) && current.status !== "deleted" && Option.isNone(current.error) - ? { ...current, status: "live" as const, error: Option.none() } - : current, + yield* SubscriptionRef.updateSome(state, (current) => + Option.isSome(current.data) && + current.status !== "deleted" && + current.status !== "live" && + Option.isNone(current.error) + ? Option.some({ ...current, status: "live" as const }) + : Option.none(), ); return; } @@ -701,12 +704,41 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* applyEventsLocked([item]); }); + // Items held until the completion marker apply together, so a replay-only resume renders once. + // A new attempt drops the previous attempt's held and late items (unapplied, so its cursor + // replays them). Both run under applyLock: each batch lands wholly before or after an attempt. + let attempt: unknown; + let catchUp: OrchestrationV2ThreadStreamItem[] = []; + const startAttempt = applyLock.withPermits(1)( + Effect.sync(() => { + attempt = undefined; + catchUp = []; + }), + ); // Keep this per-batch streaming path untraced for the same reason as applyEventsLocked. - const applyItems = Effect.fnUntraced(function* ( - items: ReadonlyArray, + const receiveItems = Effect.fnUntraced(function* ( + received: ReadonlyArray, ) { yield* applyLock.withPermits(1)( Effect.gen(function* () { + let completes = false; + for (const [input, item] of received) { + if (input !== attempt) continue; + catchUp.push(item); + if (item.kind === "synchronized") completes = true; + } + if (catchUp.length === 0) return; + if (!completes && (yield* Ref.get(awaitingCompletion))) { + // A warm resume keeps its "live" status until it learns it is behind. + yield* SubscriptionRef.updateSome(state, (current) => + current.status === "live" + ? Option.some({ ...current, status: "synchronizing" as const }) + : Option.none(), + ); + return; + } + const items = catchUp; + catchUp = []; let events: SequencedItem[] = []; for (const item of items) { if ( @@ -716,6 +748,9 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make events.push(item); continue; } + // Clearing the flag first lets the events before the marker publish + // "live", so a catch-up ending in the marker is one state change. + if (item.kind === "synchronized") yield* Ref.set(awaitingCompletion, false); yield* applyEventsLocked(events); events = []; yield* applyItemLocked(item); @@ -1028,9 +1063,10 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make never, EnvironmentSupervisor.EnvironmentSupervisor > => - subscribeDynamic( + subscribeDynamicWithInput( ORCHESTRATION_V2_WS_METHODS.subscribeThread, Effect.fn("EnvironmentThreadState.makeSubscribeInput")(function* (session) { + yield* startAttempt; let current = yield* SubscriptionRef.get(state); // A delete event already cleared this thread. Park without opening the socket. if (current.status === "deleted" && httpMisses === 0) { @@ -1119,7 +1155,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make yield* Ref.set(resuming, canResume); const acceptBoundedSnapshot = yield* Ref.get(acceptsBoundedSocketSnapshots); - return { + const input = { threadId, ...(canResume ? { afterSequence: sequence } : {}), requestCompletionMarker: true as const, @@ -1133,6 +1169,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make : {}), acceptDedupedBodies: true as const, }; + attempt = input; + return input; }), { // A socket-only open that fails retries over HTTP, which tells a @@ -1161,7 +1199,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make }, ).pipe( Stream.runForEachArray((items) => - applyItems(items).pipe( + receiveItems(items).pipe( Effect.andThen( Effect.sync(() => { defectRetries = 0; diff --git a/packages/client-runtime/src/workspaceBasenameLookup.ts b/packages/client-runtime/src/workspaceBasenameLookup.ts index 6698aed52fb38..ae55263fb2bd4 100644 --- a/packages/client-runtime/src/workspaceBasenameLookup.ts +++ b/packages/client-runtime/src/workspaceBasenameLookup.ts @@ -118,7 +118,7 @@ function pickStrippedWorkspaceMatch( } /** - * The absolute path of the one file a chat link names across other project roots, or null when + * The absolute path of the one file a chat link names across project roots, or null when * no root has it or roots name different files. Agents cite paths relative to their repo. * Nested project roots list the same file more than once, which still names one file. */ @@ -131,6 +131,9 @@ export function pickProjectLinkMatch( ): string | null { const target = relativePath.trim(); const isBasename = needsWorkspaceBasenameLookup(target); + const folded = target.toLowerCase(); + const isFoldedMatch = (entry: WorkspaceEntryCandidate) => + entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded; const matches = new Map(); let rootHits = 0; const addMatch = (path: string) => { @@ -140,10 +143,10 @@ export function pickProjectLinkMatch( }; for (const { root, entries } of searches) { if (isBasename) { - const match = pickWorkspaceBasenameMatch(target, entries); - if (match === null) continue; + if (!entries.some(isFoldedMatch)) continue; rootHits += 1; - addMatch(resolveWorkspaceFilePath(match, root)); + const match = pickWorkspaceBasenameMatch(target, entries); + if (match !== null) addMatch(resolveWorkspaceFilePath(match, root)); } else { for (const match of workspaceQualifiedPathMatches(target, root, entries)) { addMatch(resolveWorkspaceFilePath(match, root)); @@ -152,12 +155,9 @@ export function pickProjectLinkMatch( } if (isBasename && rootHits > 1) { // A root's pick, or a root left ambiguous by case, can hide another file elsewhere. - const folded = target.toLowerCase(); for (const { root, entries } of searches) { for (const entry of entries) { - if (entry.kind === "file" && basenameOfPath(entry.path).toLowerCase() === folded) { - addMatch(resolveWorkspaceFilePath(entry.path, root)); - } + if (isFoldedMatch(entry)) addMatch(resolveWorkspaceFilePath(entry.path, root)); } } } diff --git a/packages/contracts/src/auth.ts b/packages/contracts/src/auth.ts index 92d7a59a92a68..237a74ccc7139 100644 --- a/packages/contracts/src/auth.ts +++ b/packages/contracts/src/auth.ts @@ -555,6 +555,8 @@ export const AuthMcpAuthorizationServerMetadata = Schema.Struct({ authorization_endpoint: Schema.String, token_endpoint: Schema.String, registration_endpoint: Schema.String, + // Older environments do not serve one. + revocation_endpoint: Schema.optionalKey(Schema.String), response_types_supported: Schema.Array(Schema.Literal("code")), grant_types_supported: Schema.Array(Schema.Literal("authorization_code")), code_challenge_methods_supported: Schema.Array(Schema.Literal("S256")), @@ -671,6 +673,13 @@ export const AuthMcpTokenRequest = Schema.Struct({ }).pipe(HttpApiSchema.asFormUrlEncoded()); export type AuthMcpTokenRequest = typeof AuthMcpTokenRequest.Type; +/** RFC 7009: the holder of an access token ends its session. */ +export const AuthMcpRevokeRequest = Schema.Struct({ + token: Schema.optionalKey(Schema.RedactedFromValue(Schema.String)), + token_type_hint: Schema.optionalKey(Schema.String), +}).pipe(HttpApiSchema.asFormUrlEncoded()); +export type AuthMcpRevokeRequest = typeof AuthMcpRevokeRequest.Type; + export const AuthMcpTokenResult = Schema.Struct({ access_token: Schema.String, token_type: Schema.Literal("Bearer"), diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 4578a34efb5b5..4b0cb16ed5ca1 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -25,6 +25,7 @@ import { AuthMcpRegisteredClient, AuthMcpRegistrationError, AuthMcpTokenError, + AuthMcpRevokeRequest, AuthMcpTokenRequest, AuthMcpTokenResult, AuthPairingCredentialResult, @@ -738,6 +739,12 @@ class EnvironmentMcpOAuthHttpApi extends HttpApiGroup.make("mcpOAuth") success: AuthMcpTokenResult, error: AuthMcpTokenError, }), + ) + .add( + HttpApiEndpoint.post("revoke", "/oauth/mcp/revoke", { + payload: AuthMcpRevokeRequest, + success: HttpApiSchema.Empty(200), + }), ) {} const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ diff --git a/packages/contracts/src/issue.ts b/packages/contracts/src/issue.ts index 78b0cbb04b852..93ed9daf6fba8 100644 --- a/packages/contracts/src/issue.ts +++ b/packages/contracts/src/issue.ts @@ -150,6 +150,14 @@ export const IssueEventKind = Schema.Literals([ ]); export type IssueEventKind = typeof IssueEventKind.Type; +export const IssueEventReference = Schema.Struct({ + repository: TrimmedNonEmptyString, + number: PositiveInt, + kind: Schema.Literals(["issue", "pull-request"]), + url: TrimmedNonEmptyString, +}); +export type IssueEventReference = typeof IssueEventReference.Type; + export const IssueEvent = Schema.Struct({ id: TrimmedNonEmptyString, kind: IssueEventKind, @@ -157,6 +165,8 @@ export const IssueEvent = Schema.Struct({ createdAt: IsoDateTime, /** What the event was about, where it has a subject: a label name, a login, a new title. */ detail: Schema.NullOr(TrimmedNonEmptyString), + /** The issue or change request a `referenced` event came from, so a surface can open it. */ + reference: Schema.optional(IssueEventReference), }); export type IssueEvent = typeof IssueEvent.Type; diff --git a/packages/contracts/src/orchestratorMcp.ts b/packages/contracts/src/orchestratorMcp.ts index cd8dc9e3e1e47..7aa4c5c16564e 100644 --- a/packages/contracts/src/orchestratorMcp.ts +++ b/packages/contracts/src/orchestratorMcp.ts @@ -109,7 +109,7 @@ export const OrchestratorMcpTarget = Schema.Struct({ options: Schema.optional( OrchestratorMcpTargetOptions.annotate({ description: - "Options from `orchestrator_capabilities`, such as {effort:'max'}. Given values override inherited. [] or {} clears.", + "Ids vary by provider; see `orchestrator_capabilities`. Given values override inherited. [] or {} clears.", }), ), environmentId: Schema.optional( @@ -983,6 +983,7 @@ export type OrchestratorMcpEnvironmentUnlinkInput = export const OrchestratorMcpEnvironmentUnlinkResult = Schema.Struct({ environmentId: EnvironmentId, removed: Schema.Boolean, + endedThere: Schema.Boolean, }); export type OrchestratorMcpEnvironmentUnlinkResult = typeof OrchestratorMcpEnvironmentUnlinkResult.Type; diff --git a/packages/contracts/src/peerLink.ts b/packages/contracts/src/peerLink.ts index 6f33686b4b37b..3ff0fe93228d8 100644 --- a/packages/contracts/src/peerLink.ts +++ b/packages/contracts/src/peerLink.ts @@ -63,7 +63,11 @@ export type PeerLinkCreateInput = typeof PeerLinkCreateInput.Type; export const PeerLinkRemoveInput = Schema.Struct({ environmentId: EnvironmentId }); export type PeerLinkRemoveInput = typeof PeerLinkRemoveInput.Type; -export const PeerLinkRemoveResult = Schema.Struct({ removed: Schema.Boolean }); +export const PeerLinkRemoveResult = Schema.Struct({ + removed: Schema.Boolean, + // Whether the peer ended the link's session. Older servers never ask it to. + endedThere: Schema.optionalKey(Schema.Boolean), +}); export type PeerLinkRemoveResult = typeof PeerLinkRemoveResult.Type; /** Why linking or calling a peer failed, in words a user can act on. */ diff --git a/packages/contracts/src/pullRequest.ts b/packages/contracts/src/pullRequest.ts index 9e32f39c15cf3..0aa07b6cead5b 100644 --- a/packages/contracts/src/pullRequest.ts +++ b/packages/contracts/src/pullRequest.ts @@ -389,6 +389,10 @@ export const PullRequestStackMembership = Schema.Struct({ }); export type PullRequestStackMembership = typeof PullRequestStackMembership.Type; +/** Who can read a pull request on a host that can hide one in a public repository. */ +export const PullRequestVisibility = Schema.Literals(["public", "private"]); +export type PullRequestVisibility = typeof PullRequestVisibility.Type; + export const PullRequestListEntry = Schema.Struct({ stack: Schema.optional(PullRequestStackMembership), provider: SourceControlProviderKind, @@ -416,6 +420,8 @@ export const PullRequestListEntry = Schema.Struct({ labels: Schema.Array(PullRequestLabel), reviewDecision: Schema.optional(PullRequestReviewDecision), checksState: Schema.optional(PullRequestChecksState), + /** Absent where the host has no private pull requests or names no visibility. */ + visibility: Schema.optional(PullRequestVisibility), }); export type PullRequestListEntry = typeof PullRequestListEntry.Type; @@ -717,6 +723,8 @@ export const PullRequestDetail = Schema.Struct({ /** Absent where the host has no merge queue or does not report one. */ mergeQueueRemoval: Schema.optional(PullRequestMergeQueueRemoval), maintainerCanModify: Schema.optional(Schema.Boolean), + /** Absent where the host has no private pull requests or names no visibility. */ + visibility: Schema.optional(PullRequestVisibility), }); export type PullRequestDetail = typeof PullRequestDetail.Type; diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts index 3e2fbf25124a4..6f7238eb2a7a3 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.test.ts @@ -360,7 +360,7 @@ describe("AcpRegistrySupport", () => { registryUrl, }).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => `C:\\bin\\dsh${extension}`), + Effect.provideService(SpawnExecutableResolution, async () => `C:\\bin\\dsh${extension}`), ); const localSettings = decodeAcpRegistrySettings({ source: "local", commandPath: "dsh" }); for (const failure of [ @@ -1251,6 +1251,7 @@ describe("AcpRegistrySupport", () => { name: "Codex Darwin", } satisfies AcpRegistrySupport.AcpRegistryAgent; + const lookups: string[] = []; return Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const cacheDir = yield* fileSystem.makeTempDirectoryScoped({ @@ -1260,9 +1261,15 @@ describe("AcpRegistrySupport", () => { cacheDir, toolsDir: `${cacheDir}/tools`, registryUrl, - }); + }).pipe( + Effect.provideService(SpawnExecutableResolution, async (command) => { + lookups.push(command); + return "/bin/npm"; + }), + ); const result = yield* resolver.search({ query: "codex" }); + expect(lookups).toEqual(["npm"]); expect(result.agents.map((agent) => agent.id)).toEqual(["codex-acp", "other-agent"]); expect(result.agents[0]).toMatchObject({ authors: ["OpenAI", "Zed Industries"], diff --git a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts index 0c8b7fe824ab9..7e834c67208f6 100644 --- a/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts +++ b/packages/provider-acp-registry/src/server/AcpRegistrySupport.ts @@ -708,7 +708,13 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; const hostEnvironment = yield* HostProcess.Environment; - const resolveExecutable = yield* SpawnExecutableResolution; + const executableResolver = yield* SpawnExecutableResolution; + const resolveExecutable = Effect.fn("AcpRegistryCatalog.resolveExecutable")(function* ( + command: string, + environment: NodeJS.ProcessEnv, + ) { + return yield* Effect.promise(async () => executableResolver(command, platform, environment)); + }); const platformTarget = resolveAcpRegistryPlatformTarget(platform, architecture); const registryUrl = input.registryUrl ?? ACP_REGISTRY_URL; const registryDirectory = path.join(input.cacheDir, "acp-registry"); @@ -1275,9 +1281,8 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandName = npmCommandName(agent, packageIdentity.name, manifest.value); if (commandName === undefined) return Option.none(); const binDirectory = platform === "win32" ? globalPrefix : path.join(globalPrefix, "bin"); - const executablePath = resolveExecutable( + const executablePath = yield* resolveExecutable( path.join(binDirectory, commandName), - platform, environment, ); return executablePath === undefined @@ -1324,9 +1329,11 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct truncatedOutputReason: "install_failed", }).pipe(Effect.flatMap((output) => parsePackageManagerPath(managerPath, output))); const managedBinEnvironment = { ...environment, PATH: binDirectory }; - const executablePath = packageCommandCandidates(agent, packageIdentity.name) - .map((candidate) => resolveExecutable(candidate, platform, managedBinEnvironment)) - .find((candidate): candidate is string => candidate !== undefined); + let executablePath: string | undefined; + for (const candidate of packageCommandCandidates(agent, packageIdentity.name)) { + executablePath = yield* resolveExecutable(candidate, managedBinEnvironment); + if (executablePath !== undefined) break; + } return executablePath === undefined ? Option.none() : Option.some({ @@ -1349,7 +1356,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct environment: NodeJS.ProcessEnv, ) { const managerName = packageManagerFor(distribution)!; - const managerPath = resolveExecutable(managerName, platform, environment); + const managerPath = yield* resolveExecutable(managerName, environment); if (managerPath === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -1779,22 +1786,27 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const search: AcpRegistryCatalog["Service"]["search"] = Effect.fn("AcpRegistryCatalog.search")( function* (input) { const registry = yield* recentRegistry(); - const ranked = registry.agents.flatMap((agent) => { + const ranked = []; + const managerAvailability = new Map(); + for (const agent of registry.agents) { const distribution = resolveAcpRegistryDistribution({ agent, preference: "auto", platformTarget, }); const rank = searchRank(agent, input.query); - const packageManager = - distribution === undefined ? undefined : packageManagerFor(distribution.kind); - const packageManagerAvailable = - packageManager === undefined || - resolveExecutable(packageManager, platform, hostEnvironment) !== undefined; - return distribution === undefined || rank === undefined || !packageManagerAvailable - ? [] - : [{ agent, distribution, rank }]; - }); + if (distribution === undefined || rank === undefined) continue; + const packageManager = packageManagerFor(distribution.kind); + if (packageManager !== undefined) { + let available = managerAvailability.get(packageManager); + if (available === undefined) { + available = (yield* resolveExecutable(packageManager, hostEnvironment)) !== undefined; + managerAvailability.set(packageManager, available); + } + if (!available) continue; + } + ranked.push({ agent, distribution, rank }); + } ranked.sort( (left, right) => left.rank - right.rank || @@ -1865,7 +1877,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct if (settings.source === "local") { const command = settings.commandPath.trim(); if (!command) return { status: "unconfigured" } as const; - const executable = resolveExecutable(command, platform, environment ?? hostEnvironment); + const executable = yield* resolveExecutable(command, environment ?? hostEnvironment); if (executable !== undefined) yield* validateLocalExecutable(executable); return executable === undefined ? ({ @@ -1893,8 +1905,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { const available = - resolveExecutable(commandOverride, platform, environment ?? hostEnvironment) !== - undefined; + (yield* resolveExecutable(commandOverride, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1958,7 +1969,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const runner = packageManagerFor(distribution.kind)!; const available = - resolveExecutable(runner, platform, environment ?? hostEnvironment) !== undefined; + (yield* resolveExecutable(runner, environment ?? hostEnvironment)) !== undefined; return available ? ({ status: "ready", @@ -1999,7 +2010,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct const effectiveEnvironment = environment ?? hostEnvironment; const commandOverride = settings.commandPath.trim(); if (commandOverride.length > 0) { - const resolvedOverride = resolveExecutable(commandOverride, platform, effectiveEnvironment); + const resolvedOverride = yield* resolveExecutable(commandOverride, effectiveEnvironment); if (resolvedOverride === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", @@ -2066,7 +2077,7 @@ export const makeAcpRegistryCatalog = Effect.fn("AcpRegistryCatalog.make")(funct }); } const env = environment ?? hostEnvironment; - const command = resolveExecutable(executable, platform, env); + const command = yield* resolveExecutable(executable, env); if (command === undefined) { return yield* new AcpRegistryError({ reason: "runner_unavailable", diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 3a5ec9baba5fc..e882633974b86 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -86,6 +86,8 @@ export type AcpSessionRuntimeEvent = }; const defaultSessionLoadTimeout = Duration.seconds(90); +// A live child that never answers the handshake would otherwise hold the start open forever. +const startupRequestTimeout = Duration.seconds(90); const defaultSessionLoadReplayIdleGap = Duration.seconds(2); const defaultCancelTimeout = Duration.seconds(15); const maxStartupMetadataUpdates = 32; @@ -1400,6 +1402,25 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( Effect.andThen(runLoggedRequest(method, payload, effect)), ); + const withStartupTimeout = ( + method: string, + effect: Effect.Effect, + ): Effect.Effect => + effect.pipe( + Effect.timeoutOrElse({ + duration: startupRequestTimeout, + orElse: () => + Effect.fail( + new EffectAcpErrors.AcpTransportError({ + operation: "call-rpc", + method, + detail: `${method} timed out waiting for RPC response`, + cause: undefined, + }), + ), + }), + ); + const runLoggedRequest = ( method: string, payload: unknown, @@ -2299,7 +2320,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const initializeResult = yield* runLoggedRequest( "initialize", initializePayload, - acp.agent.initialize(initializePayload), + withStartupTimeout("initialize", acp.agent.initialize(initializePayload)), ); yield* options.onInitialized?.(initializeResult) ?? Effect.void; return initializeResult; @@ -2445,7 +2466,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( sessionSetupResult = yield* runLoggedRequest( "session/resume", resumePayload, - acp.agent.resumeSession(resumePayload), + withStartupTimeout("session/resume", acp.agent.resumeSession(resumePayload)), ); } else { return yield* new EffectAcpErrors.AcpRequestError({ @@ -2461,7 +2482,7 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const created = yield* runLoggedRequest( "session/new", createPayload, - acp.agent.createSession(createPayload), + withStartupTimeout("session/new", acp.agent.createSession(createPayload)), ); sessionId = created.sessionId; sessionSetupResult = created; @@ -3060,10 +3081,25 @@ const handleSessionUpdate = ); } const parsed = parseSessionUpdateEvent(params); - if (parsed.modeId) { + const modeId = parsed.modeId; + if (modeId) { yield* Ref.update(modeStateRef, (current) => - current === undefined ? current : updateModeState(current, parsed.modeId!), + current === undefined ? current : updateModeState(current, modeId), ); + // A mode-only update would otherwise leave the mode option showing the old mode. + const configOptions = yield* SubscriptionRef.get(configOptionsRef); + const isStaleMode = (option: (typeof configOptions)[number]) => + option.category === "mode" && option.type === "select" && option.currentValue !== modeId; + if (configOptions.some(isStaleMode)) { + yield* SubscriptionRef.set( + configOptionsRef, + configOptions.map((option) => + option.category === "mode" && option.type === "select" + ? { ...option, currentValue: modeId } + : option, + ), + ); + } } for (const event of parsed.events) { if (event._tag === "ToolCallUpdated") { diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 27788be8ba9f2..fc77627c796e9 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -637,6 +637,15 @@ export interface AcpAdapterV2Flavor { * tool ends. With `deferFinalizeForBackgroundWork`, the turn stays open until then. */ readonly toolOutlivesPrompt?: (toolCall: AcpToolCallState) => boolean; + /** + * Finalize a settled turn held only by running commands once the session has been silent for + * `timeout`, so a command that never reports back cannot leave the thread in Working forever. + * Other holds (questions, schedules, subagents) keep the turn open as before. + */ + readonly postSettleCommandHold?: { + readonly timeout: Duration.Input; + readonly isCommand: (toolCall: AcpToolCallState) => boolean; + }; readonly isProviderWakeNotification?: ( notification: EffectAcpSchema.SessionNotification, ) => boolean; @@ -2324,6 +2333,24 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }); const activeSelection = yield* Ref.make(null); const activeInteractionMode = yield* Ref.make(null); + // Mode values configureSession left the agent in; a later difference is the agent's own change. + const configuredModes = yield* Ref.make>(new Map()); + const readModes = Effect.gen(function* () { + const modes = new Map(); + for (const option of yield* runtime.getConfigOptions) { + if ( + option.type === "select" && + (option.category === "mode" || option.category === "collaboration_mode") + ) { + modes.set(option.id, option.currentValue); + } + } + const modeId = (yield* runtime.getModeState)?.currentModeId; + if (modeId !== undefined && !modes.has(ACP_SESSION_MODE_OPTION_ID)) { + modes.set(ACP_SESSION_MODE_OPTION_ID, modeId); + } + return modes; + }); const configuredRuntimeMode = yield* Ref.make< ProviderAdapter.ProviderAdapterV2RuntimePolicy["runtimeMode"] | null >(null); @@ -2743,7 +2770,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const notePromptProgress = /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (notification?: EffectAcpSchema.SessionNotification) { - if (promptInactivityTimeoutMillis === undefined) return; + if ( + promptInactivityTimeoutMillis === undefined && + flavor.postSettleCommandHold === undefined + ) { + return; + } if ( notification !== undefined && !ACP_PROMPT_ACTIVITY_UPDATES.has(notification.update.sessionUpdate) @@ -4275,11 +4307,15 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( const isMonitorEndNoticeText = (text: string): boolean => /Monitor\s+["']?[0-9a-f-]{8,}/i.test(text) && /ended/i.test(text); - const hasDeferredBackgroundWork = (context: ActiveAcpTurn): boolean => { + const hasDeferredBackgroundWork = ( + context: ActiveAcpTurn, + ignoreTool?: (tool: AcpToolCallState) => boolean, + ): boolean => { if (flavor.wakeOnDetachedRequest && agentRequests.size > 0) return true; if (flavor.toolOutlivesPrompt !== undefined) { // A tool that never started has nothing to report later. for (const tool of context.tools.values()) { + if (ignoreTool?.(tool) === true) continue; if (toolStatus(tool.status) === "running" && flavor.toolOutlivesPrompt(tool)) return true; } @@ -8376,6 +8412,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( } } yield* validateModelSelection(modelSelection); + yield* Ref.set(configuredModes, yield* readModes); yield* Ref.set(configuredRuntimeMode, runtimePolicy.runtimeMode); yield* ( flavor.onSessionConfigurationUpdate?.( @@ -8564,6 +8601,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); + // Re-applying the thread's mode would undo a deliberate exit, such as leaving plan mode once + // the plan was approved. Report it instead, so picking the old mode again is a real change. + const reportAgentModeChanges = Effect.fnUntraced(function* (threadId: ThreadId) { + const selection = yield* Ref.get(activeSelection); + if (selection === null || selection.options === undefined) return; + const configured = yield* Ref.get(configuredModes); + const live = yield* readModes; + const changes: Array<{ id: string; from: string; to: string }> = []; + const options = selection.options.map((option) => { + const value = live.get(option.id); + if ( + value === undefined || + typeof option.value !== "string" || + value === configured.get(option.id) || + value === option.value + ) { + return option; + } + changes.push({ id: option.id, from: option.value, to: value }); + return { ...option, value }; + }); + if (changes.length === 0) return; + yield* Ref.set(activeSelection, { ...selection, options }); + yield* Ref.set(configuredModes, live); + yield* emitProviderEvent({ + type: "thread_model_selection.updated", + driver, + threadId, + instanceId: selection.instanceId, + changes, + }); + }); + const finalizeTurn = Effect.fnUntraced(function* ( context: ActiveAcpTurn, status: "completed" | "interrupted" | "failed" | "cancelled", @@ -8659,6 +8729,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, }); } + yield* reportAgentModeChanges(context.input.threadId); const turn = providerTurnPayload(context, settledStatus, now); yield* Ref.update(providerTurns, (current) => { const updated = new Map(current); @@ -8801,6 +8872,39 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( yield* options.testHooks?.onDeferredFinalizeScheduled?.(debounce) ?? Effect.void; }); + const schedulePostSettleHoldExpiry = Effect.fn("AcpAdapterV2.schedulePostSettleHoldExpiry")( + function* (context: ActiveAcpTurn) { + const hold = flavor.postSettleCommandHold; + if (hold === undefined) return; + if (!context.promptSettled || context.finalized) return; + const timeoutMillis = Duration.toMillis(hold.timeout); + const isRunningCommand = (tool: AcpToolCallState) => + toolStatus(tool.status) === "running" && hold.isCommand(tool); + let quietSince = yield* Clock.currentTimeMillis; + // Armed even without a command yet: a pending reply can still start one. + yield* Effect.gen(function* () { + while (!context.finalized) { + quietSince = Math.max(quietSince, context.lastProgressAt); + const now = yield* Clock.currentTimeMillis; + const remaining = quietSince + timeoutMillis - now; + if (remaining > 0) { + yield* Effect.sleep(Duration.millis(remaining)); + continue; + } + if ( + context.tools.values().some(isRunningCommand) && + !hasDeferredBackgroundWork(context, isRunningCommand) + ) { + yield* finalizeTurn(context, context.promptSettledStatus ?? "completed"); + return; + } + // Something else still holds the turn; count silence again once it clears. + quietSince = now; + } + }).pipe(Effect.forkIn(sessionScope), Effect.asVoid); + }, + ); + const promptInactivityPaused = Effect.fn("AcpAdapterV2.promptInactivityPaused")(function* ( context: ActiveAcpTurn, ) { @@ -9231,6 +9335,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( if (context.finalized) return; if (deferredBackgroundWork || pendingReply) { yield* closeTextStreams(context); + yield* schedulePostSettleHoldExpiry(context); if (pendingReply) { context.replyOpen = true; yield* scheduleDeferredFinalize(context); @@ -9634,6 +9739,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( return; } if (!context.finalized) { + yield* schedulePostSettleHoldExpiry(context); if (hasDeferredBackgroundWork(context)) { yield* rearmDeferredFinalize(context); } else { diff --git a/packages/provider-acp/src/server/clientTerminals.ts b/packages/provider-acp/src/server/clientTerminals.ts index c8371fb7020e8..592bf47553494 100644 --- a/packages/provider-acp/src/server/clientTerminals.ts +++ b/packages/provider-acp/src/server/clientTerminals.ts @@ -263,7 +263,7 @@ export const makeAcpClientTerminals = Effect.fn("makeAcpClientTerminals")(functi // Agents that send shell source write bash; Node's shell on Windows is cmd.exe. const gitExecutable = isWindows && options.shellCommands === true - ? resolveExecutable("git", "win32", environment) + ? yield* Effect.promise(async () => resolveExecutable("git", "win32", environment)) : undefined; const posixShell = gitExecutable === undefined ? undefined : gitForWindowsBash(gitExecutable); diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.ts index 6998381e962a4..a5a2ec4405548 100644 --- a/packages/provider-core/src/server/ProviderAdapter.ts +++ b/packages/provider-core/src/server/ProviderAdapter.ts @@ -8,6 +8,7 @@ import { OrchestrationV2AppThread, OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, + OrchestrationV2PendingBackgroundTask, OrchestrationV2ProviderSession, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, @@ -119,6 +120,17 @@ export const ProviderAdapterV2Event = Schema.Union([ sessionScoped: Schema.optional(Schema.Boolean), retainedNativeTurnIds: Schema.optional(Schema.Array(Schema.String)), }), + /** The agent changed selected options itself, such as leaving plan mode once its plan ran. */ + Schema.Struct({ + type: Schema.Literal("thread_model_selection.updated"), + driver: ProviderDriverKind, + threadId: ThreadId, + instanceId: ProviderInstanceId, + /** Applies only where the thread still holds `from`, so newer user picks win. */ + changes: Schema.Array( + Schema.Struct({ id: Schema.String, from: Schema.String, to: Schema.String }), + ), + }), Schema.Struct({ type: Schema.Literal("provider_turn.updated"), driver: ProviderDriverKind, @@ -166,6 +178,14 @@ export const ProviderAdapterV2Event = Schema.Union([ providerTurnId: ProviderTurnId, pending: Schema.Boolean, }), + // The query process exited under a live session before this work reported back. + Schema.Struct({ + type: Schema.Literal("background_work.lost"), + driver: ProviderDriverKind, + threadId: ThreadId, + providerThreadId: ProviderThreadId, + tasks: Schema.Array(OrchestrationV2PendingBackgroundTask), + }), /** Unpersisted deltas go only to clients showing the row; final output arrives in turn_item.updated. */ Schema.Struct({ type: Schema.Literal("command_output.delta"), diff --git a/packages/provider-core/src/server/failure.test.ts b/packages/provider-core/src/server/failure.test.ts index 88c4f6bf37d55..ee2179f687205 100644 --- a/packages/provider-core/src/server/failure.test.ts +++ b/packages/provider-core/src/server/failure.test.ts @@ -132,6 +132,16 @@ it("preserves actionable T3 errors wrapped by turn startup", () => { }); assert.equal(makeProviderFailure({ cause: Cause.fail(cause) }).message, error.message); } + const unanswered = { + _tag: "CodexAppServerUnresponsiveError", + message: "Codex app-server did not answer turn/start within 2 minutes.", + }; + assert.equal( + makeProviderFailure({ + cause: Cause.fail({ _tag: "ProviderAdapterEventStreamError", cause: unanswered }), + }).message, + unanswered.message, + ); }); it("names how the provider process exited and the stage it failed in, without its output", () => { diff --git a/packages/provider-core/src/server/failure.ts b/packages/provider-core/src/server/failure.ts index c323600fe578a..981191621fa7d 100644 --- a/packages/provider-core/src/server/failure.ts +++ b/packages/provider-core/src/server/failure.ts @@ -146,6 +146,8 @@ function curatedCauseMessages(cause: unknown): { case "ClaudeConversationNotFoundError": case "CursorModelUnavailableError": case "CodexGoalObjectiveTooLongError": + case "CodexAppServerUnresponsiveError": + case "CodexAppServerRetiredError": case "ProviderSetupError": case "ProviderAdapterThreadInUseError": case "ProviderCompactionUnsupportedError": diff --git a/packages/provider-muse/src/server/MuseUsageHome.ts b/packages/provider-muse/src/server/MuseUsageHome.ts index 1ced0d2578b01..329dce90c0e7b 100644 --- a/packages/provider-muse/src/server/MuseUsageHome.ts +++ b/packages/provider-muse/src/server/MuseUsageHome.ts @@ -66,7 +66,11 @@ const make = Effect.gen(function* () { if (Option.isSome(settled)) return settled; // Spawn failures surface asynchronously; without this a missing CLI would report as pending. const resolveExecutable = yield* SpawnExecutableResolution; - if (resolveExecutable(binaryPath, yield* HostProcess.Platform, environment) === undefined) { + const platform = yield* HostProcess.Platform; + const resolved = yield* Effect.promise(async () => + resolveExecutable(binaryPath, platform, environment), + ); + if (resolved === undefined) { return Option.some(undefined); } if (awaitRefresh) return Option.some(yield* Cache.get(cache, key)); diff --git a/packages/provider-muse/src/server/sdk.test.ts b/packages/provider-muse/src/server/sdk.test.ts index ea882a25302f4..b9744cd5bbe16 100644 --- a/packages/provider-muse/src/server/sdk.test.ts +++ b/packages/provider-muse/src/server/sdk.test.ts @@ -263,7 +263,7 @@ describe("Muse launch", () => { const onWindows = (resolved: string | undefined, env: NodeJS.ProcessEnv = { ComSpec: CMD }) => museLaunch("muse", env).pipe( Effect.provideService(HostProcess.Platform, "win32"), - Effect.provideService(SpawnExecutableResolution, () => resolved), + Effect.provideService(SpawnExecutableResolution, async () => resolved), ); it.effect("runs an exe directly and a launcher script under cmd.exe on Windows", () => diff --git a/packages/provider-muse/src/server/sdk.ts b/packages/provider-muse/src/server/sdk.ts index 11de7e2d5e6d0..91f724a9d06cc 100644 --- a/packages/provider-muse/src/server/sdk.ts +++ b/packages/provider-muse/src/server/sdk.ts @@ -117,7 +117,8 @@ export const museLaunch = Effect.fn("museLaunch")(function* ( if ((yield* HostProcess.Platform) !== "win32") return { command: binaryPath, args: [] }; const env = environment ?? (yield* HostProcess.Environment); const resolveExecutable = yield* SpawnExecutableResolution; - const resolved = resolveExecutable(binaryPath, "win32", env) ?? binaryPath; + const resolved = + (yield* Effect.promise(async () => resolveExecutable(binaryPath, "win32", env))) ?? binaryPath; if (!/\.(?:cmd|bat)$/i.test(resolved)) return { command: resolved, args: [] }; const systemRoot = windowsEnvironmentValue(env, "SystemRoot"); return { diff --git a/packages/provider-muse/src/server/usage.test.ts b/packages/provider-muse/src/server/usage.test.ts index 322f10d2ac4c4..4e2d19b0b8913 100644 --- a/packages/provider-muse/src/server/usage.test.ts +++ b/packages/provider-muse/src/server/usage.test.ts @@ -264,7 +264,7 @@ describe("Muse history discovery", () => { expect(create).not.toHaveBeenCalled(); }).pipe( Effect.provide([NodeServices.layer, MuseUsageHome.layer]), - Effect.provideService(SpawnExecutableResolution, () => undefined), + Effect.provideService(SpawnExecutableResolution, async () => undefined), ), ); diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 5fd469cd3576c..968d152c111be 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -4908,7 +4908,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr if (commands.some((entry) => entry.name === command.name)) { // session.command neither accepts nor returns our ID; record the preceding history boundary. const newest = yield* client.message.list({ sessionID, order: "desc", limit: 1 }); - yield* markBefore(sessionId, newest.data[0]?.id ?? null); + const before = newest.data[0]?.id ?? null; + yield* markBefore(sessionId, before); if (!sending()) return; if (goalCommand?.type === "pause" || goalCommand?.type === "clear") { // OpenCode rejects pausing or clearing a missing goal; Codex treats that as a no-op. @@ -4921,7 +4922,44 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ); return yield* finishControl; } - return yield* client.session.command({ sessionID, ...command }).pipe(Effect.asVoid); + yield* client.session.command({ sessionID, ...command }); + // A command that never prompts the model starts no execution, so no event ends its turn. + const idle = () => state.active === turn && !busy.has(sessionId); + if (!idle()) return; + const active = yield* client.session + .active() + .pipe(Effect.timeout(ACTIVE_CHECK_TIMEOUT), Effect.option); + if (active._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command started."); + } + if (sessionId in active.value) return; + // An execution that already ended left history behind; its events may still trail this reply. + const ran = yield* OpenCode2Client.paginate( + { sessionID, order: "desc" as const, limit: 1 }, + client.message.list, + ).pipe( + Stream.takeWhile((message) => message.id !== before), + Stream.filter( + (message) => + message.type === "user" || message.type === "assistant" || message.type === "idle", + ), + Stream.runHead, + Effect.timeout(ACTIVE_CHECK_TIMEOUT), + Effect.option, + ); + if (ran._tag === "None") { + return yield* Effect.logWarning("Could not check whether an OpenCode command ran."); + } + if (ran.value._tag === "Some") return; + return yield* lock.withPermit( + Effect.suspend(() => + idle() + ? endExecution(state, turn, { + status: turn.interrupted ? "interrupted" : "completed", + }) + : Effect.void, + ), + ); } } const mentions = skillMentions(text); diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 019af2a98783f..b3e54117f02ee 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4159,6 +4159,62 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); + it.effect("reports cached input as a share of input in live and completed token usage", () => + Effect.gen(function* () { + const fake = yield* makeFakePi; + fake.queueState({ + sessionFile: FAKE_SESSION_FILE, + model: { provider: "anthropic", id: "large", contextWindow: 1_000_000 }, + }); + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + // Pi's message usage counts uncached input, cache reads and cache writes separately. + const usage = { input: 6, cacheRead: 40_101, cacheWrite: 10_561, output: 123 }; + // Session stats total every message in the session, not this turn. + fake.queueStats({ + tokens: { + input: 1_206, + cacheRead: 90_202, + cacheWrite: 60_622, + output: 250, + total: 152_280, + }, + contextUsage: { tokens: 50_791, contextWindow: 1_000_000 }, + }); + yield* fake.emit({ type: "response", command: "prompt", success: true }); + yield* fake.emit({ type: "agent_start" }); + yield* fake.emit({ type: "message_start", message: { role: "assistant" } }); + yield* fake.emit({ + type: "message_update", + usage: { ...usage, totalTokens: 50_791 }, + assistantMessageEvent: { type: "text_delta", contentIndex: 0, delta: "ok" }, + }); + const live = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.tokenUsage !== undefined, + ); + assert.deepInclude( + live.type === "provider_turn.updated" ? live.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + yield* fake.emit({ type: "agent_settled" }); + const completed = yield* takeEvent( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.status === "completed", + ); + assert.deepInclude( + completed.type === "provider_turn.updated" ? completed.providerTurn.tokenUsage : undefined, + { inputTokens: 50_668, cachedInputTokens: 40_101 }, + ); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect.each(["turn window", "full tree"] as const)( "finishes a turn whose %s has a parentId cycle", (cycleIn) => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index 5fb20184b8da2..26ff7118ff3b3 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -361,6 +361,11 @@ function compactionTitle(status: PiCompactionStatus): string { } } +type PiMessageTokenUsage = Pick< + OrchestrationV2ProviderTurnTokenUsage, + "inputTokens" | "cachedInputTokens" | "outputTokens" +>; + interface ActivePiTurn { readonly turnInput: ProviderAdapter.ProviderAdapterV2TurnInput; readonly providerTurn: OrchestrationV2ProviderTurn; @@ -379,6 +384,7 @@ interface ActivePiTurn { promptMayBeCommandOnly: boolean; latestCompactionAfterTokens: number | null; lastLiveUsedTokens: number | null; + lastMessageUsage: PiMessageTokenUsage | undefined; settleProbeGeneration: number; /** An extension may start compaction immediately after Pi emits agent_settled. */ settleWhenIdle: boolean; @@ -930,6 +936,25 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return value === undefined ? undefined : Math.max(0, Math.trunc(value)); }; + // Pi counts uncached input, cache reads and cache writes separately; input includes all three. + const piMessageTokenUsage = (usage: unknown): PiMessageTokenUsage => { + const uncachedInputTokens = nonNegativeInteger(usage, "input"); + const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); + const outputTokens = nonNegativeInteger(usage, "output"); + return { + ...(uncachedInputTokens === undefined + ? {} + : { + inputTokens: + uncachedInputTokens + + (cachedInputTokens ?? 0) + + (nonNegativeInteger(usage, "cacheWrite") ?? 0), + }), + ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), + ...(outputTokens === undefined ? {} : { outputTokens }), + }; + }; + const rememberModelContextWindow = (model: unknown): number | null => { const provider = recordString(model, "provider"); const id = recordString(model, "id"); @@ -1020,6 +1045,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( const tokenUsageFromStats = ( stats: unknown, fallbackUsedTokens: number | null, + messageUsage: PiMessageTokenUsage | undefined, updatedAt: DateTime.Utc, ): OrchestrationV2ProviderTurnTokenUsage | undefined => { const contextUsage = recordField(stats, "contextUsage"); @@ -1028,24 +1054,20 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( nonNegativeInteger(contextUsage, "tokens") ?? fallbackUsedTokens ?? undefined; if (usedTokens === undefined || maxTokens === undefined || maxTokens === 0) return undefined; - - const totals = recordField(stats, "tokens"); - const inputTokens = nonNegativeInteger(totals, "input"); - const cachedInputTokens = nonNegativeInteger(totals, "cacheRead"); - const outputTokens = nonNegativeInteger(totals, "output"); - return { - usedTokens, - maxTokens, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), - updatedAt: DateTime.formatIso(updatedAt), - }; + // Stats `tokens` are whole-session totals; the breakdown comes from the turn's last message. + return { usedTokens, maxTokens, ...messageUsage, updatedAt: DateTime.formatIso(updatedAt) }; }; - const readTokenUsage = (fallbackUsedTokens: number | null, updatedAt: DateTime.Utc) => + const readTokenUsage = (turn: ActivePiTurn, updatedAt: DateTime.Utc) => request({ type: "get_session_stats" }, 2_000).pipe( - Effect.map((stats) => tokenUsageFromStats(stats, fallbackUsedTokens, updatedAt)), + Effect.map((stats) => + tokenUsageFromStats( + stats, + turn.latestCompactionAfterTokens, + turn.lastMessageUsage, + updatedAt, + ), + ), Effect.orElseSucceed(() => undefined), ); @@ -1056,6 +1078,9 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( /* Provider events include streaming deltas; avoid a span for each update. */ Effect.fnUntraced(function* (turn: ActivePiTurn, usage: unknown) { const usedTokens = nonNegativeInteger(usage, "totalTokens"); + if (usedTokens !== undefined && usedTokens > 0) { + turn.lastMessageUsage = piMessageTokenUsage(usage); + } if ( usedTokens === undefined || usedTokens === 0 || @@ -1066,9 +1091,6 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( return; } turn.lastLiveUsedTokens = usedTokens; - const inputTokens = nonNegativeInteger(usage, "input"); - const cachedInputTokens = nonNegativeInteger(usage, "cacheRead"); - const outputTokens = nonNegativeInteger(usage, "output"); const updatedAt = yield* DateTime.now; yield* emit({ type: "provider_turn.updated", @@ -1079,9 +1101,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( tokenUsage: { usedTokens, maxTokens: contextWindow, - ...(inputTokens === undefined ? {} : { inputTokens }), - ...(cachedInputTokens === undefined ? {} : { cachedInputTokens }), - ...(outputTokens === undefined ? {} : { outputTokens }), + ...turn.lastMessageUsage, updatedAt: DateTime.formatIso(updatedAt), }, }, @@ -2101,9 +2121,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( } const treeRefs = turn.stopTreeRefs !== undefined ? turn.stopTreeRefs : yield* captureTurnTreeRefs(); - const tokenUsage = readUsage - ? yield* readTokenUsage(turn.latestCompactionAfterTokens, completedAt) - : undefined; + const tokenUsage = readUsage ? yield* readTokenUsage(turn, completedAt) : undefined; const failure = interrupted ? null : (turn.rejectedPromptFailure ?? turn.failure); yield* emit({ type: "provider_turn.updated", @@ -3502,6 +3520,7 @@ export const makePiAdapterV2 = Effect.fn("makePiAdapterV2")(function* ( compactCommand !== null || (payload?.message.trimStart().startsWith("/") ?? false), latestCompactionAfterTokens: null, lastLiveUsedTokens: null, + lastMessageUsage: undefined, settleProbeGeneration: 0, settleWhenIdle: false, compactionCancelled: false, diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.ts index 5317347aad13b..c8c17b84a9b7b 100644 --- a/packages/shared/src/composerInlineTokens.test.ts +++ b/packages/shared/src/composerInlineTokens.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { collectComposerInlineTokens as collectWithoutMath, type CollectComposerInlineTokensOptions, + composerFileLinksToPlainText, composerMathRanges, } from "./composerInlineTokens.ts"; import { markdownMathRanges } from "./markdownMath.ts"; @@ -230,3 +231,16 @@ describe("collectComposerInlineTokens", () => { ).toEqual(["$x_i$"]); }); }); + +describe("composerFileLinksToPlainText", () => { + it("shows file mentions by name and leaves other links as written", () => { + const mentions = ["src/foo.ts", ".gitignore", "pkg/__init__.py", "docs/My File (draft).md"] + .map(serializeComposerFileLink) + .join(" "); + expect(composerFileLinksToPlainText(`Review ${mentions}`)).toBe( + "Review foo.ts .gitignore __init__.py My File (draft).md", + ); + const links = "See [docs](https://example.com) and [the config](src/config.ts)"; + expect(composerFileLinksToPlainText(links)).toBe(links); + }); +}); diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.ts index b11a42b74a945..80a1b4d6916ae 100644 --- a/packages/shared/src/composerInlineTokens.ts +++ b/packages/shared/src/composerInlineTokens.ts @@ -1,3 +1,5 @@ +import { fileBasename } from "./path.ts"; + /** The formulas a Markdown parser finds in text, as source offsets. */ export type FindMathRanges = ( text: string, @@ -173,3 +175,16 @@ export function collectComposerInlineTokens( ) .sort((left, right) => left.start - right.start); } + +/** Shows each `@`-file link by its file name, as its composer chip does, for one-line previews. */ +export function composerFileLinksToPlainText(text: string): string { + let result = ""; + let cursor = 0; + // The composer reads a link as a mention only before whitespace, so one may end the text. + for (const token of collectMentionTokens(`${text} `)) { + if (!token.source.startsWith("[")) continue; + result += text.slice(cursor, token.start) + fileBasename(token.value); + cursor = token.end; + } + return result + text.slice(cursor); +} diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index a1f0af927636d..80204d903892b 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -174,6 +174,9 @@ describe("extractMarkdownLinkHrefs", () => { ["[".repeat(32_000), []], ["[a]( invalid [b](ok)", [" { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 50450a1e787de..e3458f04f3484 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -519,41 +519,36 @@ function markdownLinkDestinationScanner(markdown: string) { } } const hrefEnd = bareMarkdownLinkDestinationEnd(markdown, hrefStart); - if (hrefEnd === null || hrefEnd === hrefStart) return null; + if (hrefEnd === null) return null; const end = bareTail(hrefEnd); return end === null ? null : { hrefStart, hrefEnd, end }; }; } -// The composer escapes brackets in labels (`[\[id\].tsx](...)`), and `\]` does not close one. -function unescapedLabelEnd(markdown: string, start: number): number { - let end = markdown.indexOf("]", start); - while (end !== -1) { - let backslashes = 0; - while (end - backslashes > start && markdown[end - backslashes - 1] === "\\") backslashes += 1; - if (backslashes % 2 === 0) return end; - end = markdown.indexOf("]", end + 1); - } - return -1; -} - +// Labels may nest balanced brackets (`[the [docs] guide](...)`), and the composer escapes them +// (`[\[id\].tsx](...)`), so `\[` and `\]` never count. A blank line ends the paragraph and its labels. export function extractMarkdownLinkHrefs(markdown: string): string[] { const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - let cursor = 0; - while (cursor < markdown.length) { - const labelStart = markdown.indexOf("[", cursor); - if (labelStart === -1) break; - const labelEnd = unescapedLabelEnd(markdown, labelStart + 1); - if (labelEnd === -1) break; - - // Skip a failed label once; nested openings share its closing bracket. - cursor = labelEnd + 1; - const destination = scanDestination(cursor); - if (!destination) continue; - cursor = destination.end; - const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); - if (href) hrefs.push(href); + const bracket = /[[\]\\]|\n[ \t\r]*\n/g; + let openBrackets = 0; + for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { + if (match[0] === "\\") { + bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("\n")) { + openBrackets = 0; + } else if (match[0] === "[") { + openBrackets += 1; + } else if (openBrackets > 0) { + openBrackets -= 1; + const destination = scanDestination(match.index + 1); + if (!destination) continue; + // A link cannot contain a link, so the brackets still open around it become text. + openBrackets = 0; + bracket.lastIndex = destination.end; + const href = markdown.slice(destination.hrefStart, destination.hrefEnd).trim(); + if (href) hrefs.push(href); + } } return hrefs; } diff --git a/packages/shared/src/shell.test.ts b/packages/shared/src/shell.test.ts index d10551dabe569..07057520cb5c7 100644 --- a/packages/shared/src/shell.test.ts +++ b/packages/shared/src/shell.test.ts @@ -577,7 +577,9 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { ), ).toBe(path.join(directory, "audit-command")); const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("audit-command", "linux", env)).toBe(executable); + expect( + yield* Effect.promise(async () => resolveExecutable("audit-command", "linux", env)), + ).toBe(executable); }), ); @@ -736,7 +738,7 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { // A POSIX directory joined with win32 separators names nothing, so this needs a Windows host. it.effect.skipIf(HostProcess.Platform.defaultValue() !== "win32")( - "relists a changed PATH directory in the synchronous spawn resolver", + "relists a changed PATH directory in the spawn resolver", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; @@ -746,11 +748,17 @@ effectIt.layer(NodeServices.layer)("resolveCommandPath", (it) => { yield* fs.utimes(directory, 946_684_800, 946_684_800); const env = { PATH: directory, PATHEXT: ".EXE;.CMD" }; const resolveExecutable = yield* SpawnExecutableResolution; - expect(resolveExecutable("cursor", "win32", env)).toBe(path.join(directory, "cursor.CMD")); - expect(resolveExecutable("late", "win32", env)).toBeUndefined(); + expect(yield* Effect.promise(async () => resolveExecutable("cursor", "win32", env))).toBe( + path.join(directory, "cursor.CMD"), + ); + expect( + yield* Effect.promise(async () => resolveExecutable("late", "win32", env)), + ).toBeUndefined(); yield* fs.writeFileString(path.join(directory, "late.EXE"), ""); yield* fs.utimes(directory, 946_684_830, 946_684_830); - expect(resolveExecutable("late", "win32", env)).toBe(path.join(directory, "late.EXE")); + expect(yield* Effect.promise(async () => resolveExecutable("late", "win32", env))).toBe( + path.join(directory, "late.EXE"), + ); }), ); }); @@ -975,6 +983,73 @@ describe("npmShimExecutable", () => { }); effectIt.layer(NodeServices.layer)("resolveSpawnCommand", (it) => { + it.effect("yields while discovering a Windows executable", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const executable = path.join(directory, "tool.EXE"); + yield* fs.writeFileString(executable, ""); + let settled = false; + const pending = Promise.resolve( + SpawnExecutableResolution.defaultValue()(executable, "win32", { PATHEXT: ".EXE;.CMD" }), + ).then((value) => { + settled = true; + return value; + }); + try { + yield* Effect.promise(() => Promise.resolve()); + expect(settled).toBe(false); + } finally { + expect(yield* Effect.promise(() => pending)).toBe(executable); + } + }), + ), + ); + + it.effect("preserves PATH and PATHEXT order and discovers executables after a miss", () => + Effect.scoped( + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-spawn-" }); + const fixture = NodePath.join(directory, "tool.EXE"); + yield* fs.writeFileString(fixture, ""); + const stat = yield* Effect.promise(() => NodeFS.promises.stat(fixture)); + const files = new Set(); + using _stat = vi.spyOn(NodeFS.promises, "stat").mockImplementation(async (candidate) => { + if (!files.has(String(candidate))) throw new Error("not found"); + return stat; + }); + const lookup = resolveSpawnCommand("tool", ["status"], { + env: { PATH: "C:\\first;C:\\later", PATHEXT: ".EXE;.CMD" }, + }); + expect((yield* lookup).command).toBe("tool"); + files.add("C:\\first\\tool.CMD"); + files.add("C:\\first\\tool.EXE"); + files.add("C:\\later\\tool.EXE"); + expect(yield* lookup).toEqual({ + command: "C:\\first\\tool.EXE", + args: ["status"], + shell: false, + }); + files.delete("C:\\first\\tool.EXE"); + expect((yield* lookup).command).toBe("C:\\first\\tool.EXE"); + expect( + yield* Effect.promise(async () => + SpawnExecutableResolution.defaultValue()("tool", "win32", { + PATH: "C:\\first;C:\\later", + PATHEXT: ".EXE;.CMD", + }), + ), + ).toBe("C:\\first\\tool.CMD"); + }).pipe( + Effect.provideService(HostProcess.Platform, "win32"), + Effect.provideService(CommandResolutionCache, new Map()), + ), + ), + ); + it.effect("runs Windows executables directly without a shell", () => Effect.gen(function* () { const command = yield* resolveSpawnCommand("node.exe", ["script.js", "hello & goodbye"], { diff --git a/packages/shared/src/shell.ts b/packages/shared/src/shell.ts index ffcc1110fe381..0ba42dc3078d6 100644 --- a/packages/shared/src/shell.ts +++ b/packages/shared/src/shell.ts @@ -75,13 +75,13 @@ export type SpawnExecutableResolver = ( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -) => string | undefined; +) => string | undefined | Promise; -function resolveSpawnExecutableWithNode( +async function resolveSpawnExecutableWithNode( command: string, platform: NodeJS.Platform, env: NodeJS.ProcessEnv, -): string | undefined { +): Promise { const path = platform === "win32" ? NodePath.win32 : NodePath.posix; const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : []; const candidates = resolveCommandCandidates( @@ -90,20 +90,24 @@ function resolveSpawnExecutableWithNode( windowsPathExtensions, path.extname, ); - const isExecutable = (candidate: string) => { + const isExecutable = async (candidate: string) => { try { - if (!NodeFS.statSync(candidate).isFile()) return false; + if (!(await NodeFS.promises.stat(candidate)).isFile()) return false; if (platform === "win32") { return windowsPathExtensions.includes(path.extname(candidate).toUpperCase()); } - return canExecuteFile(candidate); + await NodeFS.promises.access(candidate, NodeFS.constants.X_OK); + return true; } catch { return false; } }; if (command.includes("/") || command.includes("\\")) { - return candidates.find(isExecutable); + for (const candidate of candidates) { + if (await isExecutable(candidate)) return candidate; + } + return undefined; } for (const pathEntry of (readEnvPath(env) ?? "").split(pathDelimiterForPlatform(platform))) { @@ -111,12 +115,12 @@ function resolveSpawnExecutableWithNode( if (normalizedPathEntry.length === 0) continue; const names = platform === "win32" - ? listPathDirectorySync(normalizedPathEntry, path.isAbsolute) + ? await listResolverPathDirectory(normalizedPathEntry, path.isAbsolute) : undefined; for (const candidate of candidates) { if (isAbsentFromListing(names, candidate)) continue; const candidatePath = path.join(normalizedPathEntry, candidate); - if (isExecutable(candidatePath)) return candidatePath; + if (await isExecutable(candidatePath)) return candidatePath; } } return undefined; @@ -661,42 +665,42 @@ export const PathDirectoryListings = Context.Reference( { defaultValue: () => Effect.runSync(makePathDirectoryListings) }, ); -const syncPathDirectoryListings = new Map< +const resolverPathDirectoryListings = new Map< string, { readonly modified: number; readonly names: ReadonlySet } >(); -// The synchronous resolver's counterpart of `PathDirectoryListings`, under the same rules. -function listPathDirectorySync( +// The spawn resolver's counterpart of `PathDirectoryListings`, under the same rules. +async function listResolverPathDirectory( directory: string, isAbsolute: (path: string) => boolean, -): ReadonlySet | undefined { +): Promise | undefined> { let modified: number; try { - const stats = NodeFS.statSync(directory); + const stats = await NodeFS.promises.stat(directory); if (!stats.isDirectory()) return undefined; modified = stats.mtimeMs; } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? NO_DIRECTORY_NAMES : undefined; } - const cached = syncPathDirectoryListings.get(directory); + const cached = resolverPathDirectoryListings.get(directory); if (cached?.modified === modified) return cached.names; - syncPathDirectoryListings.delete(directory); + resolverPathDirectoryListings.delete(directory); // This resolver runs outside Effect, so it has no Clock to read. // @effect-diagnostics-next-line globalDate:off const listedAtMs = Date.now(); let names: ReadonlySet; try { - names = new Set(NodeFS.readdirSync(directory).map((entry) => entry.toLowerCase())); + names = new Set((await NodeFS.promises.readdir(directory)).map((entry) => entry.toLowerCase())); } catch { return undefined; } if (isReusableListing(directory, modified, listedAtMs, isAbsolute)) { - if (syncPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { - const oldest = syncPathDirectoryListings.keys().next().value; - if (oldest !== undefined) syncPathDirectoryListings.delete(oldest); + if (resolverPathDirectoryListings.size >= PATH_DIRECTORY_LISTINGS_MAX_ENTRIES) { + const oldest = resolverPathDirectoryListings.keys().next().value; + if (oldest !== undefined) resolverPathDirectoryListings.delete(oldest); } - syncPathDirectoryListings.set(directory, { modified, names }); + resolverPathDirectoryListings.set(directory, { modified, names }); } return names; } @@ -1002,18 +1006,21 @@ const resolveMacosGit = Effect.fnUntraced(function* ( const nowNanos = yield* Clock.currentTimeNanos; const cached = cache.get(cacheKey); // An Xcode update or removal deletes the binary; look again instead of failing the spawn. - if ( - cached !== undefined && - cached.expiresAtNanos > nowNanos && - (cached.resolvedPath === null || - resolveExecutable(cached.resolvedPath, "darwin", env) !== undefined) - ) { - return cached.resolvedPath ?? "git"; + if (cached !== undefined && cached.expiresAtNanos > nowNanos) { + const cachedPath = cached.resolvedPath; + if ( + cachedPath === null || + (yield* Effect.promise(async () => resolveExecutable(cachedPath, "darwin", env))) !== + undefined + ) { + return cachedPath ?? "git"; + } } - const located = - resolveExecutable("git", "darwin", env) === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; + const onPath = yield* Effect.promise(async () => resolveExecutable("git", "darwin", env)); + const located = onPath === MACOS_GIT_SHIM ? locateXcodeGit(env) : undefined; const realGit = - located !== undefined && resolveExecutable(located, "darwin", env) !== undefined + located !== undefined && + (yield* Effect.promise(async () => resolveExecutable(located, "darwin", env))) !== undefined ? located : null; cacheCommandResolution(cache, cacheKey, realGit, nowNanos); @@ -1093,10 +1100,8 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( shell: false, }; } - // The scan is synchronous and runs before every child process, so it shares - // the PATH scan cache above. Explicit paths stay uncached for the same reason, - // and so do misses: a failed spawn is how providers report "not installed", - // and that has to clear the moment the binary appears. + // Cache successful PATH lookups. Explicit paths and misses stay uncached so + // newly installed executables are discoverable immediately. const explicitPath = command.includes("/") || command.includes("\\"); const cache = yield* CommandResolutionCache; const cacheKey = [ @@ -1114,7 +1119,7 @@ export const resolveSpawnCommand = Effect.fnUntraced(function* ( if (cached !== undefined && cached.expiresAtNanos > nowNanos) { resolvedExecutable = cached.resolvedPath; } else { - const found = resolveExecutable(command, platform, env); + const found = yield* Effect.promise(async () => resolveExecutable(command, platform, env)); resolvedExecutable = found === undefined ? null : preferGitForWindowsBinary(found, env); if (!explicitPath && resolvedExecutable !== null) { cacheCommandResolution(cache, cacheKey, resolvedExecutable, nowNanos); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts index 6e4600fe5a338..c71f1f36df2fb 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.test.ts @@ -414,7 +414,7 @@ describe("azureCliInvocation", () => { AzureDevOpsCli.azureCliInvocation().pipe( Effect.provideService(HostProcess.Platform, "win32"), Effect.provideService(HostProcess.Environment, { PATH: "C:\\tools" }), - Effect.provideService(SpawnExecutableResolution, () => launcher), + Effect.provideService(SpawnExecutableResolution, async () => launcher), Effect.provideService(AzureCliInstallLocation, () => install), ); diff --git a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts index 6cffe9ab0b3ab..f289e7406950f 100644 --- a/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts +++ b/packages/source-control-azure-devops/src/server/AzureDevOpsCli.ts @@ -495,7 +495,8 @@ export const azureCliInvocation = Effect.fn("AzureDevOpsCli.invocation")(functio return { command: "az", args: [] } satisfies AzureCliInvocation; } const resolveExecutable = yield* SpawnExecutableResolution; - const launcher = resolveExecutable("az", "win32", yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const launcher = yield* Effect.promise(async () => resolveExecutable("az", "win32", env)); const installFor = yield* AzureCliInstallLocation; const install = launcher === undefined ? undefined : installFor(launcher); // Unrecognized installs (pipx's Scripts\az.exe) keep the launcher and today's decode. diff --git a/packages/source-control-core/src/server/PullRequestProvider.ts b/packages/source-control-core/src/server/PullRequestProvider.ts index 33e48fdf90e57..8217163a8f619 100644 --- a/packages/source-control-core/src/server/PullRequestProvider.ts +++ b/packages/source-control-core/src/server/PullRequestProvider.ts @@ -41,6 +41,7 @@ import type { PullRequestPreview, PullRequestUpdateMethod, PullRequestViewerPermissions, + PullRequestVisibility, SourceControlProviderKind, } from "@t3tools/contracts"; import { SourceControlProviderKind as SourceControlProviderKindSchema } from "@t3tools/contracts"; @@ -118,6 +119,8 @@ export interface ProviderChangeRequest { readonly labels: ReadonlyArray; readonly reviewDecision?: PullRequestReviewDecision | null | undefined; readonly checksState?: PullRequestChecksState | null | undefined; + /** Absent where the host has no private change requests or names no visibility. */ + readonly visibility?: PullRequestVisibility; } export interface ProviderChangeRequestSummary { diff --git a/packages/source-control-core/src/server/SourceControlProvider.ts b/packages/source-control-core/src/server/SourceControlProvider.ts index 4a6e93ab74f45..ccf23f59b2258 100644 --- a/packages/source-control-core/src/server/SourceControlProvider.ts +++ b/packages/source-control-core/src/server/SourceControlProvider.ts @@ -173,6 +173,18 @@ export class SourceControlProvider extends Context.Service< }) => Effect.Effect; /** True when `createChangeRequest` opens the change request as a draft when asked. */ readonly createsDraftChangeRequests?: boolean; + /** + * The private companion of the checkout's repository, made when it has none. The branch of + * a private change request is pushed to `url` and never to the repository itself, which + * everyone can read. Absent on a host without private change requests. + */ + readonly privateChangeRequestRemote?: (input: { + readonly cwd: string; + readonly context?: SourceControlProviderContext; + }) => Effect.Effect< + { readonly url: string; readonly repository: string }, + SourceControlProviderError + >; readonly listChangeRequests: (input: { readonly cwd: string; readonly context?: SourceControlProviderContext; @@ -202,6 +214,8 @@ export class SourceControlProvider extends Context.Service< readonly bodyFile: string; /** Honored only by a provider with `createsDraftChangeRequests`. */ readonly draft?: boolean; + /** Asked only of a provider with `privateChangeRequestRemote`, which holds the head. */ + readonly private?: boolean; }) => Effect.Effect; readonly getRepositoryCloneUrls: (input: { readonly cwd: string; diff --git a/packages/source-control-core/src/server/discovery.ts b/packages/source-control-core/src/server/discovery.ts index 62ec94d7d67fe..0cc6654adf021 100644 --- a/packages/source-control-core/src/server/discovery.ts +++ b/packages/source-control-core/src/server/discovery.ts @@ -357,7 +357,8 @@ const unavailableInstallHint = Effect.fn("discovery.unavailableInstallHint")(fun return installHint; } const resolveExecutable = yield* SpawnExecutableResolution; - const path = resolveExecutable(executable, platform, yield* HostProcess.Environment); + const env = yield* HostProcess.Environment; + const path = yield* Effect.promise(async () => resolveExecutable(executable, platform, env)); const architecture = yield* HostProcess.Architecture; return `\`${path ?? executable}\` is built for another CPU architecture, so this ${architecture} machine cannot run it. Remove or replace it. ${installHint}`; }); diff --git a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts index c04145758f7b1..c944207d639ab 100644 --- a/packages/source-control-github/src/server/GitHubIssueTracker.test.ts +++ b/packages/source-control-github/src/server/GitHubIssueTracker.test.ts @@ -656,6 +656,15 @@ Redact secrets before uploading.`); ["referenced", "acme/web#50"], ["closed", null], ]); + // A cross-reference keeps what a surface needs to open its source, not only a label. + expect(issue.events.find((event) => event.kind === "referenced")).toMatchObject({ + reference: { + repository: "acme/web", + number: 50, + kind: "pull-request", + url: "https://github.com/acme/web/pull/50", + }, + }); }), ); }); diff --git a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts index 902b2525ea1b9..798a1307ae3e7 100644 --- a/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts +++ b/packages/source-control-github/src/server/GitHubPullRequestApi.test.ts @@ -4046,7 +4046,12 @@ layer("GitHubPullRequestApi.layer", (it) => { status: "COMPLETED", conclusion: "SUCCESS", checkSuite: { - workflowRun: { runAttempt: 1, workflow: { name: "linux" } }, + workflowRun: { + runAttempt: 1, + event: "push", + runNumber: 1, + workflow: { id: "W_linux", name: "linux" }, + }, }, }), checkRun({ @@ -4055,7 +4060,12 @@ layer("GitHubPullRequestApi.layer", (it) => { status: "COMPLETED", conclusion: "FAILURE", checkSuite: { - workflowRun: { runAttempt: 1, workflow: { name: "windows" } }, + workflowRun: { + runAttempt: 1, + event: "push", + runNumber: 1, + workflow: { id: "W_windows", name: "windows" }, + }, }, }), ], diff --git a/packages/source-control-github/src/server/gitHubIssueJson.ts b/packages/source-control-github/src/server/gitHubIssueJson.ts index e46ad7ec9e515..59e9b9efd118e 100644 --- a/packages/source-control-github/src/server/gitHubIssueJson.ts +++ b/packages/source-control-github/src/server/gitHubIssueJson.ts @@ -5,7 +5,6 @@ import type { IssueActor, IssueComment, IssueEvent, - IssueEventKind, IssueLabel, IssueLinkedPullRequest, IssueState, @@ -137,7 +136,7 @@ function toLinkedPullRequest( /** The change GitHub recorded, or null for a kind this page has no vocabulary for. */ function toEventFields( raw: TimelineItem, -): { readonly kind: IssueEventKind; readonly detail: string | null } | null { +): Pick | null { switch (raw.__typename) { case "ClosedEvent": return { kind: "closed", detail: null }; @@ -164,15 +163,28 @@ function toEventFields( case "RenamedTitleEvent": return { kind: "renamed", detail: trimmed(raw.currentTitle) }; case "CrossReferencedEvent": { - const repository = trimmed( - raw.source != null && "repository" in raw.source - ? raw.source.repository.nameWithOwner - : null, - ); - const number = raw.source != null && "number" in raw.source ? raw.source.number : 0; + const source = + raw.source.__typename === "PullRequest" || raw.source.__typename === "Issue" + ? raw.source + : null; + const repository = trimmed(source?.repository.nameWithOwner); + const url = trimmed(source?.url); + if (source === null || repository === null || source.number <= 0) { + return { kind: "referenced", detail: null }; + } return { kind: "referenced", - detail: repository === null || number <= 0 ? null : `${repository}#${number}`, + detail: `${repository}#${source.number}`, + ...(url === null + ? {} + : { + reference: { + repository, + number: source.number, + kind: source.__typename === "PullRequest" ? "pull-request" : "issue", + url, + }, + }), }; } default: diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts index 936056777d7ab..c257207891c0d 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.test.ts @@ -362,10 +362,23 @@ describe("pull request detail decoding", () => { checkSuite: { workflowRun: null }, ...fields, }; - const inWorkflow = ({ workflowName, ...fields }: Record) => + const inWorkflow = ({ + workflowName, + workflowId = `W_kwDORLtfbc4${String(workflowName)}`, + event = "pull_request", + runNumber = 95380, + ...fields + }: Record) => check({ ...fields, - checkSuite: { workflowRun: { runAttempt: 1, workflow: { name: workflowName } } }, + checkSuite: { + workflowRun: { + runAttempt: 1, + event, + runNumber, + workflow: { id: workflowId, name: workflowName }, + }, + }, }); const coreJson = ( @@ -677,6 +690,139 @@ describe("pull request detail decoding", () => { } }); + it("drops a cancelled check whose workflow run was superseded by a newer run on the head", () => { + const superseded = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + status: "COMPLETED", + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:00:05Z", + }; + const replacement = { + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95380, + status: "COMPLETED", + conclusion: "SUCCESS", + startedAt: "2026-10-30T10:00:10Z", + completedAt: "2026-10-30T10:05:00Z", + }; + const rollup = [ + inWorkflow({ ...superseded, name: "check", conclusion: "CANCELLED" }), + inWorkflow({ + ...superseded, + name: "web browser tests (runner ${{ matrix.slice }} of 6)", + conclusion: "CANCELLED", + }), + inWorkflow({ ...replacement, name: "check" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 1 of 6)" }), + inWorkflow({ ...replacement, name: "web browser tests (runner 2 of 6)" }), + ]; + const detail = detailOf(rollup); + + expect([detail.checks.map((check) => [check.name, check.status]), detail.checksState]).toEqual([ + [ + ["check", "success"], + ["web browser tests (runner 1 of 6)", "success"], + ["web browser tests (runner 2 of 6)", "success"], + ], + "passing", + ]); + }); + + it("keeps a cancelled check when the newer run is another workflow with the same name", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4N00ni", + runNumber: 95379, + conclusion: "CANCELLED", + }), + inWorkflow({ + name: "lint", + workflowName: "CI", + workflowId: "W_kwDORLtfbc4ToKTh", + runNumber: 95380, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test", + "cancelled", + ]); + expect(detail.checksState).toBe("failing"); + }); + + it("drops a required cancelled check once a newer run reports it, whenever it finished", () => { + const detail = detailOf([ + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 41, + conclusion: "CANCELLED", + isRequired: true, + startedAt: "2026-10-30T10:00:00Z", + completedAt: "2026-10-30T10:09:00Z", + }), + inWorkflow({ + name: "test", + workflowName: "CI", + runNumber: 42, + conclusion: "SUCCESS", + isRequired: true, + startedAt: "2026-10-30T10:01:00Z", + completedAt: "2026-10-30T10:05:00Z", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toEqual([["test", "success"]]); + expect(detail.checksState).toBe("passing"); + }); + + it.each([ + ["a push", "push", "push", "CANCELLED", false, "cancelled"], + ["another event", "pull_request", "pull_request_target", "CANCELLED", false, "cancelled"], + ["a pull request run", "pull_request", "pull_request", "FAILURE", false, "failure"], + [ + "a pull request run, if required", + "pull_request", + "pull_request", + "CANCELLED", + true, + "cancelled", + ], + ])( + "keeps an older run's check when the newer run is %s", + (_label, olderEvent, newerEvent, conclusion, isRequired, status) => { + const detail = detailOf([ + inWorkflow({ + name: "test (packages/shared)", + workflowName: "CI", + event: olderEvent, + runNumber: 41, + conclusion, + isRequired, + }), + inWorkflow({ + name: "test (apps/server)", + workflowName: "CI", + event: newerEvent, + runNumber: 42, + conclusion: "SUCCESS", + }), + ]); + + expect(detail.checks.map((check) => [check.name, check.status])).toContainEqual([ + "test (packages/shared)", + status, + ]); + expect(detail.checksState).toBe("failing"); + }, + ); + it("merges reviews with comments in time order and keeps a bodyless approval", () => { const detail = expectSuccess(activity(JSON.parse(detailJson) as Record)); expect(detail.comments.map((comment) => comment.id)).toEqual(["r1", "c1", "r2"]); diff --git a/packages/source-control-github/src/server/gitHubPullRequestJson.ts b/packages/source-control-github/src/server/gitHubPullRequestJson.ts index 32d72a9e8aa46..ad4486faf8522 100644 --- a/packages/source-control-github/src/server/gitHubPullRequestJson.ts +++ b/packages/source-control-github/src/server/gitHubPullRequestJson.ts @@ -131,6 +131,13 @@ interface LatestReviewFields { readonly isMinimized?: boolean | undefined; } +/** Run numbers count up per workflow file, whatever its name; database ids exceed int32. */ +interface WorkflowRunFields { + readonly event: string; + readonly runNumber: number; + readonly workflow: { readonly id: string }; +} + /** Check runs use status/conclusion; commit statuses use a single state. */ interface CheckFields { readonly databaseId?: number | null | undefined; @@ -146,6 +153,8 @@ interface CheckFields { readonly targetUrl?: string | null | undefined; /** Empty for app-owned runs; absent for commit statuses. */ readonly workflowName?: string | null | undefined; + /** Absent for commit statuses and app-owned runs. */ + readonly workflowRun?: WorkflowRunFields | null | undefined; readonly startedAt?: string | null | undefined; readonly completedAt?: string | null | undefined; /** Branch protection requires this check; asked for on github.com only. */ @@ -620,16 +629,42 @@ function isNamelessCheck(raw: CheckFields): boolean { return trimmed(raw.name) === null && trimmed(raw.context) === null; } -/** Unfinished runs outrank finished runs of the same check across push/PR workflows. */ +const PULL_REQUEST_EVENTS = new Set(["pull_request", "pull_request_target"]); + +/** + * Unfinished runs outrank finished runs of the same check across push/PR workflows. A newer pull + * request run of a workflow supersedes the older one's cancelled checks, whose names can differ + * (an unexpanded matrix). Other events can run one commit in different scopes (a branch and a + * tag, dispatch inputs), so their runs replace nothing. + */ function toCheckEntries(raw: ReadonlyArray | null | undefined): ReadonlyArray<{ readonly check: PullRequestCheck; readonly workflowName: string | null; readonly at: string | null; }> { + const lineageOf = (run: WorkflowRunFields) => `${run.workflow.id} ${run.event}`; + const newestRunNumber = new Map(); + const note = (key: string, runNumber: number) => { + if (runNumber > (newestRunNumber.get(key) ?? Number.NEGATIVE_INFINITY)) { + newestRunNumber.set(key, runNumber); + } + }; + for (const check of raw ?? []) { + const run = check.workflowRun; + if (run == null || !PULL_REQUEST_EVENTS.has(run.event)) continue; + note(lineageOf(run), run.runNumber); + note(`${lineageOf(run)} ${trimmed(check.name) ?? ""}`, run.runNumber); + } return (raw ?? []).flatMap((check) => { const name = trimmed(check.name) ?? trimmed(check.context); if (name === null) return []; const status = toCheckStatus(check); + const run = check.workflowRun; + if (status === "cancelled" && run != null) { + // Branch protection names required checks, so only a newer same-name check replaces one. + const replacedBy = check.isRequired === true ? `${lineageOf(run)} ${name}` : lineageOf(run); + if (run.runNumber < (newestRunNumber.get(replacedBy) ?? run.runNumber)) return []; + } return [ { check: { @@ -1259,6 +1294,7 @@ function toCheckContexts(nodes: ReadonlyArray): ReadonlyArray {} export const WorkflowRun = Schema.Struct({ /** The attempt number of this workflow run. */ runAttempt: Shared.Int, + /** The event that triggered the workflow run */ + event: Schema.String, + /** A number that uniquely identifies this workflow run in its parent workflow. */ + runNumber: Shared.Int, /** The workflow executed in this workflow run. */ workflow: Workflow }) @@ -571,7 +577,7 @@ export const PullRequestCore = GraphQL.query("PullRequestCore", { { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){mergeCommitAllowed squashMergeAllowed rebaseMergeAllowed autoMergeAllowed viewerPermission pullRequest(number:$", "number", "){number title url body state isDraft mergeable mergeStateStatus reviewDecision additions deletions changedFiles createdAt updatedAt mergedAt mergeCommit{oid}mergedBy{__typename login avatarUrl...on User{name}}closedAt headRefName baseRefName headRefOid isCrossRepository maintainerCanModify headRepositoryOwner{__typename login}headRepository{nameWithOwner viewerPermission}headRef{id}author{__typename login avatarUrl...on User{id name}}autoMergeRequest{mergeMethod}mergeQueueRemovals:timelineItems(last:1 itemTypes:[REMOVED_FROM_MERGE_QUEUE_EVENT])@include(if:$", "mergeQueue", "){nodes{__typename...on RemovedFromMergeQueueEvent{id createdAt reason}}}viewerCanUpdate viewerDidAuthor viewerCanUpdateBranch baseRef{compare(headRef:$", "headRef", "){behindBy}}reviewRequests(first:$", "requestedReviewers", "){nodes{requestedReviewer{__typename...on User{login name}...on Bot{login}...on Team{slug combinedSlug teamName:name teamAvatarUrl:avatarUrl}}}}labels(first:100){nodes{name color description}}commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{databaseId title name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{runAttempt workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{databaseId title name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{runAttempt event runNumber workflow{id name}}}}}"] } ] }, variables: { @@ -631,7 +637,7 @@ export const PullRequestCheckContexts = GraphQL.query("PullRequestCheckContexts" { name: "repository", body: ["(owner:$", "owner", " name:$", "name", "){pullRequest(number:$", "number", "){state isCrossRepository headRefName headRepositoryOwner{__typename login}headRefOid commits(last:1){nodes{commit{statusCheckRollup{contexts(first:100 after:$", "after", "){nodes{__typename...", "CheckContext", "}pageInfo{hasNextPage endCursor}}}}}}}}"] } ], fragments: [ - { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{databaseId title name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{runAttempt workflow{name}}}}}"] } + { name: "CheckContext", body: ["on StatusCheckRollupContext{__typename...on StatusContext{context state targetUrl createdAt description isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")}...on CheckRun{databaseId title name status conclusion startedAt completedAt detailsUrl isRequired(pullRequestNumber:$", "number", ")@include(if:$", "required", ")checkSuite{workflowRun{runAttempt event runNumber workflow{id name}}}}}"] } ] }, variables: { diff --git a/packages/source-control-gitlab/src/server/GitLabCli.ts b/packages/source-control-gitlab/src/server/GitLabCli.ts index b528c1ced5a8a..04a633bba7096 100644 --- a/packages/source-control-gitlab/src/server/GitLabCli.ts +++ b/packages/source-control-gitlab/src/server/GitLabCli.ts @@ -21,6 +21,8 @@ import * as SourceControlHost from "@t3tools/source-control-core/server/SourceCo import { decodeGitLabMergeRequestJson, decodeGitLabMergeRequestListJson, + type NormalizedGitLabMergeRequestRecord, + withSourceProjectPath, } from "./gitLabMergeRequests.ts"; import type * as SourceControlProvider from "@t3tools/source-control-core/server/SourceControlProvider"; @@ -377,6 +379,10 @@ const decodeGitLabMergeRequestProject = Schema.decodeEffect( Schema.fromJsonString(Schema.Struct({ id: Schema.Number, path: TrimmedNonEmptyString })), ); +const decodeGitLabProjectPath = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ path_with_namespace: TrimmedNonEmptyString })), +); + const RawGitLabNamespaceSchema = Schema.Struct({ id: Schema.Number, }); @@ -559,6 +565,35 @@ export const make = Effect.gen(function* () { ), ); + // glab's MR JSON names a fork's source project only by `source_project_id`. + const resolveSourceProjectPaths = Effect.fn("GitLabCli.resolveSourceProjectPaths")(function* ( + cwd: string, + records: ReadonlyArray, + paths: Map, + ) { + const ids = new Set(); + for (const record of records) { + const id = record.unresolvedSourceProjectId; + if (id !== undefined && !paths.has(id)) ids.add(id); + } + yield* Effect.forEach( + ids, + (id) => + execute({ cwd, args: ["api", `projects/${id}`] }).pipe( + Effect.flatMap((result) => decodeGitLabProjectPath(result.stdout.trim())), + Effect.map((project) => project.path_with_namespace), + Effect.orElseSucceed(() => null), + Effect.map((path) => void paths.set(id, path)), + ), + { concurrency: 8, discard: true }, + ); + return records.map((record) => + record.unresolvedSourceProjectId === undefined + ? record + : withSourceProjectPath(record, paths.get(record.unresolvedSourceProjectId) ?? null), + ); + }); + return GitLabCli.of({ execute, listMergeRequests: Effect.fn("GitLabCli.listMergeRequests")(function* (input) { @@ -566,6 +601,7 @@ export const make = Effect.gen(function* () { let pageSize = limit; let page = 1; const items: GitLabMergeRequestSummary[] = []; + const sourceProjectPaths = input.source?.owner ? new Map() : null; while (items.length < limit) { const result = yield* execute({ cwd: input.cwd, @@ -600,7 +636,11 @@ export const make = Effect.gen(function* () { cause: Result.isFailure(decoded) ? decoded.failure : "MR list output was truncated", }); } - items.push(...decoded.success.map(toSummaryWithOptionalUpdatedAt)); + // Only a fork head can match a fork's merge request, so other lookups skip the API calls. + const records = sourceProjectPaths + ? yield* resolveSourceProjectPaths(input.cwd, decoded.success, sourceProjectPaths) + : decoded.success; + items.push(...records.map(toSummaryWithOptionalUpdatedAt)); // Count raw entries: the decoder drops invalid ones, which would end paging early. const entries = decodeJsonArray(raw); if ( @@ -635,7 +675,9 @@ export const make = Effect.gen(function* () { ); } - return Effect.succeed(toSummaryWithOptionalUpdatedAt(decoded.success)); + return resolveSourceProjectPaths(input.cwd, [decoded.success], new Map()).pipe( + Effect.map(([record]) => toSummaryWithOptionalUpdatedAt(record!)), + ); }), ), ), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts index 7c794de8b456e..d3bd6e01366bd 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.test.ts @@ -59,6 +59,13 @@ function answer(path: string): string { created_at: "2026-07-03T00:00:00Z", system: true, }, + { + id: 10, + body: "mentioned in merge request api!51", + author: { username: "theo" }, + created_at: "2026-07-04T00:00:00Z", + system: true, + }, ]); } if (path.startsWith("projects/acme%2Fweb/issues/42/resource_label_events")) { @@ -206,7 +213,14 @@ describe("GitLabIssueTracker", () => { expect(issue.events.map((event) => [event.kind, event.detail])).toEqual([ ["labeled", "bug"], ["closed", null], + ["referenced", "merge request api!51"], ]); + expect(issue.events.at(-1)?.reference).toEqual({ + repository: "acme/api", + number: 51, + kind: "pull-request", + url: "https://gitlab.com/acme/api/-/merge_requests/51", + }); // A closing merge request is not repeated as a related one. expect( issue.linkedPullRequests.map((link) => [link.number, link.closesIssue, link.isDraft]), diff --git a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts index f8b1f80c18b0e..4f4aeb3135034 100644 --- a/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts +++ b/packages/source-control-gitlab/src/server/GitLabIssueTracker.ts @@ -25,6 +25,7 @@ import { decodeIssueDetailListJson, decodeIssueListJson, decodeIssueNotesJson, + withMentionReference, decodeLabelEventsJson, decodeLinkedMergeRequestsJson, decodeProjectLabelsJson, @@ -576,9 +577,12 @@ export const make: Effect.Effect = reactions: awardPage?.reactionsByNoteId.get(comment.id) ?? [], })), commentsCursor: commentsCursor(notes.nextCursor, awardPage?.nextCursor ?? null), - events: [...systemEvents, ...labelEvents].sort((left, right) => - left.createdAt.localeCompare(right.createdAt), - ), + events: [ + ...systemEvents.map((event) => + withMentionReference(event, issue.url, input.scope), + ), + ...labelEvents, + ].sort((left, right) => left.createdAt.localeCompare(right.createdAt)), // A merge request that closes the issue outranks its sighting as a mere mention. linkedPullRequests: [ ...closing, diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts index 7038e6a82d630..abd2f7b82f218 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.git.test.ts @@ -106,6 +106,97 @@ it.effect("lists a nested-group fork's merge requests by source branch and names }), ); +// Real `glab mr list --output json` marshals client-go's BasicMergeRequest: a fork MR names its +// source project only by `source_project_id`, never by a `source_project` path. +it.effect("names a fork merge request's source project from real glab list output", () => + Effect.gen(function* () { + const branch = "feature/fork-work"; + const mergeRequest = (iid: number, sourceProjectId: number) => ({ + id: 9000 + iid, + iid, + project_id: 100, + title: `Work ${iid}`, + state: "opened", + target_branch: "main", + source_branch: branch, + source_project_id: sourceProjectId, + target_project_id: 100, + draft: false, + sha: "0123456789abcdef0123456789abcdef01234567", + updated_at: "2026-04-07T15:00:00.000Z", + references: { short: `!${iid}`, relative: `!${iid}`, full: `group/upstream!${iid}` }, + web_url: `https://gitlab.com/group/upstream/-/merge_requests/${iid}`, + }); + const output = JSON.stringify([ + mergeRequest(1, 101), + mergeRequest(2, 101), + mergeRequest(3, 100), + mergeRequest(4, 102), + ]); + const apiCalls: ReadonlyArray[] = []; + const provider = yield* GitLabSourceControlProvider.make.pipe( + Effect.provide( + GitLabCli.layer.pipe( + Layer.provideMerge( + TestSourceControlHost.layer({ + process: { + run: (input) => + Effect.sync(() => { + if (input.args[0] !== "api") return TestSourceControlHost.processOutput(output); + apiCalls.push(input.args); + return TestSourceControlHost.processOutput( + input.args[1] === "projects/101" + ? JSON.stringify({ id: 101, path_with_namespace: "alice/upstream" }) + : "not json", + ); + }), + }, + }), + ), + Layer.provide(FileSystem.layerNoop({})), + ), + ), + ); + + const upstreamHead = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: branch, + state: "open", + limit: 20, + }); + expect(upstreamHead[0]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toEqual([]); + + const changeRequests = yield* provider.listChangeRequests({ + cwd: "/repo", + headSelector: `alice:${branch}`, + state: "open", + limit: 20, + }); + // GitManager drops a cross-repository MR whose head project is unnamed. + expect(changeRequests).toMatchObject([ + { + number: 1, + isCrossRepository: true, + headRepositoryNameWithOwner: "alice/upstream", + headRepositoryOwnerLogin: "alice", + }, + { number: 2, isCrossRepository: true, headRepositoryNameWithOwner: "alice/upstream" }, + { number: 3, isCrossRepository: false }, + { number: 4, isCrossRepository: true }, + ]); + expect(changeRequests[2]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(changeRequests[3]).not.toHaveProperty("headRepositoryNameWithOwner"); + expect(apiCalls).toHaveLength(2); + expect(apiCalls).toEqual( + expect.arrayContaining([ + ["api", "projects/101"], + ["api", "projects/102"], + ]), + ); + }), +); + const withRepository = ( test: (input: { readonly git: (...args: string[]) => Effect.Effect; diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts index 8e5077044c6b3..c5a2d56037172 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.test.ts @@ -210,6 +210,13 @@ it.effect( headSelectors: ["octocat:feature", "feature"], state: "open", }), + { headSelectors: ["octocat:feature"], limit: 100 }, + ); + assert.deepStrictEqual( + provider.headBranchProbe?.({ + headSelectors: ["feature", "octocat:feature"], + state: "open", + }), { headSelectors: ["feature"], limit: 100 }, ); }), diff --git a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts index a7d5b71ca47d3..2a2d4ac3e199c 100644 --- a/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts +++ b/packages/source-control-gitlab/src/server/GitLabSourceControlProvider.ts @@ -211,11 +211,17 @@ export const make = Effect.gen(function* () { return SourceControlProvider.SourceControlProvider.of({ kind: SourceControlProviderKind.make("gitlab"), - // GitLab lists fork merge requests by source branch with no owner filter, so read a full page. - headBranchProbe: ({ headSelectors }) => ({ - headSelectors: headSelectors.filter((selector) => !selector.includes(":")), - limit: 100, - }), + // GitLab lists fork merge requests by source branch with no owner filter, so read a full page + // once per branch. The first selector wins: GitManager puts `owner:branch` first for a fork + // head, which tells the list to name fork source projects. + headBranchProbe: ({ headSelectors }) => { + const byBranch = new Map(); + for (const selector of headSelectors) { + const branch = SourceControlProvider.sourceBranch({ headSelector: selector }); + if (!byBranch.has(branch)) byBranch.set(branch, selector); + } + return { headSelectors: [...byBranch.values()], limit: 100 }; + }, readChangeRequestTemplate: Effect.fn("GitLabSourceControlProvider.readChangeRequestTemplate")( function ({ cwd, treeish }) { return GitLabChangeRequestTemplate.detect(cwd, treeish, git.execute); diff --git a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts index 5458ed4f859ef..7a52667a4a425 100644 --- a/packages/source-control-gitlab/src/server/gitLabIssueJson.ts +++ b/packages/source-control-gitlab/src/server/gitLabIssueJson.ts @@ -250,6 +250,41 @@ function toSystemEvent( return null; } +// The path class excludes the sigil, so matching is linear on any input. +const MENTION = /^(?:merge request ([\w.\-/]*)!|issue ([\w.\-/]*)#)([1-9]\d*)$/; + +/** + * Where a "mentioned in merge request !12" note came from, addressed from the issue's own web URL + * so a self-managed host under a subpath resolves. A commit, epic or snippet mention gets none. + */ +export function withMentionReference( + event: IssueEvent, + issueUrl: string, + scope: string, +): IssueEvent { + const match = event.kind === "referenced" ? MENTION.exec(event.detail ?? "") : null; + const projectUrl = issueUrl.split("/-/")[0]!; + if (match === null || !projectUrl.toLowerCase().endsWith(`/${scope.toLowerCase()}`)) { + return event; + } + const [, mergeRequestPath, issuePath, digits] = match; + const isMergeRequest = mergeRequestPath !== undefined; + const path = mergeRequestPath ?? issuePath ?? ""; + // A project in the same namespace is named by its path alone. + const repository = + path === "" ? scope : path.includes("/") ? path : `${scope.replace(/[^/]*$/, "")}${path}`; + const base = projectUrl.slice(0, projectUrl.length - scope.length); + return { + ...event, + reference: { + repository, + number: Number(digits), + kind: isMergeRequest ? "pull-request" : "issue", + url: `${base}${repository}/-/${isMergeRequest ? "merge_requests" : "issues"}/${digits}`, + }, + }; +} + interface GitLabIssueNotes { readonly comments: ReadonlyArray; readonly events: ReadonlyArray; diff --git a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts index ef4438f5ff3ee..a40abd786cf85 100644 --- a/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts +++ b/packages/source-control-gitlab/src/server/gitLabMergeRequests.ts @@ -23,6 +23,8 @@ export interface NormalizedGitLabMergeRequestRecord { readonly isCrossRepository?: boolean; readonly headRepositoryNameWithOwner?: string | null; readonly headRepositoryOwnerLogin?: string | null; + /** Set when a cross-repository MR names its source project only by id. */ + readonly unresolvedSourceProjectId?: number; } const GitLabProjectReferenceSchema = Schema.Struct({ @@ -122,6 +124,24 @@ function normalizeGitLabMergeRequestRecord( ...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}), ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), + ...(isCrossRepository === true && + !sourceProjectPath && + typeof raw.source_project_id === "number" + ? { unresolvedSourceProjectId: raw.source_project_id } + : {}), + }; +} + +export function withSourceProjectPath( + record: NormalizedGitLabMergeRequestRecord, + sourceProjectPath: string | null, +): NormalizedGitLabMergeRequestRecord { + const { unresolvedSourceProjectId: _, ...resolved } = record; + const headRepositoryOwnerLogin = ownerLoginFromPathWithNamespace(sourceProjectPath); + return { + ...resolved, + ...(sourceProjectPath ? { headRepositoryNameWithOwner: sourceProjectPath } : {}), + ...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}), }; } diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts new file mode 100644 index 0000000000000..838309b037617 --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/TanStackSourcePullRequestProvider.test.ts @@ -0,0 +1,138 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; + +import * as TanStackSourceApi from "./TanStackSourceApi.ts"; +import * as Credentials from "./TanStackSourceCredentials.ts"; +import * as TanStackSourcePullRequestProvider from "./TanStackSourcePullRequestProvider.ts"; + +const HOST = "source.tanstack.com"; + +/** + * Shaped like `GET /pulls/{n}` of a private pull request: its head is `owner:branch` in the + * companion repository, and Source has stored no file or line counts for it. + */ +const PRIVATE_PULL = { + number: 42, + title: "Fix the thing", + state: "open", + visibility: "private", + draft: false, + author: "bob", + head: "acme:fix/thing", + createdAt: 1_000, + body: null, + base: "main", + headRepo: "acme/web.private", + headSha: "c".repeat(40), + baseSha: "b".repeat(40), + mergeCommitSha: null, + mergedAt: null, + mergedBy: null, + mergeable: null, + changedFiles: null, + changedLines: null, +}; + +const FILES = { + baseSha: "b".repeat(40), + headSha: "c".repeat(40), + mergeBaseSha: "b".repeat(40), + available: true, + truncated: false, + files: [ + { path: "a.ts", status: "modified", additions: 3, deletions: 1 }, + { path: "b.ts", status: "added", additions: 4, deletions: 0 }, + ], +}; + +const RESPONSES: Record = { + "/repos/acme/web/pulls/42": PRIVATE_PULL, + "/repos/acme/web/pulls/42/files": FILES, + "/repos/acme/web/pulls/42/checks": { checks: [], upToDate: null, mayMerge: true }, + "/repos/acme/web/pulls/42/stack": { members: [] }, + [`/repos/acme/web/check-runs?sha=${"c".repeat(40)}`]: [], + "/repos/acme/web/ci/runs?pull=42&limit=30": { items: [], next: null }, + "/repos/acme/web/issues/42": { + timeline: [ + { id: 1, comment: "Looks good", author: "alice", at: 2_000 }, + { event: "head_updated", actor: "bob", at: 3_000 }, + ], + next: null, + }, + "/repos/acme/web/pulls/42/comments": [], + "/repos/acme/web/pulls/42/commits": { + baseSha: null, + headSha: null, + mergeBaseSha: null, + available: true, + commits: [], + }, + "/user": { username: "alice" }, +}; + +const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => + input.path in RESPONSES + ? Effect.succeed(JSON.stringify(RESPONSES[input.path])) + : Effect.die(`unexpected ${input.path}`), + response: () => Effect.die("unexpected response read"), +}); + +const provider = TanStackSourcePullRequestProvider.make.pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provideService( + Credentials.TanStackSourceCredentials, + Credentials.TanStackSourceCredentials.of({ + get: () => Effect.die("unexpected credential read"), + invalidate: () => Effect.void, + }), + ), + Effect.provideService( + HttpClient.HttpClient, + HttpClient.make(() => Effect.die("unexpected http request")), + ), +); + +describe("TanStackSourcePullRequestProvider.getChangeRequest", () => { + // A client without this host's definition percent-encodes the owner's `@`; stored links + // keep the web's own spelling. + it.effect.each(["acme/web", "@acme/web", "%40acme/web"])( + "reads a private pull request of %s", + (repository) => + Effect.gen(function* () { + const detail = yield* (yield* provider).getChangeRequest({ + host: HOST, + repository, + number: 42, + cwd: "/repo", + }); + assert.strictEqual(detail.url, `https://${HOST}/@acme/web/pull/42`); + assert.strictEqual(detail.visibility, "private"); + assert.strictEqual(detail.headBranch, "fix/thing"); + assert.strictEqual(detail.headRepositoryNameWithOwner, "acme/web.private"); + // Source stores no counts for it, so they come from its files. + assert.deepStrictEqual( + [detail.changedFiles, detail.additions, detail.deletions], + [2, 7, 1], + ); + }), + ); +}); + +describe("TanStackSourcePullRequestProvider.getChangeRequestActivity", () => { + it.effect("reads the comments of a timeline that also holds events", () => + Effect.gen(function* () { + const activity = yield* (yield* provider).getChangeRequestActivity({ + host: HOST, + repository: "acme/web", + number: 42, + cwd: "/repo", + }); + assert.deepStrictEqual( + activity.comments.map((comment) => comment.body), + ["Looks good"], + ); + }), + ); +}); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts index 509e03e1f41f4..0529ce6df17c7 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.test.ts @@ -35,6 +35,8 @@ const PULL = { function checkout(options: { readonly recordedOwner: string | null; readonly isAncestor: boolean; + readonly pull?: Partial; + readonly force?: boolean; }) { const git: Array = []; const config = new Map( @@ -43,14 +45,28 @@ function checkout(options: { const api = TanStackSourceApi.TanStackSourceApi.of({ request: (input) => input.path === "/repos/acme/web/pulls/42" - ? Effect.succeed(JSON.stringify(PULL)) + ? Effect.succeed(JSON.stringify({ ...PULL, ...options.pull })) : Effect.die(`unexpected ${input.path}`), response: () => Effect.die("unexpected response read"), }); const host = TestSourceControlHost.layer({ git: { resolvePrimaryRemoteName: () => Effect.succeed("origin"), - ensureRemote: () => Effect.succeed("origin"), + ensureRemote: (input) => + Effect.sync(() => { + git.push(`remote ${input.preferredName} ${input.url}`); + return input.url === REMOTE ? "origin" : input.preferredName; + }), + fetchRemoteBranch: (input) => + Effect.sync( + () => + void git.push(`fetch ${input.remoteName} ${input.remoteBranch}:${input.localBranch}`), + ), + fetchRemoteTrackingBranch: () => Effect.void, + setBranchUpstream: (input) => + Effect.sync( + () => void git.push(`upstream ${input.branch} ${input.remoteName}/${input.remoteBranch}`), + ), readConfigValue: (_cwd, key) => Effect.succeed(key === "remote.origin.url" ? REMOTE : (config.get(key) ?? null)), writeConfigValue: (input) => Effect.sync(() => void config.set(input.key, input.value)), @@ -86,7 +102,13 @@ function checkout(options: { }, }); const run = TanStackSourceSourceControlProvider.make.pipe( - Effect.flatMap((provider) => provider.checkoutChangeRequest({ cwd: "/repo", reference: "42" })), + Effect.flatMap((provider) => + provider.checkoutChangeRequest({ + cwd: "/repo", + reference: "42", + ...(options.force === undefined ? {} : { force: options.force }), + }), + ), Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), Effect.provide(Layer.merge(host, FileSystem.layerNoop({}))), ); @@ -129,4 +151,83 @@ describe("TanStackSourceSourceControlProvider.checkoutChangeRequest", () => { assert.isFalse(git.some((command) => command.startsWith("checkout"))); }); }); + + // Source publishes no `refs/pull//head` for a private pull request, on either repository. + it.effect("takes a private pull request's branch from the companion repository", () => { + const pull = { head: "acme:fix-thing", headRepo: "acme/web.private" }; + const { run, git, config } = checkout({ recordedOwner: null, isAncestor: true, pull }); + const forced = checkout({ recordedOwner: null, isAncestor: true, pull, force: true }); + return Effect.gen(function* () { + yield* forced.run; + assert.include(forced.git, "checkout --no-track -B fix-thing refs/remotes/acme/fix-thing --"); + yield* run; + assert.strictEqual(config.get("branch.fix-thing.pushRemote"), "acme"); + assert.deepStrictEqual(git, [ + `remote source ${REMOTE}`, + "remote acme https://source.tanstack.com/@acme/web.private.git", + "fetch acme fix-thing:fix-thing", + "upstream fix-thing acme/fix-thing", + "switch fix-thing", + ]); + }); + }); +}); + +describe("TanStackSourceSourceControlProvider private pull requests", () => { + it.effect("asks Source for the companion and opens the pull request as private", () => { + const requests: Array<{ method: string; path: string; body: unknown }> = []; + const api = TanStackSourceApi.TanStackSourceApi.of({ + request: (input) => { + requests.push({ method: input.method ?? "GET", path: input.path, body: input.body }); + return Effect.succeed( + JSON.stringify({ + owner: "acme", + name: "web.private", + defaultBranch: null, + cloneUrl: "https://source.tanstack.com/@acme/web.private.git", + }), + ); + }, + response: () => Effect.die("unexpected response read"), + }); + const files = FileSystem.layerNoop({ readFileString: () => Effect.succeed("Body") }); + return Effect.gen(function* () { + const provider = yield* TanStackSourceSourceControlProvider.make; + const companion = provider.privateChangeRequestRemote; + assert.isDefined(companion); + assert.deepStrictEqual(yield* companion({ cwd: "/repo" }), { + url: "https://source.tanstack.com/@acme/web.private.git", + repository: "acme/web.private", + }); + yield* provider.createChangeRequest({ + cwd: "/repo", + baseRefName: "main", + headSelector: "sec/fix", + title: "Fix", + bodyFile: "/tmp/body.md", + private: true, + }); + assert.deepStrictEqual(requests, [ + { method: "POST", path: "/repos/acme/web/private-remote", body: undefined }, + { + method: "POST", + path: "/repos/acme/web/pulls", + body: { title: "Fix", head: "sec/fix", base: "main", body: "Body", private: true }, + }, + ]); + }).pipe( + Effect.provideService(TanStackSourceApi.TanStackSourceApi, api), + Effect.provide( + Layer.merge( + TestSourceControlHost.layer({ + git: { + resolvePrimaryRemoteName: () => Effect.succeed("origin"), + readConfigValue: () => Effect.succeed(REMOTE), + }, + }), + files, + ), + ), + ); + }); }); diff --git a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts index a1abb376b472d..f194848611361 100644 --- a/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts +++ b/packages/source-control-tanstack-source/src/server/TanStackSourceSourceControlProvider.ts @@ -395,6 +395,18 @@ export const make = Effect.gen(function* () { }, ), createsDraftChangeRequests: true, + privateChangeRequestRemote: Effect.fn( + "TanStackSourceSourceControlProvider.privateChangeRequestRemote", + )(function* (input) { + const target = yield* resolveTarget("privateChangeRequestRemote", input); + const companion = yield* read( + "privateChangeRequestRemote", + input.cwd, + { host: target.host, method: "POST", path: `/repos/${target.repository}/private-remote` }, + Repository, + ); + return { url: companion.cloneUrl, repository: `${companion.owner}/${companion.name}` }; + }), createChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.createChangeRequest")( function* (input) { const target = yield* resolveTarget("createChangeRequest", { @@ -437,6 +449,7 @@ export const make = Effect.gen(function* () { base: input.target?.refName ?? input.baseRefName, ...(body.trim().length === 0 ? {} : { body }), ...(input.draft === true ? { draft: true } : {}), + ...(input.private === true ? { private: true } : {}), }, }) .pipe( @@ -494,7 +507,8 @@ export const make = Effect.gen(function* () { return repository.defaultBranch; }, ), - // Every pull request's head is published as `refs/pull//head`, forks and GitHub sync too. + // A pull request's head is published as `refs/pull//head`, forks and GitHub sync too. A + // private one has no such ref: its branch is read from the companion repository. checkoutChangeRequest: Effect.fn("TanStackSourceSourceControlProvider.checkoutChangeRequest")( function* (input) { const pull = yield* getPull(input); @@ -519,9 +533,26 @@ export const make = Effect.gen(function* () { }); const operation = "TanStackSourceSourceControlProvider.checkoutChangeRequest"; const branches = yield* git.listLocalBranchNames(input.cwd); - if (!pull.isCrossRepository) { + const companion = + pullRepository !== null && + pull.headRepositoryNameWithOwner?.toLowerCase() === + `${pullRepository}.private`.toLowerCase() + ? pull.headRepositoryNameWithOwner + : null; + if (!pull.isCrossRepository || companion !== null) { const localBranch = pull.headRefName; - const remoteBranch = { cwd: input.cwd, remoteName, remoteBranch: localBranch }; + const remoteBranch = { + cwd: input.cwd, + remoteName: + companion === null + ? remoteName + : yield* git.ensureRemote({ + cwd: input.cwd, + preferredName: companion.split("/")[0] ?? "private", + url: `${Hosts.webRepositoryUrl(HOST, companion)}.git`, + }), + remoteBranch: localBranch, + }; if (input.force !== true && !branches.includes(localBranch)) yield* git.fetchRemoteBranch({ ...remoteBranch, localBranch }); else yield* git.fetchRemoteTrackingBranch(remoteBranch); @@ -535,11 +566,18 @@ export const make = Effect.gen(function* () { "--no-track", "-B", localBranch, - `refs/remotes/${remoteName}/${localBranch}`, + `refs/remotes/${remoteBranch.remoteName}/${localBranch}`, "--", ], }); yield* git.setBranchUpstream({ ...remoteBranch, branch: localBranch }); + // Whatever push defaults say, this branch must not be published to the public remote. + if (companion !== null) + yield* git.writeConfigValue({ + cwd: input.cwd, + key: `branch.${localBranch}.pushRemote`, + value: remoteBranch.remoteName, + }); yield* Effect.scoped(git.switchRef({ cwd: input.cwd, refName: localBranch })); return; } diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts new file mode 100644 index 0000000000000..ac43a46ccdcad --- /dev/null +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { tanStackSourceRepositoryPath } from "./tanStackSourceHosts.ts"; + +describe("tanStackSourceRepositoryPath", () => { + it.each([ + ["acme/web", "acme/web"], + ["@acme/web", "acme/web"], + // Clients without this host's definition percent-encode the owner's `@`. + ["%40acme/web", "acme/web"], + ["/@acme/web.git/", "acme/web"], + ["acme/web.private", "acme/web.private"], + ["acme", null], + ["acme/web/extra", null], + ["acme/..", null], + ])("reads %s as %s", (path, repository) => { + expect(tanStackSourceRepositoryPath(path)).toBe(repository); + }); +}); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts index 22923264629bf..dfa6d4e9031a0 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceHosts.ts @@ -1,4 +1,4 @@ -import { TANSTACK_SOURCE_HOST } from "../shared/definition.ts"; +import { TANSTACK_SOURCE_HOST, withoutOwnerMark } from "../shared/definition.ts"; export const TANSTACK_SOURCE_HOSTS = [TANSTACK_SOURCE_HOST] as const; export type TanStackSourceHost = (typeof TANSTACK_SOURCE_HOSTS)[number]; @@ -10,14 +10,14 @@ export function tanStackSourceHost(host: string): TanStackSourceHost | null { const SEGMENT = /^[A-Za-z0-9_.-]+$/u; -/** `owner/name` from the API spelling or the web spelling `@owner/name`, `.git` dropped. */ +/** `owner/name` from the API spelling or either web spelling of the owner, `.git` dropped. */ export function tanStackSourceRepositoryPath(path: string): string | null { - const [owner, name, ...rest] = path - .trim() - .replace(/^\/+|\/+$/gu, "") - .replace(/\.git$/u, "") - .replace(/^@/u, "") - .split("/"); + const [owner, name, ...rest] = withoutOwnerMark( + path + .trim() + .replace(/^\/+|\/+$/gu, "") + .replace(/\.git$/u, ""), + ).split("/"); return rest.length === 0 && owner !== undefined && name !== undefined && diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts index 4d698fb881dfb..24c93e6aac83d 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.test.ts @@ -146,6 +146,7 @@ describe("toActivity", () => { ["4", "review-comment", null], ]); expect(activity.comments[0]?.url).toBe(`https://${HOST}/@TanStack/ai/pull/9#comment-1`); + expect(Json.pullUrl(HOST, "%40TanStack/ai", 9)).toBe(`https://${HOST}/@TanStack/ai/pull/9`); expect(activity.reviewThreads).toMatchObject([ { id: "4", path: "a.ts", line: 2, side: "left", isResolved: true }, ]); diff --git a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts index acf3c4158f95c..51537627ca3e7 100644 --- a/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts +++ b/packages/source-control-tanstack-source/src/server/tanStackSourceJson.ts @@ -16,6 +16,8 @@ import type { import * as DateTime from "effect/DateTime"; import * as Schema from "effect/Schema"; +import { withoutOwnerMark } from "../shared/definition.ts"; + /** Source sends times as epoch milliseconds. */ const EpochMillis = Schema.Finite; const Login = Schema.String; @@ -29,6 +31,7 @@ export const SourcePull = Schema.Struct({ labels: Schema.optional(Schema.Array(Schema.String)), head: Schema.String, createdAt: EpochMillis, + visibility: Schema.optional(Schema.String), }); export type SourcePull = typeof SourcePull.Type; @@ -135,7 +138,8 @@ const TimelineEntry = Schema.Struct({ type TimelineEntry = typeof TimelineEntry.Type; export const SourceTimeline = Schema.Struct({ - timeline: Schema.Array(TimelineEntry), + // Events such as `head_updated` sit between the comments and carry no id. + timeline: Schema.Array(Schema.Union([TimelineEntry, Schema.Struct({ event: Schema.String })])), next: Schema.NullOr(Schema.String), }); @@ -239,10 +243,20 @@ export const SourceUser = Schema.Struct({ username: Schema.String }); export const iso = (millis: number) => DateTime.formatIso(DateTime.makeUnsafe(millis)); export const pullUrl = (host: string, repository: string, number: number) => - `https://${host}/@${repository}/pull/${number}`; + `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`; -/** A GitHub-synced pull request from a fork names its head only by its pull ref. */ -export const headBranchName = (head: string) => head.replace(/^refs\/heads\//u, ""); +/** + * A GitHub-synced pull request from a fork names its head only by its pull ref, and a private + * one as `owner:branch`. A branch name holds no colon, so the owner is all that one can precede. + */ +export const headBranchName = (head: string) => + head.replace(/^refs\/heads\//u, "").replace(/^[^/:]+:/u, ""); + +/** Absent when Source names no visibility, so a reader tells unknown from public. */ +const visibilityOf = (pull: Pick) => + pull.visibility === "private" || pull.visibility === "public" + ? { visibility: pull.visibility } + : {}; export function toActor(login: string | null, host: string): PullRequestActor | null { if (login === null || login.trim() === "") return null; @@ -280,6 +294,7 @@ export function toChangeRequest( baseBranch: pull.base ?? "", state: pull.state, isDraft: pull.draft, + ...visibilityOf(pull), mergeability: "unknown", additions: 0, deletions: 0, @@ -380,7 +395,9 @@ export function toActivity(input: { }): ProviderChangeRequestActivity { const { host } = input; const page = pullUrl(host, input.repository, input.number); - const entries = input.timeline.timeline.filter(visible); + const entries = input.timeline.timeline.filter( + (entry): entry is TimelineEntry => "id" in entry && visible(entry), + ); const comments: Array = entries.map((entry: TimelineEntry) => ({ id: String(entry.id), kind: diff --git a/packages/source-control-tanstack-source/src/shared/definition.test.ts b/packages/source-control-tanstack-source/src/shared/definition.test.ts index e3ce5c867fa5c..6e09a89fa2cda 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.test.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.test.ts @@ -31,7 +31,23 @@ describe("TanStack Source definition", () => { number: 7, }), ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); + // A stored link or an older client may name the repository as the web spells it. + for (const repository of ["@TanStack/router", "%40TanStack/router"]) + expect( + definition.changeRequestUrl({ host: "source.tanstack.com", repository, number: 7 }), + repository, + ).toBe("https://source.tanstack.com/@TanStack/router/pull/7"); expect(definition.checkoutCommandArgument("src pr checkout 7")).toBe("7"); expect(definition.checkoutCommandArgument("gh pr checkout 7")).toBeNull(); }); + + it.each(["tanstack/router", "@tanstack/router", "%40tanstack/router"])( + "keys %s as the API's owner/name", + (repository) => { + expect(definition.canonicalRepositoryKey?.(`source.tanstack.com/${repository}`)).toBe( + "source.tanstack.com/tanstack/router", + ); + expect(definition.canonicalRepositoryKey?.(`github.com/${repository}`)).toBeNull(); + }, + ); }); diff --git a/packages/source-control-tanstack-source/src/shared/definition.ts b/packages/source-control-tanstack-source/src/shared/definition.ts index 1aee00c968dc6..032adc5a45cdd 100644 --- a/packages/source-control-tanstack-source/src/shared/definition.ts +++ b/packages/source-control-tanstack-source/src/shared/definition.ts @@ -37,6 +37,20 @@ function parseChangeRequestUrl(url: URL) { : { ...link, repositoryUrl: `${url.origin}/@${CHANGE_REQUEST_PATH.exec(url.pathname)![1]}` }; } +/** + * `owner/name` as the API names it. The web spells it `@owner/name`, and a client without this + * definition percent-encodes that as `%40owner/name`. + */ +export const withoutOwnerMark = (repository: string) => repository.replace(/^(?:@|%40)/iu, ""); + +/** Links stored with the web's spelling compare equal to the project's own key. */ +function canonicalRepositoryKey(key: string): string | null { + const slash = key.indexOf("/"); + return slash > 0 && isTanStackSourceHost(key.slice(0, slash)) + ? `${TANSTACK_SOURCE_HOST}/${withoutOwnerMark(key.slice(slash + 1))}` + : null; +} + /** Keys drop the owner's `@`, so a project's repository is `owner/name` as the API names it. */ function repositoryKeyFromRemote(key: string): string | null { // Remote parsing spells the `@` percent-encoded. @@ -80,13 +94,13 @@ export const definition = defineSourceControl({ ? null : webUrl ? changeRequestUrlBelow(webUrl, `pull/${number}`) - : `https://${host}/@${repository.replace(/^@/u, "")}/pull/${number}`, + : `https://${host}/@${withoutOwnerMark(repository)}/pull/${number}`, parseChangeRequestUrl, commitUrl: (input) => buildCommitUrl( input.webUrl ? input - : { ...input, webUrl: `https://${input.host}/@${input.repository.replace(/^@/u, "")}` }, + : { ...input, webUrl: `https://${input.host}/@${withoutOwnerMark(input.repository)}` }, "commit", ), parseIssueUrl: (url) => @@ -122,6 +136,7 @@ export const definition = defineSourceControl({ checkoutChangeRequestHost: () => null, changeRequestHeadRef: (number) => `refs/pull/${number}/head`, repositoryKeyFromRemote, + canonicalRepositoryKey, recognizeRemote: ({ hostname }) => isTanStackSourceHost(hostname) ? { kind: KIND, name: "TanStack Source", baseUrl: `https://${TANSTACK_SOURCE_HOST}` } diff --git a/patches/@legendapp__list@3.7.3.patch b/patches/@legendapp__list@3.7.3.patch new file mode 100644 index 0000000000000..2afc400b04435 --- /dev/null +++ b/patches/@legendapp__list@3.7.3.patch @@ -0,0 +1,28 @@ +diff --git a/react-native.js b/react-native.js +index 440b0ad..fd5d18d 100644 +--- a/react-native.js ++++ b/react-native.js +@@ -1344,7 +1344,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( +diff --git a/react-native.mjs b/react-native.mjs +index b95e1f8..e2b013a 100644 +--- a/react-native.mjs ++++ b/react-native.mjs +@@ -1323,7 +1323,8 @@ function checkAtBottom(ctx, allowedEdge, allowGateCreatedInCurrentCheck) { + return; + } + if (contentSize > 0 && queuedInitialLayout) { +- const isContentLess = contentSize < scrollLength; ++ // T3 patch: a top inset (e.g. a translucent header) shrinks the room content has to fit in. ++ const isContentLess = contentSize + getContentInsetTop(ctx) < scrollLength; + set$(ctx, "isAtEnd", isContentLess || distanceFromEnd <= EDGE_POSITION_EPSILON); + set$(ctx, "isNearEnd", isContentLess || distanceFromEnd <= onEndReachedThreshold * scrollLength); + set$( diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cdf1c829c7ba1..564cfd7d7f6e7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -369,6 +369,7 @@ patchedDependencies: '@effect/vitest@4.1.5': dd0bf2b1ae0f63aff0d620ebc67b82d19759b3fa69a608ef85e2a5b40b4d46c5 '@expo/ui@58.0.27': 9f2547678939f4ec78fe45163b6455aad63d3c80353d7e0cc783f6a61a7ccc2f '@ff-labs/fff-node@0.11.0': 93f62a76399b435a76588b2bef237db0a1e85880c1ac0d0759c416e9cc579252 + '@legendapp/list@3.7.3': 85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4 '@muse-code/sdk@1.4.6': 7b495b607fc5d76b444c7c4d58821e839726a30e6f3c53564f0d59f2d5b42101 '@pierre/diffs@1.7.0-beta.4': 7edcdd484a99c7ec0b2667499c4cb21d113ec9bea1f8570c0b0a030d33bbf1cd '@react-native-menu/menu@2.0.0': 6872ba71b9847c5a0210b1b896923dadc3860faedfe28d9f062bcedfe786ef1d @@ -573,7 +574,7 @@ importers: version: 5.4.6 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@material/material-color-utilities': specifier: 0.3.0 version: 0.3.0 @@ -1106,7 +1107,7 @@ importers: version: 5.3.0 '@legendapp/list': specifier: 3.7.3 - version: 3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) + version: 3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0) '@noble/hashes': specifier: 'catalog:' version: 1.8.0 @@ -15733,7 +15734,7 @@ snapshots: '@koromix/koffi-win32-x64@3.3.6': optional: true - '@legendapp/list@3.7.3(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': + '@legendapp/list@3.7.3(patch_hash=85979836ae620bdc6b40e29e3da04afd0a1a3a925ef00bdb3788e9b6fa2153f4)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(@react-native/metro-config@0.88.1(@babel/core@7.29.7(supports-color@8.1.1))(bufferutil@4.1.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(@types/react@19.3.0)(bufferutil@4.1.0)(react@19.3.0)(supports-color@8.1.1)(utf-8-validate@6.0.6))(react@19.3.0)': dependencies: react: 19.3.0 use-sync-external-store: 1.7.0(react@19.3.0) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index d8fd4bc07cb15..7e3c147d69351 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -232,6 +232,7 @@ patchedDependencies: react-native-image-viewing@0.2.2: patches/react-native-image-viewing@0.2.2.patch mdast-util-math@3.0.0: patches/mdast-util-math@3.0.0.patch micromark-extension-llm-math@3.1.0: patches/micromark-extension-llm-math@3.1.0.patch + "@legendapp/list@3.7.3": patches/@legendapp__list@3.7.3.patch micromark-extension-gfm-table@2.1.1: patches/micromark-extension-gfm-table@2.1.1.patch micromark@4.0.2: patches/micromark@4.0.2.patch mdast-util-to-hast@13.2.1: patches/mdast-util-to-hast@13.2.1.patch diff --git a/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts new file mode 100644 index 0000000000000..6cfbafc6c49b2 --- /dev/null +++ b/scripts/scenarios/citation-skips-ambiguous-project-files.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const FILE = "handoff.txt"; + +test( + "A bare citation leaves the file unresolved when other projects contain several matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("planning"); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: [`See :codex-file-citation{path="${FILE}" line_range_start="1"}`], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts new file mode 100644 index 0000000000000..22458e6223fbb --- /dev/null +++ b/scripts/scenarios/citation-skips-other-project-after-ambiguous-local-search.e2e.ts @@ -0,0 +1,34 @@ +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +test( + "A bare citation leaves the file unresolved when the thread project has ambiguous matches", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("support", { + "current/Handoff.txt": "Current support handoff", + "archive/HANDOFF.txt": "Archived support handoff", + }); + await t3.project("reports", { "notes/HANDOFF.txt": "Report handoff" }); + const thread = await t3.thread({ + project, + title: "Find the handoff", + messages: ['See :codex-file-citation{path="handoff.txt" line_range_start="1"}'], + }); + + await t3.open(thread); + await screen.getByRole("button", /^Agent See/).tap(); + await screen.getByRole("link", /^handoff\.txt/).tap(); + + try { + await expect( + browser + .locator("[data-right-panel-surface-content]") + .getByText("The file could not be accessed or read. It may be missing or inaccessible."), + ).toBeVisible(); + } finally { + await app.screenshot("ambiguous-local-handoff-citation"); + } + }, +); diff --git a/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts new file mode 100644 index 0000000000000..739497a827757 --- /dev/null +++ b/scripts/scenarios/clone-failure-after-dismissing-progress.e2e.ts @@ -0,0 +1,113 @@ +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture holds Git's HTTP request open. +import * as NodeHttp from "node:http"; +import * as NodeCrypto from "@effect/platform-node/NodeCrypto"; +import { ProjectId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as SecureRandom from "effect/crypto/SecureRandom"; +import * as Stream from "effect/Stream"; + +import { T3_HOME } from "../e2e.config.ts"; +import { rpcClient, runPromise, test, WEB } from "./t3.ts"; + +test( + "Dismissing clone progress leaves the later failure notification visible", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo"); + const thread = await t3.thread({ project, title: "Other work", messages: ["Start"] }); + const gitRequest = Promise.withResolvers(); + const remote = NodeHttp.createServer((_request, response) => { + gitRequest.resolve(response); + }); + + try { + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + const projectId = ProjectId.make( + await runPromise( + SecureRandom.SecureRandom.pipe( + Effect.flatMap((random) => random.uuidV4()), + Effect.provide(NodeCrypto.layer), + ), + ), + ); + const name = "pending-clone"; + const origin = app.baseUrl ?? ""; + await t3.open(thread); + await screen.getByText("Start", { exact: true }).waitFor(); + + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + const createdAt = DateTime.formatIso(yield* DateTime.now); + yield* client["projectClone.start"]({ + projectId, + title: name, + createdAt, + remoteUrl: `http://127.0.0.1:${address.port}/${name}.git`, + destinationPath: `${project}/../${name}`, + }); + }).pipe(Effect.scoped), + ); + const response = await gitRequest.promise; + + const toastTitle = (title: string) => + browser.locator(`[data-slot="toast-title"]:text-is("${title}")`); + const dismiss = async (title: string) => { + await browser + .locator( + `[data-position]:has(> div > [data-slot="toast-close"]):has([data-slot="toast-title"]:text-is("${title}"))`, + ) + .getByRole("button", "Dismiss notification", { exact: true }) + .tap(); + await toastTitle(title).waitFor({ state: "detached" }); + }; + const progress = toastTitle(`Cloning ${name}`); + const failure = toastTitle(`Failed to clone ${name}`); + + await progress.waitFor(); + await dismiss(`Cloning ${name}`); + + response.writeHead(404).end(); + await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + yield* client.subscribeProjectClones({}).pipe( + Stream.filter((clones) => + clones.some((clone) => clone.projectId === projectId && clone.phase === "failed"), + ), + Stream.runHead, + ); + }).pipe(Effect.scoped, Effect.timeout("10 seconds")), + ); + + try { + await expect(failure).toBeVisible(); + } finally { + await app.screenshot("after-background-clone-fails"); + } + + await dismiss(`Failed to clone ${name}`); + + const retryRequest = Promise.withResolvers(); + remote.once("request", (_request, response) => retryRequest.resolve(response)); + const retry = await runPromise( + Effect.gen(function* () { + const client = yield* rpcClient(T3_HOME, origin); + return yield* client["projectClone.retry"]({ projectId }); + }).pipe(Effect.scoped), + ); + await expect(retry.applied).toBe(true); + const retryResponse = await retryRequest.promise; + await expect(progress).toBeVisible(); + retryResponse.writeHead(404).end(); + await expect(failure).toBeVisible(); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +); diff --git a/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts new file mode 100644 index 0000000000000..dbd90361cfe45 --- /dev/null +++ b/scripts/scenarios/closed-linked-thread-stays-closed-during-pairing.e2e.ts @@ -0,0 +1,139 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodeCredential = Schema.decodeUnknownSync(Schema.Struct({ credential: Schema.String })); + +test( + "A closed linked-thread tab does not take over the conversation when pairing finishes", + WEB, + async ({ t3, app, browser, screen }) => { + const project = await t3.project("primary"); + const parent = await t3.thread({ + project, + title: "Current work", + messages: ["Keep this conversation open"], + }); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + const second = makeState(SECOND_HOME); + const issued = await runPromise(second.cli(["auth", "session", "issue", "--token-only"])); + // @effect-diagnostics-next-line globalFetch:off -- Seeds the real peer link from the scenario's Node fixture. + const pairing = await fetch(`${host}/api/auth/pairing-token`, { + method: "POST", + headers: { + authorization: `Bearer ${issued.stdout.trim()}`, + "content-type": "application/json", + }, + body: JSON.stringify({ purpose: "peer-link", access: "full-access" }), + }); + if (!pairing.ok) throw new Error(`Could not mint a peer-link code: ${pairing.status}`); + const { credential } = decodeCredential(await pairing.json()); + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "full-access", + }); + }).pipe(Effect.scoped), + ); + + const linkedProject = await second.state.project("linked"); + const linkedTitle = "Remote design notes"; + const linkedPrompt = "Read the remote design notes"; + const remoteThread = await second.state.thread({ + project: linkedProject, + title: linkedTitle, + messages: [linkedPrompt], + }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + await browser.setViewport({ width: 1440, height: 900 }); + + // Restore the same saved tab that opening the delegated thread in the panel would leave. + await browser.addInitScript( + ({ via, linked, parentId, childId, title }) => { + if (location.pathname !== `/${via}/${parentId}`) return; + const id = `linked-thread:${encodeURIComponent(via)}:${encodeURIComponent(linked)}:${encodeURIComponent(childId)}`; + localStorage.setItem( + "t3code:right-panel-state:v2", + JSON.stringify({ + version: 16, + state: { + byThreadKey: { + [`${via}:${parentId}`]: { + isOpen: true, + activeSurfaceId: id, + surfaces: [ + { + kind: "linked-thread", + id, + viaEnvironmentId: via, + environmentId: linked, + threadId: childId, + label: "Scenario", + title, + }, + ], + }, + }, + threadPanelVisibilityByThreadKey: {}, + }, + }), + ); + }, + { + via, + linked, + parentId: parent.threadId, + childId: remoteThread.threadId, + title: linkedTitle, + }, + ); + + const tokenUrl = `${host}/oauth/token`; + const requested = Promise.withResolvers(); + const release = Promise.withResolvers(); + await browser.route(tokenUrl, async (route) => { + if (route.request.method !== "POST") return route.fallback(); + requested.resolve(); + await release.promise; + await route.continue(); + }); + try { + await t3.open(parent); + await screen.getByText(linkedPrompt, { exact: true }).waitFor(); + const originalUrl = await browser.url(); + await screen.getByRole("button", "Connect to interact", { exact: true }).tap(); + await requested.promise; + await screen.getByRole("button", `Close ${linkedTitle}`, { exact: true }).tap(); + + release.resolve(); + await screen + .getByText("This device is paired with it and can use its threads.", { exact: true }) + .waitFor(); + + await app.screenshot("after-pairing-finishes"); + await expect(browser).toHaveURL(originalUrl); + } finally { + release.resolve(); + await browser.unroute(tokenUrl); + } + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts new file mode 100644 index 0000000000000..42c5c57b1ea4c --- /dev/null +++ b/scripts/scenarios/linked-thread-connects-before-fallback-timeout.e2e.ts @@ -0,0 +1,88 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +const linkEnvironments = Effect.fn("scenario.linkEnvironments")(function* ( + primaryOrigin: string, + secondOrigin: string, + fallback: string, +) { + const primary = yield* rpcClient(T3_HOME, primaryOrigin); + const second = yield* rpcClient(SECOND_HOME, secondOrigin); + for (const client of [primary, second]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli(["auth", "pairing", "create", "--json"]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: secondOrigin, + alternateUrls: [fallback], + pairingCode: credential, + access: "full-access", + }); +}, Effect.scoped); + +test( + "Connect to interact opens the editable thread before a silent fallback times out", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const primary = app.baseUrl ?? ""; + const secondServer = startSecondServer(primary); + try { + const { host } = await secondServer.ready; + const alternate = new URL(host); + alternate.hostname = "127.0.0.2"; + await runPromise(linkEnvironments(primary, host, alternate.origin)); + + const second = makeState(SECOND_HOME).state; + const project = await second.project("linked"); + const thread = await second.thread({ + project, + title: "Linked handoff", + messages: ["first"], + }); + const via = await runPromise(environmentId(primary)); + const target = await runPromise(environmentId(host)); + + await browser.addInitScript((fallback) => { + const fetchActual = globalThis.fetch; + globalThis.fetch = (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input), location.href); + if (url.origin !== fallback || url.pathname !== "/.well-known/t3/environment") { + // @effect-diagnostics-next-line globalFetch:off - This interception runs inside the browser. + return fetchActual(input, init); + } + // The browser's network silently drops this route. The preferred address is still real. + return new Promise((_, reject) => { + const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined); + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }; + }, alternate.origin); + + await t3.open(`/linked/${via}/${target}/${thread.threadId}`); + await screen.getByRole("heading", "Linked handoff").waitFor(); + await screen.getByRole("button", "Connect to interact").tap(); + + try { + await expect + .poll(() => browser.evaluate(() => location.pathname), { timeout: 4_000 }) + .toBe(`/${target}/${encodeURIComponent(thread.threadId)}`); + } finally { + await app.screenshot("linked-thread-after-connect"); + } + } finally { + await secondServer.stop(); + } + }, +); diff --git a/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts new file mode 100644 index 0000000000000..fd24c39b74dea --- /dev/null +++ b/scripts/scenarios/linked-thread-retry-reads-again.e2e.ts @@ -0,0 +1,105 @@ +/// +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { T3_HOME } from "../e2e.config.ts"; +import { SECOND_HOME, startSecondServer } from "./second-server.ts"; +import { environmentId, makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const decodePairing = Schema.decodeEffect( + Schema.fromJsonString(Schema.Struct({ credential: Schema.String })), +); + +test( + "Try again immediately reads a linked thread once it is reachable", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("primary"); + const origin = app.baseUrl ?? ""; + const server = startSecondServer(origin); + try { + const { host } = await server.ready; + await runPromise( + Effect.gen(function* () { + const primary = yield* rpcClient(T3_HOME, origin); + const remote = yield* rpcClient(SECOND_HOME, host); + for (const client of [primary, remote]) { + yield* client["server.updateSettings"]({ patch: { linkedEnvironmentsEnabled: true } }); + } + const pairing = yield* makeState(SECOND_HOME).cli([ + "auth", + "pairing", + "create", + "--json", + ]); + const { credential } = yield* decodePairing(pairing.stdout); + yield* primary["peerLinks.link"]({ + url: host, + pairingCode: credential, + access: "approval-required", + }); + }).pipe(Effect.scoped), + ); + + const remote = makeState(SECOND_HOME).state; + const project = await remote.project("linked"); + const prompt = "Read the linked design notes"; + const thread = await remote.thread({ project, title: "Design notes", messages: [prompt] }); + const via = await runPromise(environmentId(origin)); + const linked = await runPromise(environmentId(host)); + + // Drop only the first subscription, as if the linked machine were briefly unreachable. + // Every later request goes to the real server and reads the seeded thread. + await browser.addInitScript(() => { + let failed = false; + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (failed || typeof data !== "string") return send.call(this, data); + const parsed = JSON.parse(data); + const messages = Array.isArray(parsed) ? parsed : [parsed]; + const request = messages.find( + (message) => message?._tag === "Request" && message.tag === "peerLinks.subscribeThread", + ); + if (!request) return send.call(this, data); + failed = true; + const others = messages.filter((message) => message !== request); + if (others.length > 0) send.call(this, JSON.stringify(others)); + // @effect-diagnostics-next-line globalTimers:off - This callback is injected into the browser. + setTimeout(() => { + this.dispatchEvent( + new MessageEvent("message", { + data: JSON.stringify({ + _tag: "Exit", + requestId: request.id, + exit: { + _tag: "Failure", + cause: [ + { + _tag: "Fail", + error: { + _tag: "PeerLinkThreadReadError", + reason: "unreachable", + label: "Scenario", + message: "The linked machine is temporarily unreachable.", + }, + }, + ], + }, + }), + }), + ); + }, 0); + }; + }); + + await t3.open(`/linked/${via}/${linked}/${thread.threadId}`); + await screen.getByRole("button", "Try again", { exact: true }).tap(); + await app.screenshot("after-trying-again"); + // The automatic retry waits 15 seconds. This checks the user's explicit retry. + await expect(screen.getByText(prompt, { exact: true })).toBeVisible({ timeout: 4_000 }); + } finally { + await server.stop(); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts new file mode 100644 index 0000000000000..c944cf1ec9d42 --- /dev/null +++ b/scripts/scenarios/notebook-shows-saved-output-in-tall-preview.e2e.ts @@ -0,0 +1,80 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const savedResults = Array.from({ length: 17 }, (_, index) => `Saved result ${index + 1}`); +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: [ + { output_type: "stream", name: "stdout", text: Array(12).fill("Processing").join("\n") }, + ...savedResults.map((result) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `${result}` }, + })), + ], + }, + ], +}; +const lastOutput = '[data-notebook-output="0-17"]'; + +test( + "All saved notebook outputs render when they fit in a tall preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // The stream puts the final result below the fold until the user scrolls. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 1070; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator('[data-notebook-output="0-15"] iframe').waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = viewport.scrollHeight; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + const bounds = viewport.getBoundingClientRect(); + return Array.from(viewport.querySelectorAll("[data-notebook-output]"), (output) => { + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return "Output is offscreen"; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }); + }, lastOutput), + ) + .toEqual(savedResults); + } finally { + await app.screenshot("last-saved-output-in-tall-preview"); + } + }, +); diff --git a/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts new file mode 100644 index 0000000000000..2897ecc0df7eb --- /dev/null +++ b/scripts/scenarios/notebook-shows-visible-saved-output.e2e.ts @@ -0,0 +1,77 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { language_info: { name: "python" } }, + cells: [ + { + id: "results", + cell_type: "code", + source: [], + metadata: {}, + execution_count: 1, + outputs: Array.from({ length: 17 }, (_, index) => ({ + output_type: "display_data", + metadata: {}, + data: { "text/html": `Saved result ${index + 1}` }, + })), + }, + ], +}; +const fifteenthOutputFrame = '[data-notebook-output="0-14"] iframe'; +const lastOutput = '[data-notebook-output="0-16"]'; + +test( + "A visible saved notebook output renders when earlier outputs have scrolled above it", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "results.ipynb": JSON.stringify(notebook) }); + const thread = await t3.thread({ project, title: "Review results", messages: ["Start"] }); + await browser.setViewport({ width: 1440, height: 1080 }); + await t3.open(thread); + await screen.getByText("fixture turn complete", { exact: false }).waitFor(); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("results.ipynb"); + await screen.getByRole("option", "results.ipynb", { exact: false }).tap(); + await browser.locator(lastOutput).waitFor({ state: "attached", timeout: 120_000 }); + + // Leave room for the final output and fewer than sixteen preceding outputs. + const height = await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + return window.innerHeight - viewport.clientHeight + 940; + }, lastOutput); + await browser.setViewport({ width: 1440, height }); + await browser.locator(fifteenthOutputFrame).waitFor({ timeout: 30_000 }); + await browser.evaluate((selector) => { + const viewport = document.querySelector(selector)!.closest(".scrollbar-gutter-both")!; + viewport.scrollTop = 170; + return null; + }, lastOutput); + + try { + await expect + .poll(() => + browser.evaluate((selector) => { + const output = document.querySelector(selector); + const viewport = output?.closest(".scrollbar-gutter-both"); + if (!output || !viewport) return null; + const bounds = viewport.getBoundingClientRect(); + const row = output.getBoundingClientRect(); + if (row.top < bounds.top || row.bottom > bounds.bottom) return null; + return ( + output.querySelector("iframe")?.contentDocument?.body?.textContent?.trim() || + "Output is in view but blank" + ); + }, lastOutput), + ) + .toBe("Saved result 17"); + } finally { + await app.screenshot("last-saved-output"); + } + }, +); diff --git a/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts new file mode 100644 index 0000000000000..8ee5453bbba20 --- /dev/null +++ b/scripts/scenarios/queued-message-shows-file-mention-by-name.e2e.ts @@ -0,0 +1,37 @@ +import { expect } from "e2e"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, runPromise, test, WEB } from "./t3.ts"; + +test( + "A queued message shows its @-file mention by name, not as a raw link", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "src/foo.ts": "export {};\n" }); + const thread = await t3.thread({ + project, + title: "Long work", + messages: ["Show me around"], + model: "showcase", + }); + await t3.open(thread); + + const composer = screen.getByRole("textbox"); + await composer.pressSequentially("Review @foo"); + await screen.getByRole("option", "foo.ts", { exact: false }).tap(); + await expect(composer).toContainText("foo.ts"); + + // The showcase recording streams for several seconds, long enough to queue behind its turn. + await runPromise(makeState(T3_HOME).cli(["thread", "send", thread.threadId, "Show me again"])); + await screen.getByText("Working for", { exact: false }).waitFor(); + // Enter steers by default; the alternate send queues. + await browser.keyboard.press("ControlOrMeta+Enter"); + + const queued = screen.getByRole("listitem", "Queued message 1 of 1, not sent"); + await queued.waitFor(); + // Read the row once: the queued message sends, and its row goes, when the turn ends. + const text = await queued.textContent(); + await app.screenshot("queued-row"); + expect(text).toContain("Review foo.ts"); + }, +); diff --git a/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts new file mode 100644 index 0000000000000..49186eaa4429a --- /dev/null +++ b/scripts/scenarios/rejected-theme-file-supersedes-earlier-read.e2e.ts @@ -0,0 +1,64 @@ +/// +import { expect } from "e2e"; + +import { test, WEB } from "./t3.ts"; + +declare global { + interface Window { + releaseOldThemeRead: () => void; + } +} + +test( + "An earlier theme file cannot become the draft after its replacement is rejected", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("demo"); + await t3.open("/settings/appearance"); + await screen.getByRole("button", "Add theme", { exact: true }).tap(); + const dialog = screen.getByRole("dialog", "Add a theme"); + + await browser.evaluate(() => { + const target = document.querySelector('input[type="file"]')?.parentElement; + if (!target) throw new Error("No theme file drop target"); + + const gate = Promise.withResolvers(); + const theme = JSON.stringify({ + version: 1, + name: "Earlier theme", + appearance: "dark", + colors: { accent: "#734ee4" }, + }); + const first = new File([theme], "earlier.json", { type: "application/json" }); + const text = File.prototype.text; + File.prototype.text = function () { + if (this.name === first.name) return gate.promise.then(() => theme); + return text.call(this); + }; + window.releaseOldThemeRead = gate.resolve; + + const drop = (file: File) => { + const files = new DataTransfer(); + files.items.add(file); + target.dispatchEvent( + new DragEvent("drop", { dataTransfer: files, bubbles: true, cancelable: true }), + ); + }; + drop(first); + drop(new File([" ".repeat(300_000)], "replacement.json", { type: "application/json" })); + return null; + }); + + await dialog.getByText(/That file is/).waitFor(); + await browser.evaluate(async () => { + window.releaseOldThemeRead(); + // Let the earlier file response and its React update reach the dialog. + await new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + return null; + }); + await app.screenshot("dialog-after-earlier-theme-read-finishes"); + await expect(dialog.getByRole("button", "Add theme", { exact: true })).toBeDisabled(); + }, +); diff --git a/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts new file mode 100644 index 0000000000000..acd9096465978 --- /dev/null +++ b/scripts/scenarios/webhook-log-keeps-whole-emoji.e2e.ts @@ -0,0 +1,75 @@ +import { ProjectSnapshot, ProviderInstanceId } from "@t3tools/contracts"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; + +import { T3_HOME } from "../e2e.config.ts"; +import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts"; + +const PROMPT_LOG_LIMIT = 64 * 1024; +const FRAME_OPEN = "".length; + +const deliverStraddlingEmoji = Effect.fn("scenario.deliverStraddlingEmoji")( + function* (origin: string) { + const issued = yield* makeState(T3_HOME).cli(["auth", "session", "issue", "--token-only"]); + const { projects } = yield* HttpClient.execute( + HttpClientRequest.get(`${origin}/api/projects`).pipe( + HttpClientRequest.bearerToken(issued.stdout.trim()), + ), + ).pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap(HttpClientResponse.schemaBodyJson(ProjectSnapshot)), + ); + const client = yield* rpcClient(T3_HOME, origin); + const { task } = yield* client["scheduledTasks.upsert"]({ + title: "Webhook log", + prompt: "{{body.text}}", + enabled: true, + schedule: { type: "webhook" }, + projectId: projects.find((project) => project.title === "webhook-log")!.id, + workspaceStrategy: { type: "root" }, + modelSelection: { instanceId: ProviderInstanceId.make("devReplay"), model: "showcase" }, + runtimeMode: "full-access", + interactionMode: "default", + }); + // The emoji's high surrogate is the last code unit the delivery log keeps. + const text = `${"a".repeat(PROMPT_LOG_LIMIT - 1 - FRAME_OPEN)}😀 tail`; + yield* HttpClient.execute( + HttpClientRequest.post(`${origin}${task.webhook!.path}`).pipe( + HttpClientRequest.bodyJsonUnsafe({ text }), + ), + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + }, + Effect.scoped, + Effect.provide(FetchHttpClient.layer), +); + +test( + "A long webhook prompt in the delivery log does not end in a broken character", + WEB, + async ({ t3, app, browser, screen }) => { + await t3.project("webhook-log"); + await runPromise(deliverStraddlingEmoji(app.baseUrl ?? "")); + + await t3.open("/settings/scheduled-tasks"); + await screen.getByRole("button", "Actions for Webhook log").tap(); + await screen.getByRole("menuitem", "Deliveries").tap(); + const dialog = screen.getByRole("dialog"); + await dialog.getByRole("button", /POST/).tap(); + const prompt = dialog.getByText(/^ { + const block = [...document.querySelectorAll("pre")].find((pre) => + pre.textContent?.startsWith(" +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { expect } from "e2e"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Path from "effect/Path"; +import JSZip from "jszip"; + +import { test, WEB } from "./t3.ts"; + +const SHEETS = ["Overview", "Actuals", "Forecast"]; +const RELATIONSHIPS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; + +async function workbook() { + const archive = new JSZip(); + const sheets = SHEETS.map( + (name, index) => ``, + ).join(""); + archive.file( + "xl/workbook.xml", + `${sheets}`, + ); + const relationships = SHEETS.map( + (_, index) => + ``, + ).join(""); + archive.file("xl/_rels/workbook.xml.rels", `${relationships}`); + for (const [index] of SHEETS.entries()) + archive.file( + `xl/worksheets/sheet${index + 1}.xml`, + `${index + 1}`, + ); + return archive.generateAsync({ type: "uint8array" }); +} + +test( + "Two rapid right arrows advance two tabs in an Excel preview", + WEB, + async ({ t3, app, screen, browser }) => { + const project = await t3.project("demo", { "budget.xlsx": await workbook() }); + const archive = await JSZip.loadAsync(await workbook()); + const manifest = (await archive.file("xl/workbook.xml")!.async("string")).replace( + ' { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + first.focus(); + for (let press = 0; press < 2; press++) + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + return null; + }); + await screen.getByRole("grid", /Actuals|Forecast/).waitFor(); + await app.screenshot("after-two-right-arrows"); + await expect + .poll(() => + browser.evaluate( + () => + document + .querySelector('[role="tablist"]') + ?.parentElement?.querySelector('[role="grid"]') + ?.getAttribute("aria-label") ?? null, + ), + ) + .toBe("Forecast"); + + await browser.keyboard.press("Control+p"); + await screen.getByPlaceholder("Search files…").fill("wraparound.xlsx"); + await screen.getByRole("option", "wraparound.xlsx", { exact: false }).tap(); + await browser + .locator('[data-active-tab="true"]') + .getByText("wraparound.xlsx", { exact: true }) + .waitFor(); + const overview = screen.getByRole("tab", "Overview"); + await overview.waitFor(); + + const { ok: showSucceeded, selectedAtSecondPress } = await browser.evaluate(async () => { + const first = document.querySelector( + '[role="tablist"] [role="tab"][aria-selected="true"]', + )!; + const pressRight = () => + document.activeElement?.dispatchEvent( + new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true, cancelable: true }), + ); + const postMessage = Worker.prototype.postMessage; + return await new Promise<{ ok: boolean; selectedAtSecondPress: string | null }>((resolve) => { + Worker.prototype.postMessage = function ( + this: Worker, + message: { method?: string; id?: number }, + options?: Transferable[] | StructuredSerializeOptions, + ) { + if (message.method === "show") { + Worker.prototype.postMessage = postMessage; + const onReply = (event: MessageEvent<{ id: number; ok: boolean }>) => { + if (event.data.id !== message.id) return; + this.removeEventListener("message", onReply); + if (event.data.ok !== true) { + resolve({ ok: false, selectedAtSecondPress: null }); + return; + } + // The worker client has queued the first layout, and React has yet to commit it. + queueMicrotask(() => { + const selected = first.getAttribute("aria-selected"); + pressRight(); + resolve({ ok: true, selectedAtSecondPress: selected }); + }); + }; + this.addEventListener("message", onReply); + } + Reflect.apply(postMessage, this, [message, options]); + }; + first.focus(); + pressRight(); + }); + }); + expect(showSucceeded).toBe(true); + expect(selectedAtSecondPress).toBe("true"); + await expect(overview).toBeFocused(); + await app.screenshot("after-wrapping-to-overview"); + await expect(overview).toHaveAttribute("aria-selected", "true"); + await expect(screen.getByRole("grid", "Overview")).toBeVisible(); + }, +);