diff --git a/.github/upstream-fixes/cursor b/.github/upstream-fixes/cursor index 0be12054a5773..3f2b5eb8b6679 100644 --- a/.github/upstream-fixes/cursor +++ b/.github/upstream-fixes/cursor @@ -1 +1 @@ -ce36269560ad502cf6a5c44775fc4e648e829d2a +6ce5c5b4d4a3560bb9a5dbb1b6b2ecfaf21a67d9 diff --git a/.github/upstream-fixes/manual b/.github/upstream-fixes/manual index f2f75bb8c58ac..397252400dd40 100644 --- a/.github/upstream-fixes/manual +++ b/.github/upstream-fixes/manual @@ -6,3 +6,18 @@ ce56dfe956d1 # fix(notebook): keep the final frame across saved stream records ( 2e2af395f626 # fix(web): EPUB previews keep SVG lighting filters (#44498): did not apply af70189a8f6f # fix(web): remote localhost links in chat and terminal open through a port forward (#44452): did not apply 30e7a1f84822 # fix(shared): thread search by PR number keeps the PR title when a branch PR is also linked (#44495): adds an upstream runtime identifier; manual port needed to packages/client-runtime/src/threadPullRequests.test.ts +bf6c5dfd556b # failed CI as a single pick in #48 (https://github.com/Ryoku-dev/hyakki/actions/runs/46711414007); needs a manual port +93955ac9bd0d # fix(web): preserve ODT list marker styles (#44514): did not apply +1356a26ebad1 # fix(web): large CSV previews keep their end position (#44520): did not apply +13f9213cffc0 # fix(client-runtime): keep the scheme and port in fallback URLs for mounted Forgejo pull requests (#44521): did not apply +5f435d14570d # fix(server): detach idle threads from shared provider sessions (#44020): did not apply +2338c6f30583 # fix(shared): thread links work after list code blocks (#44527): did not apply +1060a7e151d8 # fix(server): avoid broken emoji in project search previews during indexing (#44531): did not apply +c0f45b67620c # fix(client-runtime): /reload-skills refreshes the composer skill menu (#31309): did not apply +d26bc688a5e9 # fix(server): resolve project favicons with encoded HTML rel tokens (#44537): did not apply +c49c99659427 # fix(mcp): include completed user input answers in thread reads (#44542): did not apply +cf4a35f7a7af # fix(web): /feedback no longer drops a pending reply (#44541): did not apply +1f6fe0afbf52 # fix(web): large logs keep their place when switching tabs (#44517): did not apply +ae8c3c8d6a03 # fix(web): diff panel shows images when their file row is expanded (#44556): did not apply +6ce5c5b4d4a3 # fix: show proposed plan titles once after code examples (#44518): did not apply +b89c25ffd9a7 # fix(web): keep sidebar search results when opening threads (#30278): adds an upstream runtime identifier; manual port needed to apps/web/src/components/Sidebar.search.browser.test.tsx diff --git a/.github/upstream-fixes/skip b/.github/upstream-fixes/skip index 745aebf04645f..ea8fb14d772b7 100644 --- a/.github/upstream-fixes/skip +++ b/.github/upstream-fixes/skip @@ -1,3 +1,4 @@ # Upstream commits the fixes workflow must never pick, one sha per line. # Add a commit here when it does not fit this fork; a short sha is enough. 270fb873f470 # Failed CI twice as a single pick in PR #13; needs a manual port. +bf6c5dfd556b # failed CI as a single pick in #48 (https://github.com/Ryoku-dev/hyakki/actions/runs/46711414007); needs a manual port diff --git a/apps/server/src/guest/GuestShareService.test.ts b/apps/server/src/guest/GuestShareService.test.ts index 5873b4fe93bcd..2317c0bfcd5f3 100644 --- a/apps/server/src/guest/GuestShareService.test.ts +++ b/apps/server/src/guest/GuestShareService.test.ts @@ -5,6 +5,7 @@ import { ChatAttachmentId, CommandId, EventId, + GUEST_SHARE_TTL_MS, GuestShareId, type GuestStreamEvent, MessageId, @@ -757,27 +758,70 @@ it.effect("pages the guest back through turns older than the stream's snapshot", }).pipe(Effect.scoped, Effect.provide(layerTest)), ); -it.effect("ends a running command's output once the owner stops sharing", () => +it.effect.each(["thread.guest-share.close", "thread.archive", "thread.delete"] as const)( + "ends a running command's output on %s", + (type) => + Effect.gen(function* () { + const { orchestrator, guestShares, credential } = yield* shareThread; + const commandOutputs = yield* CommandOutputHub.CommandOutputHub; + const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); + const command = yield* writeItem("item:running", { + type: "command_execution", + status: "running", + input: "ls /work/src", + output: "before-close\n", + }); + const opened = yield* Deferred.make(); + const collecting = yield* (yield* guestShares.commandOutput(session, command)).pipe( + Stream.tap(() => Deferred.succeed(opened, undefined)), + Stream.runCollect, + Effect.forkChild, + ); + yield* Deferred.await(opened); + // Let the periodic revocation fiber finish its initial open-share check and enter its 30s wait. + yield* TestClock.adjust("1 second"); + yield* orchestrator.dispatch({ + type, + commandId: CommandId.make(`${type}-during-command`), + threadId, + }); + yield* commandOutputs.append({ threadId, itemId: command, chunk: "SECRET_AFTER_CLOSE\n" }); + yield* TestClock.adjust("1 second"); + const endedBeforeRecheck = collecting.pollUnsafe() !== undefined; + // Advance past the fallback poll so an unpatched server finishes cleanly and fails on the leak assertion. + yield* TestClock.adjust("30 seconds"); + const frames = Array.from(yield* Fiber.join(collecting)); + assert.isFalse(frames.some((frame) => frame.text.includes("SECRET_AFTER_CLOSE"))); + assert.isTrue(endedBeforeRecheck); + assert.isTrue( + Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command))), + ); + }).pipe(Effect.provide(layerTest)), +); + +it.effect("ends a running command's output when the link expires, before the next recheck", () => Effect.gen(function* () { - const { orchestrator, guestShares, credential } = yield* shareThread; + const { guestShares, credential } = yield* shareThread; const { token: session } = yield* guestShares.redeem({ credential, name: "Sam" }); const command = yield* writeItem("item:running", { type: "command_execution", status: "running", input: "ls /work/src", + output: "before-expiry\n", }); - const collecting = yield* Stream.runCollect( - yield* guestShares.commandOutput(session, command), - ).pipe(Effect.forkChild); - yield* orchestrator.dispatch({ - type: "thread.guest-share.close", - commandId: CommandId.make("close-during-command"), - threadId, - }); - yield* TestClock.adjust("30 seconds"); - const frames = Array.from(yield* Fiber.join(collecting)); - assert.isTrue(frames.every((frame) => frame.running)); - assert.isTrue(Exit.isFailure(yield* Effect.exit(guestShares.commandOutput(session, command)))); + // Opening 10s after the share puts the 30s rechecks at 10s past each half minute, off the expiry. + yield* TestClock.adjust("10 seconds"); + const opened = yield* Deferred.make(); + const collecting = yield* (yield* guestShares.commandOutput(session, command)).pipe( + Stream.tap(() => Deferred.succeed(opened, undefined)), + Stream.runCollect, + Effect.forkChild, + ); + yield* Deferred.await(opened); + yield* TestClock.adjust(GUEST_SHARE_TTL_MS - 10_000 - 1); + assert.isUndefined(collecting.pollUnsafe()); + yield* TestClock.adjust(2); + assert.isDefined(collecting.pollUnsafe()); }).pipe(Effect.provide(layerTest)), ); diff --git a/apps/server/src/guest/GuestShareService.ts b/apps/server/src/guest/GuestShareService.ts index 264ff3296db0c..3e348bfe1c719 100644 --- a/apps/server/src/guest/GuestShareService.ts +++ b/apps/server/src/guest/GuestShareService.ts @@ -490,6 +490,12 @@ const make = Effect.gen(function* () { }); }); + const endsShareFor = (shareId: GuestShareId) => (event: OrchestrationV2DomainEvent) => { + if (event.type === "thread.archived" || event.type === "thread.deleted") return true; + const updated = threadOf(event); + return updated !== null && updated.guestShare?.id !== shareId; + }; + /** Completes once the session no longer opens its share, so open reads end with it. */ const untilRevoked = (session: string) => authorize(session, "session").pipe( @@ -559,11 +565,7 @@ const make = Effect.gen(function* () { if (initialView === null) return yield* inactive; const ended: GuestStreamEvent = { type: "ended" }; - const endsShare = (event: OrchestrationV2DomainEvent) => { - if (event.type === "thread.archived" || event.type === "thread.deleted") return true; - const updated = threadOf(event); - return updated !== null && updated.guestShare?.id !== share.id; - }; + const endsShare = endsShareFor(share.id); const live = orchestrator .streamStoredEventsFrom({ threadId: thread.id, afterSequence: snapshot.snapshotSequence }) .pipe( @@ -655,7 +657,7 @@ const make = Effect.gen(function* () { session: string, itemId: string, ) { - const { thread } = yield* authorize(session, "session"); + const { thread, share } = yield* authorize(session, "session"); const id = TurnItemId.make(itemId); const item = (yield* orchestrator @@ -668,7 +670,7 @@ const make = Effect.gen(function* () { Effect.map((page) => page.items[0]?.item ?? null), Effect.mapError(() => unavailable), )); - return item === null ? yield* unavailable : { thread, item }; + return item === null ? yield* unavailable : { thread, share, item }; }); const render = Effect.fn("GuestShareService.render")(function* (session: string, itemId: string) { @@ -708,12 +710,29 @@ const make = Effect.gen(function* () { session: string, itemId: string, ) { - const { item } = yield* threadItem(session, itemId); + const { thread, share, item } = yield* threadItem(session, itemId); if (item.type !== "command_execution") return yield* unavailable; + const afterSequence = yield* orchestrator + .getThreadEventSequence(thread.id) + .pipe(Effect.mapError(() => unavailable)); + // A share that ends before the cursor is read fails this check; one that ends after it ends + // `shareEnded`. + yield* authorize(session, "session"); + const endsShare = endsShareFor(share.id); + const shareEnded = orchestrator + .streamStoredEventsFrom({ threadId: thread.id, afterSequence }) + .pipe( + Stream.filter((stored) => endsShare(stored.event)), + Stream.runHead, + Effect.ignore, + ); + const untilExpiry = Effect.sleep( + Math.max(0, Date.parse(share.expiresAt) - DateTime.toEpochMillis(yield* DateTime.now)), + ); return commandOutputs.subscribe({ threadId: item.threadId, itemId: item.id }).pipe( // A lost hub stream ends the output; the row reloads it when reopened. Stream.catchCause(() => Stream.empty), - Stream.interruptWhen(untilRevoked(session)), + Stream.interruptWhen(Effect.raceAll([shareEnded, untilExpiry, untilRevoked(session)])), ); }); diff --git a/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.ts b/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.ts index 7605fc6bea621..a7877af98072d 100644 --- a/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.ts +++ b/apps/server/src/resourceTelemetry/ResourceTelemetryHistory.ts @@ -117,27 +117,44 @@ function buildBuckets(input: { }): ReadonlyArray { const windowStartMs = input.nowMs - input.windowMs; const buckets: ResourceTelemetryHistoryBucket[] = []; + // Samples arrive sorted by sampledAtMs, so one cursor walks them across all buckets. + let index = 0; for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += input.bucketMs) { const endedAtMs = Math.min(input.nowMs, startedAtMs + input.bucketMs); - const samples = input.samples.filter( - (sample) => - sample.sampledAtMs >= startedAtMs && - (endedAtMs === input.nowMs - ? sample.sampledAtMs <= endedAtMs - : sample.sampledAtMs < endedAtMs), - ); - const cpuTotal = samples.reduce((total, sample) => total + sample.cpuPercent, 0); + const isLastBucket = endedAtMs === input.nowMs; + while (index < input.samples.length && input.samples[index]!.sampledAtMs < startedAtMs) { + index += 1; + } + let count = 0; + let cpuTotal = 0; + let maxCpuPercent = -Infinity; + let maxRssBytes = -Infinity; + let maxProcessCount = -Infinity; + let ioReadBytes = 0; + let ioWriteBytes = 0; + while (index < input.samples.length) { + const sample = input.samples[index]!; + if (isLastBucket ? sample.sampledAtMs > endedAtMs : sample.sampledAtMs >= endedAtMs) { + break; + } + count += 1; + cpuTotal += sample.cpuPercent; + maxCpuPercent = Math.max(maxCpuPercent, sample.cpuPercent); + maxRssBytes = Math.max(maxRssBytes, sample.rssBytes); + maxProcessCount = Math.max(maxProcessCount, sample.processCount); + ioReadBytes += sample.ioReadBytes; + ioWriteBytes += sample.ioWriteBytes; + index += 1; + } buckets.push({ startedAt: DateTime.makeUnsafe(startedAtMs), endedAt: DateTime.makeUnsafe(endedAtMs), - avgCpuPercent: samples.length === 0 ? 0 : cpuTotal / samples.length, - maxCpuPercent: - samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.cpuPercent)), - maxRssBytes: samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.rssBytes)), - ioReadBytes: samples.reduce((total, sample) => total + sample.ioReadBytes, 0), - ioWriteBytes: samples.reduce((total, sample) => total + sample.ioWriteBytes, 0), - maxProcessCount: - samples.length === 0 ? 0 : Math.max(...samples.map((sample) => sample.processCount)), + avgCpuPercent: count === 0 ? 0 : cpuTotal / count, + maxCpuPercent: count === 0 ? 0 : maxCpuPercent, + maxRssBytes: count === 0 ? 0 : maxRssBytes, + ioReadBytes, + ioWriteBytes, + maxProcessCount: count === 0 ? 0 : maxProcessCount, }); } return buckets; diff --git a/apps/web/src/components/CommandPalette.composition.browser.test.tsx b/apps/web/src/components/CommandPalette.composition.browser.test.tsx index e7f0022362c90..3366f22c6572a 100644 --- a/apps/web/src/components/CommandPalette.composition.browser.test.tsx +++ b/apps/web/src/components/CommandPalette.composition.browser.test.tsx @@ -13,11 +13,13 @@ import { AsyncResult } from "effect/reactivity"; const scopes = vi.hoisted(() => ({ denied: undefined as string | undefined, sourceControl: undefined as unknown, + isBrowsePending: false, lookupRepository: vi.fn(), })); -const setup = (deniedScope?: string, sourceControl?: unknown) => { +const setup = (deniedScope?: string, sourceControl?: unknown, isBrowsePending = false) => { scopes.denied = deniedScope; scopes.sourceControl = sourceControl; + scopes.isBrowsePending = isBrowsePending; }; const githubAvailable = { versionControlSystems: [], @@ -131,7 +133,11 @@ vi.mock("../state/filesystem", async (original) => ({ })); vi.mock("../state/query", async (original) => ({ ...(await original()), - useEnvironmentQuery: () => ({ data: scopes.sourceControl, isLoading: false }), + useEnvironmentQuery: () => ({ + data: scopes.sourceControl, + isLoading: false, + isPending: scopes.isBrowsePending, + }), })); vi.mock("./settings/useAvailableSettingsSearchItems", () => ({ useAvailableSettingsSearchItems: () => [], @@ -173,6 +179,27 @@ describe.each(["repository", "folder", "destination"] as const)("add-project %s" }); }); +it.each([ + { isBrowsePending: false, leavesInput: true }, + { isBrowsePending: true, leavesInput: false }, +])( + "Tab with nothing to complete in the folder path: %j", + async ({ isBrowsePending, leavesInput }) => { + setup(undefined, undefined, isBrowsePending); + await using _screen = await render({null}); + await act(() => openCommandPalette({ open: "add-project" })); + await page.getByText("Local folder", { exact: true }).click(); + const input = page.getByRole("combobox"); + await input.fill("/workspace/zzz"); + await userEvent.keyboard("{Tab}"); + if (leavesInput) { + await expect.element(input).not.toHaveFocus(); + expect(page.getByRole("dialog").element().contains(document.activeElement)).toBe(true); + } else await expect.element(input).toHaveFocus(); + await expect.element(input).toHaveValue("/workspace/zzz"); + }, +); + it.each([ { step: "folder", source: "Local folder", keys: "", description: /^(?!.*(Ctrl|⌘)).*Add.*Enter/ }, { @@ -228,6 +255,7 @@ it.each([ { flow: "Git URL", value: "https://github.com/Ryoku-dev/hyakki.git", submit: "Continue (Enter)" }, { flow: "New project", value: "demo-tab-order", submit: /^Create \(/ }, ])("moves focus from the $flow input to its enabled submit button on Tab", async (step) => { + setup(); await using _screen = await render({null}); await act(() => openCommandPalette({ open: "add-project" })); await page.getByText(step.flow, { exact: true }).click(); diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.ts index b2449bf57d367..46cab268bf0e8 100644 --- a/apps/web/src/components/CommandPalette.logic.test.ts +++ b/apps/web/src/components/CommandPalette.logic.test.ts @@ -61,6 +61,19 @@ describe("linked pull request thread navigation", () => { }); describe("reduceCommandPaletteUiState", () => { + it("keeps the session on dismissal and advances it on keyboard reopen", () => { + const open: CommandPaletteUiState = { + open: true, + mode: "command", + openIntent: null, + session: 1, + }; + const toggle = { _tag: "ToggleMode", mode: "command" } as const; + const closed = reduceCommandPaletteUiState(open, toggle); + expect(closed).toMatchObject({ open: false, session: 1 }); + expect(reduceCommandPaletteUiState(closed, toggle)).toMatchObject({ open: true, session: 2 }); + }); + it("opens PR search from another overlay and replaces an earlier search", () => { const first = reduceCommandPaletteUiState( { open: true, mode: "files", openIntent: null, session: 0 }, @@ -90,7 +103,7 @@ describe("reduceCommandPaletteUiState", () => { ).toBeNull(); }); - it("keeps the session across mode switches so only intents start the palette over", () => { + it("starts a new session when a shortcut replaces the active mode", () => { let state: CommandPaletteUiState = { open: false, mode: "command", @@ -100,12 +113,12 @@ describe("reduceCommandPaletteUiState", () => { state = reduceCommandPaletteUiState(state, { _tag: "OpenNewThreadIn" }); expect(state).toMatchObject({ open: true, openIntent: { kind: "new-thread-in" }, session: 1 }); state = reduceCommandPaletteUiState(state, { _tag: "ToggleMode", mode: "files" }); - expect(state).toMatchObject({ mode: "files", openIntent: null, session: 1 }); + expect(state).toMatchObject({ mode: "files", openIntent: null, session: 2 }); state = reduceCommandPaletteUiState(state, { _tag: "OpenAddProject" }); expect(state).toMatchObject({ mode: "command", openIntent: { kind: "add-project" }, - session: 2, + session: 3, }); }); }); @@ -943,7 +956,10 @@ describe("returning from file and content search", () => { const closed = reduceCommandPaletteUiState(child, { _tag: "SetOpen", open: false }); expect(closed).toEqual({ open: false, mode: "files", openIntent: null, session: 0 }); expect(reduceCommandPaletteUiState(closed, { _tag: "BackToCommand" })).toEqual(closed); - expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual(root); + expect(reduceCommandPaletteUiState(closed, { _tag: "SetOpen", open: true })).toEqual({ + ...root, + session: 1, + }); }); }); diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.ts index e979f38b5e5cd..62db4121c1f32 100644 --- a/apps/web/src/components/CommandPalette.logic.ts +++ b/apps/web/src/components/CommandPalette.logic.ts @@ -98,7 +98,7 @@ export interface CommandPaletteUiState { readonly mode: SearchOverlayMode; /** What the current palette session opened to; read once when the palette view mounts. */ readonly openIntent: CommandPaletteOpenIntent | null; - /** Bumped by every intent so an open palette starts over from the new one. */ + /** Advances when the palette opens or a new intent replaces the current session. */ readonly session: number; readonly parentSearch?: CommandPaletteReturnContext; readonly restoredSearch?: CommandPaletteReturnContext; @@ -136,18 +136,23 @@ export function reduceCommandPaletteUiState( switch (action._tag) { case "SetOpen": return action.open - ? { open: true, mode: "command", openIntent: state.openIntent, session } + ? { + open: true, + mode: "command", + openIntent: state.openIntent, + session: state.open && state.mode === "command" ? session : session + 1, + } : { open: false, mode: state.mode, openIntent: null, session }; case "ToggleMode": return state.open && state.mode === action.mode ? { open: false, mode: state.mode, openIntent: null, session } - : { open: true, mode: action.mode, openIntent: null, session }; + : { open: true, mode: action.mode, openIntent: null, session: session + 1 }; case "OpenChildSearch": return { open: true, mode: action.mode, openIntent: null, - session, + session: state.open ? session : session + 1, parentSearch: action.context, }; case "BackToCommand": diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 275b6ba69e947..04e2ecfa20280 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -604,12 +604,18 @@ function OpenCommandPaletteDialog(props: { await navigate({ to: "/draft/$draftId", params: { draftId: addProjectDraftId } }); return true; }; + const openSyncedProject = async ( + projectRef: ScopedProjectRef, + project: EnvironmentProject | null, + ): Promise => { + if (project !== null && (await moveDraftToAddedProject(project))) return; + await handleNewThread(projectRef); + }; const openAddedProject = async (projectRef: ScopedProjectRef): Promise => { // A moved draft is keyed from the project record, so wait for it to reach this client. const project = addProjectDraftId === null ? null : await waitForProject(projectRef, 3_000).catch(() => null); - if (project !== null && (await moveDraftToAddedProject(project))) return; - await handleNewThread(projectRef); + await openSyncedProject(projectRef, project); }; const createNewProject = useNewProject(openAddedProject); const cloneLookupGeneration = useRef(0); @@ -866,7 +872,7 @@ function OpenCommandPaletteDialog(props: { useEffect( () => () => { browseNavigation.invalidate(); - // A replaced or closed session must not report its in-flight lookup. + // A replaced or closed session must not report its in-flight lookup or clone start. cloneLookupGeneration.current += 1; }, [browseNavigation], @@ -2418,6 +2424,8 @@ function OpenCommandPaletteDialog(props: { return; } + const paletteAtStart = useCommandPaletteStore.getState(); + const flowGeneration = cloneLookupGeneration.current; setIsRemoteProjectCloning(true); const startResult = await startProjectClone({ environmentId: addProjectCloneFlow.environmentId, @@ -2442,17 +2450,30 @@ function OpenCommandPaletteDialog(props: { } return; } - setOpen(false); void suggestAppAccessForRemote( addProjectCloneFlow.environmentId, addProjectCloneFlow.remoteUrl, ); + const palette = useCommandPaletteStore.getState(); + if ( + palette.session !== paletteAtStart.session || + (palette.open && + (palette !== paletteAtStart || cloneLookupGeneration.current !== flowGeneration)) + ) { + return; + } + if (palette.open) setOpen(false); const projectRef = scopeProjectRef( addProjectCloneFlow.environmentId, startResult.value.projectId, ); - await waitForProject(projectRef, 3_000).catch(() => null); - const navigationResult = await settlePromise(() => openAddedProject(projectRef)); + const project = await waitForProject( + projectRef, + addProjectDraftId === null ? 3_000 : 6_000, + ).catch(() => null); + const paletteAfterSync = useCommandPaletteStore.getState(); + if (paletteAfterSync.open || paletteAfterSync.session !== paletteAtStart.session) return; + const navigationResult = await settlePromise(() => openSyncedProject(projectRef, project)); if (navigationResult._tag === "Failure") { const error = squashAtomCommandFailure(navigationResult); toastManager.add( @@ -2882,9 +2903,12 @@ function OpenCommandPaletteDialog(props: { if (event.key === "Tab" && isBrowsing && !relativePathNeedsActiveProject) { if (event.nativeEvent.isComposing || event.keyCode === 229) return; - (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); - event.preventDefault(); + const claimTab = () => { + (event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.(); + event.preventDefault(); + }; if (highlightedItemValue === "browse:up") { + claimTab(); void browseUp(); return; } @@ -2895,10 +2919,15 @@ function OpenCommandPaletteDialog(props: { ? { name: highlightedEntry.name, isComplete: true } : getFilesystemBrowseTabCompletion(visibleBrowseEntries, browsePath.filterQuery); if (completion?.isComplete) { + claimTab(); void browseTo(completion.name); } else if (completion && !pinnedCloneDirectoryName) { + claimTab(); setHighlightedItemValue(null); setQuery(`${browsePath.directoryPath}${completion.name}`); + } else if (isBrowsePending) { + // Nothing to complete yet; keep Tab so a fast typist is not thrown out while entries load. + claimTab(); } return; } @@ -2971,6 +3000,13 @@ function OpenCommandPaletteDialog(props: { return; } + const paletteAtPick = useCommandPaletteStore.getState(); + const flowGeneration = cloneLookupGeneration.current; + const cloneSelectionIsStale = () => + addProjectCloneFlow?.step === "confirm" && + (useCommandPaletteStore.getState() !== paletteAtPick || + cloneLookupGeneration.current !== flowGeneration); + setIsPickingProjectFolder(true); let pickedPath: string | null = null; let desktopWslState: DesktopWslState | null = null; @@ -2991,20 +3027,23 @@ function OpenCommandPaletteDialog(props: { ...(fileManagerInitialPath ? { initialPath: fileManagerInitialPath } : {}), ...(pickerTargetEnvironmentId ? { targetEnvironmentId: pickerTargetEnvironmentId } : {}), }; - pickedPath = await api.dialogs.pickFolder( - Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined, - ); + if (!cloneSelectionIsStale()) { + pickedPath = await api.dialogs.pickFolder( + Object.keys(pickerOptions).length > 0 ? pickerOptions : undefined, + ); + } } catch { setIsPickingProjectFolder(false); return; } setIsPickingProjectFolder(false); - if (!pickedPath) { + if (!pickedPath || cloneSelectionIsStale()) { return; } if (parseWslUncPath(pickedPath)) { if (desktopWslState === null) { desktopWslState = (await window.desktopBridge?.getWslState().catch(() => null)) ?? null; + if (cloneSelectionIsStale()) return; } let primaryRunningDistro: string | null = null; try { diff --git a/apps/web/src/components/settings/settingsSearch.test.ts b/apps/web/src/components/settings/settingsSearch.test.ts index fc3a8751a5501..231b868cc27fc 100644 --- a/apps/web/src/components/settings/settingsSearch.test.ts +++ b/apps/web/src/components/settings/settingsSearch.test.ts @@ -305,6 +305,7 @@ describe("searchSettings", () => { ["Native sessions", "providers"], ["CODEX_HOME path", "providers"], ["Shadow home path", "providers"], + ["ChatGPT account", "providers"], ["Your dictionary", "speech-dictionary"], ] as const) { expect(searchSettings(title)[0]?.id, title).toBe(id); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index d1c7a9885d170..bb3f4c7515f9a 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -1109,6 +1109,7 @@ export const SETTINGS_SEARCH_ITEMS = [ title: msg("Providers"), to: "/settings/providers", searchTerms: [ + msg("ChatGPT account"), msg( "agents cli codex claude cursor grok fx kiro opencode antigravity google sign in sign out install subscription instances authentication api key models configuration binary path config directory codex_home shadow home endpoint arguments environment variables display name accent color custom favorite hidden auto compact native sessions import resume", ), diff --git a/packages/shared/src/markdownLinks.test.ts b/packages/shared/src/markdownLinks.test.ts index 0f34976707d30..79febccab7c7f 100644 --- a/packages/shared/src/markdownLinks.test.ts +++ b/packages/shared/src/markdownLinks.test.ts @@ -279,6 +279,23 @@ describe("extractMarkdownLinkHrefs", () => { expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); }); + it.each([ + ["```md\n- [Setup](./a/README.md)\n```\n\nSee [README.md](./b/README.md)", ["./b/README.md"]], + ["Write `[Setup](./a/README.md)` as [README.md](./b/README.md)", ["./b/README.md"]], + ["[a `b](./a/README.md)` [c](./b/README.md)", ["./b/README.md"]], + ["[`code`](./a/README.md) and [x](<./b/a`b`.md>)", ["./a/README.md", "./b/a`b`.md"]], + ["`unclosed [a](./a/README.md)\n\nand` [b](./b/README.md)", ["./a/README.md", "./b/README.md"]], + ["~~~\n[a](./a/README.md)\n\n~~~\n[b](./b/README.md)", ["./b/README.md"]], + ["Type `` ``` `` then [a](./a/README.md)", ["./a/README.md"]], + ["\\``[a](./a/README.md)` [b](./b/README.md)", ["./b/README.md"]], + ["```\n```js\n[a](./a/README.md)\n```\n[b](./b/README.md)", ["./b/README.md"]], + ["- ```\n [a](./a/README.md)\n ```\n\n[b](./b/README.md)", ["./b/README.md"]], + ["> ```\n> [a](./a/README.md)\n> ```\n\n[b](./b/README.md)", ["./b/README.md"]], + ["- ```\n [a](./a/README.md)\n\n[b](./b/README.md)", ["./b/README.md"]], + ])("skips links inside code in %s", (markdown, hrefs) => { + expect(extractMarkdownLinkHrefs(markdown)).toEqual(hrefs); + }); + it.each([ [ String.raw`[one](<./a/doc\> final.ts>) [two](<./b/doc\> final.ts>)`, diff --git a/packages/shared/src/markdownLinks.ts b/packages/shared/src/markdownLinks.ts index 7e2d0b243a95a..4b756193b64ea 100644 --- a/packages/shared/src/markdownLinks.ts +++ b/packages/shared/src/markdownLinks.ts @@ -517,15 +517,25 @@ const PARAGRAPH_INTERRUPTION_PATTERN = const BLOCKQUOTE = 0; +export function extractInlineCodeSpans(text: string): string[] { + if (!text.includes("`")) return []; + const spans: string[] = []; + visitMarkdownLines(text, (line, _start, fenced) => { + if (!fenced) collectLineCodeSpans(line, spans); + }); + return spans; +} + /** - * Inline code spans outside fenced code. Blockquotes and list items are tracked line by line as + * Visits text lines and fenced code lines. Blockquotes and list items are tracked line by line as * CommonMark nests them, because a fence closes only at its own container's indentation and ends * with that container. A full parse would be exact but costs about 100x this scan, which runs on * every streamed chunk. */ -export function extractInlineCodeSpans(text: string): string[] { - if (!text.includes("`")) return []; - const spans: string[] = []; +function visitMarkdownLines( + text: string, + visit: (line: string, start: number, fenced: boolean) => void, +) { // Open containers, outermost first: BLOCKQUOTE, or a list item's content indentation. const containers: number[] = []; let fence: { marker: string; indented: boolean } | null = null; @@ -535,7 +545,10 @@ export function extractInlineCodeSpans(text: string): string[] { let indentedCode = false; // Depth of an item that has only its marker so far; a blank line next ends it. let emptyItemDepth = 0; + let lineStart = 0; for (const line of text.split("\n")) { + const start = lineStart; + lineStart += line.length + 1; let source = line.endsWith("\r") ? line.slice(0, -1) : line; if (source.includes("\t")) { let column = 0; @@ -583,6 +596,7 @@ export function extractInlineCodeSpans(text: string): string[] { if (content === "") continue; // A fence written inside indented code ends with that code. if (!fence.indented || indent >= 4) { + visit(line, start, true); const closer = FENCE_CLOSER_PATTERN.exec(content)?.[1]; if ( closer?.startsWith(fence.marker[0]!) && @@ -605,7 +619,7 @@ export function extractInlineCodeSpans(text: string): string[] { content !== "" && (indent >= 4 || !PARAGRAPH_INTERRUPTION_PATTERN.test(content)) ) { - collectLineCodeSpans(line, spans); + visit(line, start, false); continue; } containers.length = matched; @@ -626,13 +640,18 @@ export function extractInlineCodeSpans(text: string): string[] { if (!paragraph && !closedContainer) indentedCode = true; // Indented code is not skipped, but a fence shown inside it still hides its lines. Inside // a paragraph an indented line is text, where only a backtick run opens code (a span). - if (opener && (!paragraph || opener[0] === "`")) fence = { marker: opener, indented: true }; - else collectLineCodeSpans(line, spans); + if (opener && (!paragraph || opener[0] === "`")) { + fence = { marker: opener, indented: true }; + visit(line, start, true); + } else { + visit(line, start, false); + } break; } indentedCode = false; if (opener) { fence = { marker: opener, indented: false }; + visit(line, start, true); break; } if (content[0] === ">") { @@ -662,7 +681,7 @@ export function extractInlineCodeSpans(text: string): string[] { readIndent(); continue; } - collectLineCodeSpans(line, spans); + visit(line, start, false); paragraph = !( ATX_HEADING_PATTERN.test(content) || (paragraph && SETEXT_UNDERLINE_PATTERN.test(content)) @@ -670,7 +689,6 @@ export function extractInlineCodeSpans(text: string): string[] { break; } } - return spans; } function markdownRunEndFinder(markdown: string, delimiter: RegExp) { @@ -756,16 +774,46 @@ function markdownLinkDestinationScanner(markdown: string) { }; } +// Code is literal: fenced lines become spaces, keeping every offset. +function blankFencedCode(text: string): string { + if (!text.includes("```") && !text.includes("~~~")) return text; + let blanked = ""; + let copied = 0; + visitMarkdownLines(text, (line, start, fenced) => { + if (!fenced) return; + blanked += text.slice(copied, start) + line.replace(/[^\r]/g, " "); + copied = start + line.length; + }); + return blanked + text.slice(copied); +} + // 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[] { +export function extractMarkdownLinkHrefs(text: string): string[] { + const markdown = blankFencedCode(text); const hrefs: string[] = []; const scanDestination = markdownLinkDestinationScanner(markdown); - const bracket = /!\[|[[\]\\]|\n[ \t\r]*\n/g; + const paragraphEnd = markdownRunEndFinder(markdown, /\n[ \t\r]*\n/g); + // A code span closes at the next run of as many backticks in its paragraph. + const closersByLength = new Map(); + for (const run of markdown.matchAll(/`+/g)) { + const closers = closersByLength.get(run[0].length) ?? { ends: [], next: 0 }; + closers.ends.push(run.index + run[0].length); + closersByLength.set(run[0].length, closers); + } + const bracket = /!\[|[[\]\\]|`+|\n[ \t\r]*\n/g; const openers: boolean[] = []; for (let match = bracket.exec(markdown); match; match = bracket.exec(markdown)) { if (match[0] === "\\") { bracket.lastIndex = match.index + 2; + } else if (match[0].startsWith("`")) { + const length = match[0].length; + const closers = closersByLength.get(length) ?? { ends: [], next: 0 }; + while ((closers.ends[closers.next] ?? Infinity) - length < bracket.lastIndex) closers.next++; + const end = closers.ends[closers.next]; + if (end !== undefined && end - length <= paragraphEnd(bracket.lastIndex)) { + bracket.lastIndex = end; + } } else if (match[0].startsWith("\n")) { openers.length = 0; } else if (match[0].endsWith("[")) { diff --git a/packages/shared/src/path.test.ts b/packages/shared/src/path.test.ts index c9a97d2aab98a..aed44aa526e8d 100644 --- a/packages/shared/src/path.test.ts +++ b/packages/shared/src/path.test.ts @@ -128,6 +128,8 @@ describe("workspaceRelativeFilePath", () => { ["/repo/project/docs/a/../b.md", "/repo/project", "docs/a/../b.md"], ["/repo/a\\b.txt", "/repo", "a\\b.txt"], ["/repo/a/b.txt", "/repo", "a/b.txt"], + ["/repo//src/app.ts", "/repo", "src/app.ts"], + ["C:\\repo\\\\src\\app.ts", "C:\\repo", "src/app.ts"], ["/repo/a\\", "/repo", "a\\"], ["/repo/..\\notes.md", "/repo", "..\\notes.md"], ["/repo/a\\/../../notes.md", "/repo", null], diff --git a/packages/shared/src/path.ts b/packages/shared/src/path.ts index cb8df09b69356..b8f3f7c1e2594 100644 --- a/packages/shared/src/path.ts +++ b/packages/shared/src/path.ts @@ -158,7 +158,7 @@ export function workspaceRelativeFilePath( const rootForCompare = caseInsensitive ? normalizedRoot.toLowerCase() : normalizedRoot; if (pathForCompare.replace(/\/+$/, "") === rootForCompare) return "."; if (!pathForCompare.startsWith(`${rootForCompare}/`)) return null; - const relativePath = normalizedPath.slice(normalizedRoot.length + 1); + const relativePath = normalizedPath.slice(normalizedRoot.length + 1).replace(/^\/+/, ""); // `/repo/../x` starts with the root but escapes it; the server rejects that as a workspace path. let depth = 0; for (const segment of relativePath.split("/")) { diff --git a/packages/shared/src/pullRequestComposerTrigger.test.ts b/packages/shared/src/pullRequestComposerTrigger.test.ts index a919d7245c85c..bc6ac5244e9ba 100644 --- a/packages/shared/src/pullRequestComposerTrigger.test.ts +++ b/packages/shared/src/pullRequestComposerTrigger.test.ts @@ -23,6 +23,8 @@ describe("detectPullRequestComposerTrigger", () => { ["see #12", 4, "#", "12"], ["after !5", 6, "!", "5"], ["#crash", 0, "#", "crash"], + ["#किताब", 0, "#", "किताब"], + ["#cafe\u0301", 0, "#", "cafe\u0301"], ])("finds the trigger in %j", (text, rangeStart, sigil, query) => { const cursor = rangeStart + 1 + query.length; expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toEqual({ @@ -43,6 +45,7 @@ describe("detectPullRequestComposerTrigger", () => { ["C#", 2], ["![image", "![image".length], ["## Heading", 2], + ["#\u0301", "#\u0301".length], ])("ignores %j", (text, cursor) => { expect(detectPullRequestComposerTrigger(text, cursor, GITLAB)).toBeNull(); }); diff --git a/packages/shared/src/pullRequestComposerTrigger.ts b/packages/shared/src/pullRequestComposerTrigger.ts index 5016048e60f95..3cf1555ca8a23 100644 --- a/packages/shared/src/pullRequestComposerTrigger.ts +++ b/packages/shared/src/pullRequestComposerTrigger.ts @@ -17,9 +17,10 @@ export type PullRequestComposerTrigger = { | { readonly kind: "reference"; readonly sigil: PullRequestReferenceSigil } ); -// Logins are ASCII, but the query also matches display names, which can be in any script. -// Combining marks (\p{M}) attach to the letter before them, so they cannot start a name. -const TOKEN = /^(?:@([\p{L}\p{N}_][\p{L}\p{M}\p{N}_.-]*)?|([#!])([\p{L}\p{N}_-]*))$/u; +// Logins are ASCII, but queries also match display names and reference titles in any script. +// Combining marks (\p{M}) attach to the letter before them, so they cannot start a query. +const TOKEN = + /^(?:@([\p{L}\p{N}_][\p{L}\p{M}\p{N}_.-]*)?|([#!])([\p{L}\p{N}_-][\p{L}\p{M}\p{N}_-]*)?)$/u; /** What a pull request's host can complete; absent fields complete nothing. */ export type PullRequestCompletionSupport = Pick< diff --git a/scripts/scenarios/dismissed-palette-clone-keeps-reopened-palette.e2e.ts b/scripts/scenarios/dismissed-palette-clone-keeps-reopened-palette.e2e.ts new file mode 100644 index 0000000000000..36ee8a902fa5d --- /dev/null +++ b/scripts/scenarios/dismissed-palette-clone-keeps-reopened-palette.e2e.ts @@ -0,0 +1,131 @@ +/// +// @effect-diagnostics-next-line nodeBuiltinImport:off -- The fixture serves a local Git remote. +import * as NodeHttp from "node:http"; +import { expect } from "e2e"; + +import { test, WEB } from "./hyakki.ts"; + +test( + "A clone reply leaves a newly opened command palette open", + WEB, + async ({ hyakki, app, browser, screen }) => { + const project = await hyakki.project("demo"); + const thread = await hyakki.thread({ project, title: "Current work", messages: ["Start"] }); + const remote = NodeHttp.createServer(); + await new Promise((resolve) => remote.listen(0, "127.0.0.1", resolve)); + try { + const address = remote.address(); + if (!address || typeof address === "string") throw new Error("No Git fixture port"); + + await browser.addInitScript(() => { + const starts = new WeakMap(); + let released = false; + const searchesAfterRelease = new Set(); + document.addEventListener("release-palette-clone-start", () => { + released = true; + }); + const send = WebSocket.prototype.send; + WebSocket.prototype.send = function (data) { + if (typeof data === "string") { + for (const request of [JSON.parse(data)].flat()) { + if (request?._tag === "Request" && request.tag === "projectClone.start") { + starts.set(this, String(request.id)); + } + if ( + released && + request?._tag === "Request" && + request.tag === "orchestration.searchThreads" + ) { + searchesAfterRelease.add(String(request.id)); + } + } + } + return send.call(this, data); + }; + const listen = WebSocket.prototype.addEventListener; + WebSocket.prototype.addEventListener = function ( + this: WebSocket, + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions, + ) { + if (type !== "message" || typeof listener !== "function") { + return listen.call(this, type, listener, options); + } + return listen.call( + this, + type, + (event: Event) => { + const { data } = event as MessageEvent; + const wire = typeof data === "string" ? [JSON.parse(data)].flat() : []; + if ( + wire.some( + (message) => + message?._tag === "Exit" && + message.exit?._tag === "Success" && + String(message.requestId) === starts.get(this), + ) + ) { + document.documentElement.dataset.scenarioCloneReply = "ready"; + document.addEventListener( + "release-palette-clone-start", + () => listener.call(this, event), + { + once: true, + }, + ); + } else { + listener.call(this, event); + if ( + wire.some( + (message) => + message?._tag === "Exit" && + searchesAfterRelease.has(String(message.requestId)), + ) + ) { + document.documentElement.dataset.scenarioSearchAfterRelease = "answered"; + } + } + }, + options, + ); + } as typeof WebSocket.prototype.addEventListener; + }); + + await hyakki.open(thread); + await screen.getByText("Start", { exact: true }).waitFor({ timeout: 30_000 }); + const palette = screen.getByRole("dialog", "Command palette"); + await browser.keyboard.press("Control+k"); + await palette.getByRole("combobox").fill("> Add project"); + await palette.getByText("Add project", { exact: true }).tap(); + await palette.getByRole("option", /^Git URL/).tap(); + await palette.getByRole("combobox").fill(`http://127.0.0.1:${address.port}/clone.git`); + await screen.getByRole("button", "Continue (Enter)").tap(); + await palette.getByRole("combobox").fill(`${project}-copy`); + await palette.getByRole("button", /^(?:Create & )?Clone \(/).tap(); + await browser.locator("html[data-scenario-clone-reply=ready]").waitFor(); + await browser.keyboard.press("Escape"); + await palette.waitFor({ state: "hidden" }); + await browser.keyboard.press("Control+k"); + await palette.getByRole("combobox").fill("Current work"); + await browser.evaluate(() => { + document.dispatchEvent(new Event("release-palette-clone-start")); + return null; + }); + // A search sent after the release is answered only after the clone reply's + // continuation ran; if that continuation closed the palette, no search is sent. + await browser.keyboard.press("Backspace"); + const openPalette = '[data-slot="command-dialog-popup"][data-open]'; + await browser + .locator( + `html[data-scenario-search-after-release=answered], html:not(:has(${openPalette}))`, + ) + .waitFor({ state: "attached" }); + await app.screenshot("reopened-palette-after-clone-start-returns"); + expect(await browser.locator(openPalette).isVisible()).toBe(true); + } finally { + remote.close(); + remote.closeAllConnections(); + } + }, +);