diff --git a/apps/mobile/src/connection/runtime.ts b/apps/mobile/src/connection/runtime.ts index 25b3c3600a..09f8568f71 100644 --- a/apps/mobile/src/connection/runtime.ts +++ b/apps/mobile/src/connection/runtime.ts @@ -49,6 +49,7 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( providerCatalogsOnDemand: true, providerCatalogDigests: true, providerStatusDeltas: true, + editorUpdates: true, // Halves idle pings. The timeout is checked on ping ticks, after an unanswered ping // and 15 s with no frame: within 25 s of the last frame (20 s at the 5 s default), // and a host stalled for 10 s can lose the socket (15 s at the default). diff --git a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts index 793d301698..b81990350b 100644 --- a/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts +++ b/apps/mobile/src/features/pull-requests/pullRequestNavigation.test.ts @@ -63,6 +63,28 @@ describe("native PR entry points", () => { ).toEqual({ ...context, host: "github.com", repository: "someone/else", number: 12 }); }); + it("uses the thread's remote-less project only when it tracks folders", () => { + const url = "https://github.com/org/repo/pull/12"; + const trackedFolderProject = { + id: ProjectId.make("project"), + environmentId: EnvironmentId.make("remote"), + repositoryIdentity: null, + trackedFolders: [{ path: "/workspace/repo", name: "repo" }], + }; + const plainFolderProject = { + id: ProjectId.make("project"), + environmentId: EnvironmentId.make("remote"), + repositoryIdentity: null, + }; + expect(destination(url, context, [trackedFolderProject], () => true)).toEqual({ + ...context, + host: "github.com", + repository: "org/repo", + number: 12, + }); + expect(destination(url, context, [plainFolderProject], () => true)).toBeNull(); + }); + it("leaves links to the external opener when the environment cannot show them", () => { const url = "https://github.com/org/repo/pull/12"; expect(nativePullRequestDestination(url, context, projects, () => false)).toBeNull(); diff --git a/apps/mobile/src/lib/pullRequestNavigation.ts b/apps/mobile/src/lib/pullRequestNavigation.ts index feef5ae6b0..8245ce0292 100644 --- a/apps/mobile/src/lib/pullRequestNavigation.ts +++ b/apps/mobile/src/lib/pullRequestNavigation.ts @@ -41,7 +41,9 @@ export function pullRequestFileLinkRoute( export function nativePullRequestDestination( url: string, context: { environmentId: string; projectId: string } | null, - projects: ReadonlyArray>, + projects: ReadonlyArray< + Pick + >, configLoaded: (environmentId: EnvironmentId) => boolean, ) { if (!context) return null; diff --git a/apps/mobile/src/state/server.ts b/apps/mobile/src/state/server.ts index 085db658cd..bd00aecac0 100644 --- a/apps/mobile/src/state/server.ts +++ b/apps/mobile/src/state/server.ts @@ -19,6 +19,7 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt providerCatalogsOnDemand: true, providerCatalogDigests: true, providerStatusDeltas: true, + editorUpdates: true, omitRefreshedProviders: true, }); export const describeOutdatedServer = createOutdatedServerDescriptionCommand(connectionAtomRuntime); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 8825ae9c33..a73440fcd0 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -615,6 +615,7 @@ export interface OrchestratorV2Shape { readonly threadId?: ThreadId; readonly afterSequence?: number; readonly eventType?: OrchestrationV2DomainEvent["type"]; + readonly bounded?: boolean; }) => Stream.Stream; readonly streamDomainEvents: Stream.Stream; } @@ -20054,7 +20055,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ), ), streamStoredEventsFrom: (input) => - eventSink.stream({ ...input, bounded: true }).pipe( + eventSink.stream({ bounded: true, ...input }).pipe( Stream.mapError( (cause) => new OrchestratorDomainEventStreamError({ diff --git a/apps/server/src/peer/handoff/ThreadHandoff.test.ts b/apps/server/src/peer/handoff/ThreadHandoff.test.ts index e44bdbd64f..9b6773ab48 100644 --- a/apps/server/src/peer/handoff/ThreadHandoff.test.ts +++ b/apps/server/src/peer/handoff/ThreadHandoff.test.ts @@ -1213,3 +1213,108 @@ it.live("settling a thread with no move reads no runs or messages", () => }), ).pipe(Effect.provide(layerTestHost)), ); + +it.live( + "settles a pending move whose turn ends while startup is still settling another thread", + () => + Effect.scoped( + Effect.gen(function* () { + const { root, laptopRepo, boxRepo } = yield* makeRepos; + const turns = yield* Ref.make>([]); + const releases = yield* Queue.unbounded(); + const packing = yield* Deferred.make(); + const releasePack = yield* Deferred.make(); + const b = yield* serveBox(boxRepo, `${root}/box-state`, turns); + const a = yield* makeLaptop( + laptopRepo, + turns, + Queue.take(releases), + undefined, + Deferred.succeed(packing, undefined).pipe(Effect.andThen(Deferred.await(releasePack))), + ); + yield* linkTo(a.links, b, "full-access"); + + // Thread A was already departing before restart; thread B is mid-turn. + yield* Queue.offer(releases, undefined); + yield* seedThread(a, laptopRepo); + yield* a.orchestrator.dispatch({ + type: "thread.handoff.update", + commandId: CommandId.make("command:handoff:startup-departing"), + threadId, + expected: null, + handoff: { + state: "departing", + handoffId: "startup-a", + environmentId: box.environmentId, + label: "Box", + projectId: ProjectId.make("project:box"), + }, + }); + + const waitingThreadId = ThreadId.make("thread:handoff:waiting"); + yield* a.orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:create:waiting"), + threadId: waitingThreadId, + projectId: ProjectId.make("project:laptop"), + title: "Waiting thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: laptopRepo, + }); + yield* a.orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("command:send:waiting"), + threadId: waitingThreadId, + messageId: MessageId.make("message:waiting:1"), + text: "Finish while another move departs.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + }); + yield* until(a.orchestrator, waitingThreadId, (projection) => + projection.runs.some((run) => run.status === "running"), + ); + + yield* a.handoff.start_(); + // Startup is now blocked mid-depart on thread A before subscribing to live events. + yield* Deferred.await(packing); + + // Thread B's move is accepted and its turn finishes while startup settle is still running. + yield* a.orchestrator.dispatch({ + type: "thread.handoff.update", + commandId: CommandId.make("command:handoff:waiting-pending"), + threadId: waitingThreadId, + expected: null, + handoff: { + state: "pending", + handoffId: "startup-b", + environmentId: box.environmentId, + label: "Box", + projectId: ProjectId.make("project:box"), + acceptedAt: "2099-01-01T00:00:00.000Z", + }, + }); + yield* Queue.offer(releases, undefined); + yield* idle(a.orchestrator, waitingThreadId); + + // Let thread A's startup depart finish; thread B's already-ended turn must still settle. + yield* Deferred.succeed(releasePack, undefined); + yield* until( + a.orchestrator, + threadId, + (projection) => projection.thread.handoff?.state === "departed", + ); + yield* until( + a.orchestrator, + waitingThreadId, + (projection) => projection.thread.handoff?.state === "departed", + ); + }), + ).pipe(Effect.provide(layerTestHost)), +); diff --git a/apps/server/src/peer/handoff/ThreadHandoff.ts b/apps/server/src/peer/handoff/ThreadHandoff.ts index 94502ed276..07fe56b400 100644 --- a/apps/server/src/peer/handoff/ThreadHandoff.ts +++ b/apps/server/src/peer/handoff/ThreadHandoff.ts @@ -18,6 +18,7 @@ import { import * as Context from "effect/Context"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as DateTime from "effect/DateTime"; +import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; @@ -38,7 +39,7 @@ import * as ThreadManagement from "../../orchestration-v2/ThreadManagementServic import * as ServerEnvironment from "../../environment/ServerEnvironment.ts"; import * as ProjectService from "../../project/ProjectService.ts"; import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts"; -import { forkParked } from "../../serverActivation.ts"; +import { forkParked, ServerActivation } from "../../serverActivation.ts"; import * as PeerForwarding from "../PeerForwarding.ts"; import * as PeerLinks from "../PeerLinks.ts"; import * as HandoffGit from "./HandoffGit.ts"; @@ -962,39 +963,65 @@ const make = Effect.gen(function* () { Effect.ignoreCause({ log: true }), ); - const start_: ThreadHandoff["Service"]["start_"] = () => - forkParked( - Effect.gen(function* () { - // Moves a restart cut short, or that were waiting for a turn that ended meanwhile. - const shells = yield* projections.getShellSnapshot().pipe( - Effect.map((snapshot) => snapshot.threads), - Effect.orElseSucceed(() => []), - ); - yield* Effect.forEach( - shells.filter( - (shell) => shell.handoff?.state === "pending" || shell.handoff?.state === "departing", - ), - (shell) => settle(shell.id), - { discard: true }, - ); - yield* threads.streamDomainEvents.pipe( - Stream.filter( - (event) => - event.type === "run.updated" && - ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes( - event.payload.status, + const start_: ThreadHandoff["Service"]["start_"] = Effect.fn("ThreadHandoff.start_")( + function* () { + const snapshotReady = yield* Deferred.make(); + const activation = yield* ServerActivation; + yield* forkParked( + Effect.gen(function* () { + // Moves a restart cut short, or that were waiting for a turn that ended meanwhile. + // Snapshot rows and snapshotSequence share one transaction, so streaming after that + // sequence catches any turn that finishes while startup settles are still running. + const snapshot = yield* projections.getShellSnapshot().pipe( + Effect.asSome, + Effect.orElseSucceed(() => Option.none()), + ); + yield* Deferred.succeed(snapshotReady, undefined); + if (Option.isSome(snapshot)) { + yield* Effect.forEach( + snapshot.value.threads.filter( + (shell) => + shell.handoff?.state === "pending" || shell.handoff?.state === "departing", ), - ), - Stream.map((event) => event.threadId), - Stream.merge( - Stream.tick("30 seconds").pipe( - Stream.flatMap(() => Stream.fromIterable([...recovering.keys()])), + (shell) => settle(shell.id), + { discard: true }, + ); + } + const runEvents = Option.isSome(snapshot) + ? threads + .streamStoredEventsFrom({ + afterSequence: snapshot.value.snapshotSequence, + eventType: "run.updated", + bounded: false, + }) + .pipe(Stream.map((stored) => stored.event)) + : threads.streamDomainEvents; + yield* runEvents.pipe( + Stream.filter( + (event) => + event.type === "run.updated" && + ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes( + event.payload.status, + ), ), - ), - Stream.runForEach(settle), - ); - }).pipe(Effect.ignoreCause({ log: true })), - ); + Stream.map((event) => event.threadId), + Stream.merge( + Stream.tick("30 seconds").pipe( + Stream.flatMap(() => Stream.fromIterable([...recovering.keys()])), + ), + ), + Stream.runForEach(settle), + ); + }).pipe( + Effect.ensuring(Deferred.succeed(snapshotReady, undefined)), + Effect.ignoreCause({ log: true }), + ), + ); + if (activation === undefined) { + yield* Deferred.await(snapshotReady); + } + }, + ); return ThreadHandoff.of({ options, propose, start, cancel, adopt, start_, settle }); }); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index e1ca70c253..88809fc243 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -947,6 +947,23 @@ const layerMakeRoutes = Layer.mergeAll( Layer.effectDiscard( ThreadHandoff.ThreadHandoff.pipe(Effect.flatMap((handoff) => handoff.start_())), ), + // Warm editor discovery on startup so the first client snapshot usually carries editors already. + Layer.effectDiscard( + ExternalLauncher.ExternalLauncher.pipe( + Effect.flatMap((launcher) => + ServerActivation.forkParked( + launcher.resolveAvailableEditors().pipe( + Effect.flatMap((editors) => + editors.includes("file-manager") + ? launcher.resolveFileManagerRevealKind().pipe(Effect.asVoid) + : Effect.void, + ), + Effect.ignore, + ), + ), + ), + ), + ), ) .pipe( Layer.provide( diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 8a467f1335..d3f64070fa 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -256,6 +256,48 @@ it.effect("resends late editors without rolling back updates already sent", () = }), ); +it.effect( + "sends an editorsUpdated delta instead of a second snapshot when the client opts in", + () => + Effect.gen(function* () { + const targets = [{ kind: "mdns" as const, host: "test.local" }]; + const editorsSent = yield* Deferred.make(); + const events = yield* withLateConfigDiscovery( + snapshotConfig({ settings: { enableProviderUpdateChecks: true } as never }), + Stream.empty, + { + resolveAvailableEditors: () => Effect.succeed(["cursor", "file-manager"]), + resolveFileManagerRevealKind: () => Effect.succeed("finder"), + }, + { resolveTargets: () => Deferred.await(editorsSent).pipe(Effect.as(targets)) }, + { resolve: () => Effect.succeed([]) }, + { editorUpdates: true }, + ).pipe( + Stream.tap((event) => + event.type === "editorsUpdated" ? Deferred.succeed(editorsSent, undefined) : Effect.void, + ), + Stream.runCollect, + ); + + const [editorsEvent, remoteSnapshot] = Array.from(events); + assert.equal(events.length, 2); + assert.equal(editorsEvent?.type, "editorsUpdated"); + if (editorsEvent?.type === "editorsUpdated") { + assert.deepEqual(editorsEvent.payload, { + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "finder", + }); + } + assert.equal(remoteSnapshot?.type, "snapshot"); + if (remoteSnapshot?.type === "snapshot") { + assert.deepEqual(remoteSnapshot.config.availableEditors, ["cursor", "file-manager"]); + assert.equal(remoteSnapshot.config.shellRevealInFileManagerKind, "finder"); + assert.deepEqual(remoteSnapshot.config.remoteOpenTargets, targets); + } + }), +); + it.effect("resends a reveal kind and remote targets that outlast the snapshot timeout", () => Effect.gen(function* () { const targets = [{ kind: "mdns" as const, host: "test.local" }]; diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index e836c43b08..54a1e7016a 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -360,6 +360,7 @@ export const withLateConfigDiscovery = ( launcher: EditorDiscovery, remoteOpenTargets: RemoteOpenTargets.RemoteOpenTargets["Service"], directEndpoints: Pick, + options?: { readonly editorUpdates?: boolean }, ) => { const lateEditorConfig = Stream.fromEffect(launcher.resolveAvailableEditors()).pipe( Stream.filter( @@ -408,7 +409,14 @@ export const withLateConfigDiscovery = ( ...rest } = current; const next = { ...rest, ...event.editorConfig }; - return [next, [{ version: 1, type: "snapshot", config: next }]]; + return [ + next, + [ + options?.editorUpdates === true + ? { version: 1, type: "editorsUpdated", payload: event.editorConfig } + : { version: 1, type: "snapshot", config: next }, + ], + ]; } case "remoteOpenTargetsResolved": { const next = { ...current, remoteOpenTargets: event.targets }; @@ -3750,6 +3758,7 @@ export const layerWsRpc = ( resolveTargets: () => Fiber.join(remoteTargets), }, { resolve: () => Fiber.join(directResult) }, + { editorUpdates: input.editorUpdates === true }, ); return Stream.concat( rpcInitialItems([ diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index 054226c195..d145a119d9 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -34,6 +34,9 @@ import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; import { AppRoot } from "~/AppRoot"; +import { openCommandPalette } from "~/commandPaletteBus"; +import { useCommandPaletteThreadActions } from "~/components/CommandPaletteThreadActions"; +import { I18nProvider } from "~/i18n/I18nProvider"; // The route loads ChatView lazily, and its first transform (React Compiler over ~4k lines) // takes 6-11s; importing it here keeps that out of the test's timeout. import "~/components/ChatView"; @@ -54,7 +57,7 @@ import { startWorkspaceFocus } from "~/lib/workspaceFocus"; import { usePromptStashStore, writePromptStashStorageForTest } from "~/promptStashStore"; import { useRightPanelStore } from "~/rightPanelStore"; import { getRouter } from "~/router"; -import { appAtomRegistry } from "~/rpc/atomRegistry"; +import { AppAtomRegistryProvider, appAtomRegistry } from "~/rpc/atomRegistry"; import { getProjectFileQueryAtom } from "~/components/files/projectFilesQueryState"; import { environmentThreadDetails } from "~/state/threads"; import { @@ -1022,6 +1025,62 @@ it("opens the thread actions menu for an older settled thread the shell leaves o .toBeVisible(); }); +it("refreshes command palette thread actions when an older settled thread's family read lands", async () => { + await page.viewport(1400, 900); + const thread = { ...threadWithHistory("older-settled-palette", 1), olderSettled: true as const }; + using _environment = installFakeEnvironment([thread]); + using family = holdRpc( + ORCHESTRATION_V2_WS_METHODS.getThreadFamily, + Effect.sync(() => threadFamily(thread.id)), + ); + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + + const ref = scopeThreadRef(ENVIRONMENT_ID, thread.id); + function PaletteActionsProbe() { + const items = useCommandPaletteThreadActions({ + threadRef: ref, + projectCwd: "/workspace/render", + }); + return ( +
{items.map((item) => item.title).join("|")}
+ ); + } + + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + await using _app = await render(, { + // AppRoot brings its own router. + router: false, + }); + await using _probe = await render( + + + + + , + ); + await expect + .element(page.getByText("older-settled-palette: question 0"), { timeout: 5_000 }) + .toBeVisible(); + await family.called; + await expect.element(page.getByTestId("palette-thread-actions")).toHaveTextContent(""); + openCommandPalette({ query: "Pin thread" }); + await expect.element(page.getByRole("option", { name: "Pin thread" })).not.toBeInTheDocument(); + + family.release(); + await expect + .element(page.getByTestId("palette-thread-actions"), { timeout: 5_000 }) + .toMatchTextContent(/Pin thread/); + await expect + .element(page.getByRole("option", { name: /Pin thread/ }), { timeout: 5_000 }) + .toBeVisible(); +}); + it("retains each thread's diff selection when returning from another thread or Settings", async () => { await page.viewport(1400, 900); const a = threadWithHistory("diff-selection-a", 1); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index bf1634f972..4690ee935e 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -846,7 +846,11 @@ function OpenCommandPaletteDialog(props: { ); const currentProjectCwd = currentProject?.workspaceRoot ?? null; const currentThreadActionItems = useCommandPaletteThreadActions({ - threadRef: activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null, + threadRef: activeThread + ? scopeThreadRef(activeThread.environmentId, activeThread.id) + : paletteRouteTarget?.kind === "server" + ? paletteRouteTarget.threadRef + : null, projectCwd: currentProjectCwd, }); const currentProjectCwdForBrowse = diff --git a/apps/web/src/components/CommandPaletteThreadActions.tsx b/apps/web/src/components/CommandPaletteThreadActions.tsx index a9aa344f58..47328b1ee6 100644 --- a/apps/web/src/components/CommandPaletteThreadActions.tsx +++ b/apps/web/src/components/CommandPaletteThreadActions.tsx @@ -1,4 +1,13 @@ -import type { ContextMenuItem, KeybindingCommand, ScopedThreadRef } from "@onicode/contracts"; +import { useAtomValue } from "@effect/atom-react"; +import type { EnvironmentServerConfig } from "@onicode/client-runtime/connection"; +import { scopeProjectRef } from "@onicode/client-runtime/environment"; +import { + AuthOrchestrationOperateScope, + type ContextMenuItem, + type KeybindingCommand, + type ScopedThreadRef, +} from "@onicode/contracts"; +import { Atom } from "effect/reactivity"; import { ArchiveIcon, CircleCheckIcon, @@ -21,6 +30,10 @@ import { } from "~/icons"; import { useThreadActionMenu } from "../hooks/useThreadActionMenu"; +import { canTurnThreadShellIntoProject } from "../hooks/useThreadActions"; +import { useProject, useQuietThreadShell, useServerConfig } from "../state/entities"; +import { useEnvironmentScope, useEnvironmentScopeDenied } from "../state/session"; +import { canMoveThreadsAtom } from "../state/threadHandoff"; import { ADDON_ICON_CLASS, ITEM_ICON_CLASS, @@ -60,13 +73,52 @@ const SHORTCUTS: Partial> = { "regenerate-title": "thread.regenerateTitle", }; +const FALSE_ATOM = Atom.make(false); + +const isConfigLoaded = (config: EnvironmentServerConfig | undefined) => config !== undefined; +const supportsAutoSettleOptOut = (config: EnvironmentServerConfig | undefined) => + config?.environment.capabilities.threadAutoSettleOptOut === true; +const supportsProjectFromScratch = (config: EnvironmentServerConfig | undefined) => + config?.environment.capabilities.threadProjectFromScratch === true; +const selectScratchWorkspaceRoot = (config: EnvironmentServerConfig | undefined) => + config?.scratchWorkspaceRoot ?? null; + /** The open thread's menu actions (settle, pin, snooze, archive...) as palette rows. */ export function useCommandPaletteThreadActions(input: { readonly threadRef: ScopedThreadRef | null; readonly projectCwd: string | null; }): Array { + const { threadRef } = input; + const environmentId = threadRef?.environmentId ?? null; + const thread = useQuietThreadShell(threadRef); + const project = useProject( + thread === null ? null : scopeProjectRef(thread.environmentId, thread.projectId), + ); + const configLoaded = useServerConfig(environmentId, isConfigLoaded); + const autoSettleOptOut = useServerConfig(environmentId, supportsAutoSettleOptOut); + const projectFromScratchSupported = useServerConfig(environmentId, supportsProjectFromScratch); + const scratchWorkspaceRoot = useServerConfig(environmentId, selectScratchWorkspaceRoot); + const canOperate = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const canTriage = !useEnvironmentScopeDenied(environmentId, AuthOrchestrationOperateScope); + const canMoveThreads = useAtomValue( + environmentId === null ? FALSE_ATOM : canMoveThreadsAtom(environmentId), + ); + const canTurnIntoProject = canTurnThreadShellIntoProject({ + thread, + project, + supportsProjectFromScratch: projectFromScratchSupported, + scratchWorkspaceRoot, + }); const { readMenu } = useThreadActionMenu(input); - const menu = readMenu(); + const menu = readMenu({ + thread, + configLoaded, + autoSettleOptOut, + canOperate, + canTriage, + canMoveThreads, + canTurnIntoProject, + }); if (!menu) return []; const toPaletteItem = ( diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.ts index e0ac477d47..dc18acc83f 100644 --- a/apps/web/src/connection/runtime.ts +++ b/apps/web/src/connection/runtime.ts @@ -41,6 +41,7 @@ const layerProvidedClientConnection = layerSnapshotLoader.pipe( usageLimitSources: true, hostPressure: true, usageLimitsCommand: true, + editorUpdates: true, }), ), Layer.provideMerge( diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts index ad1d05b49f..84560df85e 100644 --- a/apps/web/src/hooks/useThreadActionMenu.ts +++ b/apps/web/src/hooks/useThreadActionMenu.ts @@ -8,6 +8,7 @@ import { squashAtomCommandFailure, } from "@onicode/client-runtime/state/runtime"; import { canSnooze, effectiveSnoozed } from "@onicode/client-runtime/state/thread-settled"; +import type { EnvironmentThreadShell } from "@onicode/client-runtime/state/shell"; import { AuthOrchestrationOperateScope, type ScopedThreadRef, @@ -69,6 +70,17 @@ function failureToast(title: string, error: unknown) { ); } +/** Reactive snapshot passed by render-time callers so `readMenu` stays pure. */ +export interface ThreadActionMenuSnapshot { + readonly thread: EnvironmentThreadShell | null; + readonly configLoaded: boolean; + readonly autoSettleOptOut: boolean; + readonly canOperate: boolean; + readonly canTriage: boolean; + readonly canMoveThreads: boolean; + readonly canTurnIntoProject: boolean; +} + export function useThreadActionMenu(input: { readonly threadRef: ScopedThreadRef | null; readonly projectCwd: string | null; @@ -132,15 +144,18 @@ export function useThreadActionMenu(input: { }); /** The thread's menu as of now, and a runner for its actions. Null until the thread loads. */ - const readMenu = () => { + const readMenu = (snapshot?: ThreadActionMenuSnapshot) => { if (threadRef === null) return null; - const thread = readThreadShell(threadRef); + const thread = snapshot !== undefined ? snapshot.thread : readThreadShell(threadRef); if (!thread) return null; const now = new Date(); - const configLoaded = readEnvironmentServerConfigLoaded(threadRef.environmentId); + const configLoaded = + snapshot?.configLoaded ?? readEnvironmentServerConfigLoaded(threadRef.environmentId); const supports = { settlement: configLoaded, - autoSettleOptOut: readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId), + autoSettleOptOut: + snapshot?.autoSettleOptOut ?? + readEnvironmentSupportsAutoSettleOptOut(threadRef.environmentId), snooze: configLoaded, pinning: configLoaded, titleRegeneration: configLoaded, @@ -148,8 +163,10 @@ export function useThreadActionMenu(input: { const isRegeneratingTitle = thread.titleRegeneration != null; const snoozePresets = resolveSnoozePresets(now, timestampFormat, threadRef.environmentId); const items = buildThreadActionMenuItems({ - canOperate: readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), - canTriage: threadTriagePermitted(threadRef.environmentId), + canOperate: + snapshot?.canOperate ?? + readEnvironmentScope(threadRef.environmentId, AuthOrchestrationOperateScope), + canTriage: snapshot?.canTriage ?? threadTriagePermitted(threadRef.environmentId), canFind: onFind !== undefined, canRename: onStartRename !== undefined, branch: thread.branch ?? null, @@ -165,8 +182,9 @@ export function useThreadActionMenu(input: { supports, snoozePresets, canContinueElsewhere: - threadCanStartHandoff(thread.handoff) && readCanMoveThreads(threadRef.environmentId), - canTurnIntoProject: canTurnThreadIntoProject(threadRef), + threadCanStartHandoff(thread.handoff) && + (snapshot?.canMoveThreads ?? readCanMoveThreads(threadRef.environmentId)), + canTurnIntoProject: snapshot?.canTurnIntoProject ?? canTurnThreadIntoProject(threadRef), }); const run = async (action: ThreadActionMenuId) => { const api = readLocalApi(); diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 316a5997d0..88bc5cc799 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -30,6 +30,10 @@ import { environmentSession, readEnvironmentScope } from "../state/session"; import { appAtomRegistry } from "../rpc/atomRegistry"; import { environmentServerConfigsAtom } from "../state/server"; import { isScratchProject } from "@onicode/client-runtime/state/projects"; +import type { + EnvironmentProject, + EnvironmentThreadShell, +} from "@onicode/client-runtime/state/shell"; import { orchestrationEnvironment } from "../state/orchestration"; import { projectEnvironment } from "../state/projects"; import { threadEnvironment } from "../state/threads"; @@ -281,18 +285,33 @@ function clearDeletedThreadPanelState(ref: ScopedThreadRef) { usePreviewMiniPlayerStore.getState().removeThread(ref); } +/** Pure predicate shared between imperative menus and reactive palette items. */ +export function canTurnThreadShellIntoProject(input: { + readonly thread: Pick | null; + readonly project: Pick | null; + readonly supportsProjectFromScratch: boolean; + readonly scratchWorkspaceRoot: string | null | undefined; +}): boolean { + if (!input.thread?.worktreePath || !input.supportsProjectFromScratch || input.project === null) { + return false; + } + return isScratchProject(input.project, input.scratchWorkspaceRoot ?? undefined); +} + /** A No project thread that already has its own folder, on a server that can promote it. */ export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean { const thread = readThreadShell(threadRef); const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId); - if (!thread?.worktreePath || config?.environment.capabilities.threadProjectFromScratch !== true) { - return false; - } - const project = readProject({ - environmentId: threadRef.environmentId, - projectId: thread.projectId, + if (!thread) return false; + return canTurnThreadShellIntoProject({ + thread, + project: readProject({ + environmentId: threadRef.environmentId, + projectId: thread.projectId, + }), + supportsProjectFromScratch: config?.environment.capabilities.threadProjectFromScratch === true, + scratchWorkspaceRoot: config?.scratchWorkspaceRoot, }); - return project !== null && isScratchProject(project, config.scratchWorkspaceRoot); } function threadOperationFailure(target: ScopedThreadRef) { diff --git a/apps/web/src/lib/openPullRequestLink.browser.test.tsx b/apps/web/src/lib/openPullRequestLink.browser.test.tsx index b481202e5a..04c3b1a092 100644 --- a/apps/web/src/lib/openPullRequestLink.browser.test.tsx +++ b/apps/web/src/lib/openPullRequestLink.browser.test.tsx @@ -200,9 +200,15 @@ it("opens a pull request linked on the Issues page beside its issues", async () expect(screen.router?.state.location.pathname).toBe("/issues"); }); -it("opens a thread's pull request beside it when its project is a folder with no remote", async () => { +it("opens a thread's pull request beside it only when its remote-less project tracks folders", async () => { setup(); - state.projects = [{ ...project, repositoryIdentity: null }]; + state.projects = [ + { + ...project, + repositoryIdentity: null, + trackedFolders: [{ path: "/repo/effect", name: "effect" }], + }, + ]; await using screen = await render( @@ -214,4 +220,19 @@ it("opens a thread's pull request beside it when its project is a folder with no surfaces: [{ kind: "pull-request", projectId: "project", number: 86 }], }); expect(state.openLink).not.toHaveBeenCalled(); + + setup(); + state.projects = [{ ...project, repositoryIdentity: null }]; + const defaults: boolean[] = []; + screen.container.addEventListener( + "click", + (nativeEvent) => { + defaults.push(nativeEvent.defaultPrevented); + nativeEvent.preventDefault(); + }, + { once: true }, + ); + await screen.getByRole("link", { name: "Pull request" }).click(); + expect(defaults).toEqual([false]); + expect(useRightPanelStore.getState().byThreadKey).toEqual({}); }); diff --git a/apps/web/src/state/server.ts b/apps/web/src/state/server.ts index dbe6eec97f..851be695b7 100644 --- a/apps/web/src/state/server.ts +++ b/apps/web/src/state/server.ts @@ -36,6 +36,7 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt usageLimitSources: true, hostPressure: true, usageLimitsCommand: true, + editorUpdates: true, }); export const environmentUpdateStatesAtom = environmentAtomList( "web-environment-update-states", diff --git a/packages/client-runtime/src/changeRequestLinks.test.ts b/packages/client-runtime/src/changeRequestLinks.test.ts index b4c1d00ea6..3a6ff3feeb 100644 --- a/packages/client-runtime/src/changeRequestLinks.test.ts +++ b/packages/client-runtime/src/changeRequestLinks.test.ts @@ -140,8 +140,13 @@ describe("resolveChangeRequestLinkTarget", () => { ).toBeNull(); }); - it("opens a thread's pull request under its own multi-repo folder project, which has no remote", () => { - const folder = { id: ProjectId.make("folder"), environmentId: local, repositoryIdentity: null }; + it("opens a thread's pull request under its own multi-repo folder project, not a plain folder", () => { + const folder = { + id: ProjectId.make("folder"), + environmentId: local, + repositoryIdentity: null, + trackedFolders: [{ path: "/folder/app", name: "app" }], + }; expect( resolveChangeRequestLinkTarget({ url, @@ -152,6 +157,27 @@ describe("resolveChangeRequestLinkTarget", () => { lendHostProject: true, }), ).toEqual({ project: folder, host: "github.com", repository: "acme/app", number: 7 }); + + for (const plain of [ + { id: ProjectId.make("plain"), environmentId: local, repositoryIdentity: null }, + { + id: ProjectId.make("empty-tracked"), + environmentId: local, + repositoryIdentity: null, + trackedFolders: [], + }, + ]) { + expect( + resolveChangeRequestLinkTarget({ + url, + projects: [plain], + configLoaded: loaded, + environmentId: local, + projectId: plain.id, + lendHostProject: true, + }), + ).toBeNull(); + } }); it("finds the checked-out repository in any environment that reads change requests", () => { diff --git a/packages/client-runtime/src/changeRequestLinks.ts b/packages/client-runtime/src/changeRequestLinks.ts index a078dee8aa..f2cb843a39 100644 --- a/packages/client-runtime/src/changeRequestLinks.ts +++ b/packages/client-runtime/src/changeRequestLinks.ts @@ -13,6 +13,7 @@ interface ChangeRequestProject { readonly id: ProjectId; readonly environmentId: EnvironmentId; readonly repositoryIdentity?: RepositoryIdentity | null | undefined; + readonly trackedFolders?: ReadonlyArray | null | undefined; } /** The project whose own repository holds the change request, not just one on its host. */ @@ -94,7 +95,12 @@ export function resolveChangeRequestLinkTarget candidate.id === projectId && !candidate.repositoryIdentity)) + candidates.find( + (candidate) => + candidate.id === projectId && + !candidate.repositoryIdentity && + (candidate.trackedFolders?.length ?? 0) > 0, + )) : undefined); if (project === undefined || !configLoaded(project.environmentId)) return null; return { diff --git a/packages/client-runtime/src/rpc/session.test.ts b/packages/client-runtime/src/rpc/session.test.ts index daa82510b0..16d421b7cc 100644 --- a/packages/client-runtime/src/rpc/session.test.ts +++ b/packages/client-runtime/src/rpc/session.test.ts @@ -913,7 +913,22 @@ describe("RpcSessionFactory", () => { providers: [{ ...status, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }], }, }; - const allEvents = [providerEvent, ...themeEvents, ...sourceEvents, ...settingsEvents]; + const editorsEvent: ServerConfigStreamEventType = { + version: 1, + type: "editorsUpdated", + payload: { + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "finder", + }, + }; + const allEvents = [ + providerEvent, + editorsEvent, + ...themeEvents, + ...sourceEvents, + ...settingsEvents, + ]; const observedByFastSubscriber = yield* Queue.unbounded(); yield* session .subscribeServerConfig({ environmentThemes: true, usageLimitSources: true }) @@ -937,6 +952,9 @@ describe("RpcSessionFactory", () => { ]); expect(recovered[1]).toMatchObject({ config: { + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "finder", providers: [{ ...PROVIDER, checkedAt: "2026-04-10T00:05:00.000Z", message: "Checked" }], }, }); diff --git a/packages/client-runtime/src/rpc/session.ts b/packages/client-runtime/src/rpc/session.ts index 53c6cb16df..b001c0b696 100644 --- a/packages/client-runtime/src/rpc/session.ts +++ b/packages/client-runtime/src/rpc/session.ts @@ -89,6 +89,7 @@ export interface RpcSessionOptions { readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + readonly editorUpdates?: boolean; readonly pingInterval?: Duration.Input; readonly onInitialConfig?: () => void; } @@ -208,6 +209,7 @@ export const make = Effect.fn("RpcSessionFactory.make")(function* ( ...(options.providerCatalogsOnDemand === true ? { providerCatalogsOnDemand: true } : {}), ...(options.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}), ...(options.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}), + ...(options.editorUpdates === true ? { editorUpdates: true } : {}), }; // Config state merges the snapshots it fetches back in, so no subscriber needs them broadcast. const onDemandSnapshots = (input: ServerConfigSubscriptionInput) => ({ diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index cca51a6ff3..2ab57cbe4e 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -468,6 +468,7 @@ export interface ServerConfigSubscriptionOptions { readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + readonly editorUpdates?: boolean; } type ServerProviderEntry = ServerConfig["providers"][number]; @@ -667,6 +668,7 @@ export const makeEnvironmentServerConfigState = Effect.fn("EnvironmentServerConf ...(subscription.providerCatalogsOnDemand === true ? { providerCatalogsOnDemand: true } : {}), ...(subscription.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}), ...(subscription.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}), + ...(subscription.editorUpdates === true ? { editorUpdates: true } : {}), }).pipe( Stream.map((event): Update => (current) => { const next = applyServerConfigProjection(current, event); @@ -976,6 +978,7 @@ export function createServerEnvironmentAtoms( readonly providerCatalogsOnDemand?: boolean; readonly providerCatalogDigests?: boolean; readonly providerStatusDeltas?: boolean; + readonly editorUpdates?: boolean; /** Machine refresh replies carry no providers; the config stream already delivers them. */ readonly omitRefreshedProviders?: boolean; }, @@ -1008,6 +1011,7 @@ export function createServerEnvironmentAtoms( : {}), ...(options.providerCatalogDigests === true ? { providerCatalogDigests: true } : {}), ...(options.providerStatusDeltas === true ? { providerStatusDeltas: true } : {}), + ...(options.editorUpdates === true ? { editorUpdates: true } : {}), }, // Scoped to the stream, which restarts with every new session. AtomRegistry.toStream(get.registry, fetchedMachineCatalogsAtom(environmentId)), diff --git a/packages/client-runtime/src/state/serverConfigProjection.test.ts b/packages/client-runtime/src/state/serverConfigProjection.test.ts index 6e20572b2c..29a816276d 100644 --- a/packages/client-runtime/src/state/serverConfigProjection.test.ts +++ b/packages/client-runtime/src/state/serverConfigProjection.test.ts @@ -170,3 +170,42 @@ describe("applyServerConfigProjection hostPressureUpdated", () => { expect(Option.getOrThrow(ended).config.hostPressure).toBeUndefined(); }); }); + +describe("applyServerConfigProjection editorsUpdated", () => { + it("applies late editor discovery without replacing the rest of the config", () => { + const initial = applyServerConfigProjection(Option.none(), { + type: "snapshot", + version: 1, + config: { + availableEditors: [], + providers: [], + settings: { defaultAutoPull: true }, + environment: { capabilities: {} }, + }, + } as unknown as ServerConfigStreamEvent); + const updated = applyServerConfigProjection(initial, { + type: "editorsUpdated", + version: 1, + payload: { + availableEditors: ["cursor", "file-manager"], + shellRevealInFileManager: true, + shellRevealInFileManagerKind: "finder", + }, + } as ServerConfigStreamEvent); + const resolved = Option.getOrThrow(updated); + expect(resolved.config.availableEditors).toEqual(["cursor", "file-manager"]); + expect(resolved.config.shellRevealInFileManager).toBe(true); + expect(resolved.config.shellRevealInFileManagerKind).toBe("finder"); + expect(resolved.config.settings).toEqual({ defaultAutoPull: true }); + + const cleared = applyServerConfigProjection(updated, { + type: "editorsUpdated", + version: 1, + payload: { availableEditors: ["cursor"] }, + } as ServerConfigStreamEvent); + const clearedConfig = Option.getOrThrow(cleared).config; + expect(clearedConfig.availableEditors).toEqual(["cursor"]); + expect(clearedConfig.shellRevealInFileManager).toBeUndefined(); + expect(clearedConfig.shellRevealInFileManagerKind).toBeUndefined(); + }); +}); diff --git a/packages/client-runtime/src/state/serverConfigProjection.ts b/packages/client-runtime/src/state/serverConfigProjection.ts index d1dedf10fe..10c1aabc78 100644 --- a/packages/client-runtime/src/state/serverConfigProjection.ts +++ b/packages/client-runtime/src/state/serverConfigProjection.ts @@ -216,5 +216,29 @@ export function applyServerConfigProjection( latestEvent: event, source: "live", })); + case "editorsUpdated": + return Option.map(current, (projection) => { + const { + availableEditors: _editors, + shellRevealInFileManager: _reveal, + shellRevealInFileManagerKind: _revealKind, + ...rest + } = projection.config; + const nextConfig: ServerConfig = { + ...rest, + availableEditors: event.payload.availableEditors, + ...(event.payload.shellRevealInFileManager === undefined + ? {} + : { shellRevealInFileManager: event.payload.shellRevealInFileManager }), + ...(event.payload.shellRevealInFileManagerKind === undefined + ? {} + : { shellRevealInFileManagerKind: event.payload.shellRevealInFileManagerKind }), + }; + return { + config: reuseUnchanged(projection.config, nextConfig), + latestEvent: event, + source: "live", + }; + }); } } diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 3fa052cdbc..a9898337b5 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -1216,15 +1216,6 @@ describe("environment shell cold start", () => { const makeColdStart = Effect.fn("test.makeColdStartShell")(function* ( origin: Persistence.ShellCacheOrigin | undefined, - // Set for a connection that is prepared but has no session yet. - // Each held load waits for one `releaseLoads`. An "uninterruptible" hold stands for a load - // that applies its answer, which an interrupt has to wait for. - early?: { - readonly serverResumes: boolean; - readonly holdLoads?: boolean | "uninterruptible"; - readonly snapshotSequence?: number; - readonly emptyCache?: boolean; - }, ) { yield* TestClock.setTime(NOW); const subscriptions = yield* Queue.unbounded<{ @@ -1236,18 +1227,6 @@ describe("environment shell cold start", () => { readonly origin: Persistence.ShellCacheOrigin | undefined; }>(); const httpLoads = yield* Ref.make(0); - const loadOptions = yield* Queue.unbounded(); - const releases = yield* Queue.unbounded(); - const scope = yield* Effect.scope; - const holdLoad = - early?.holdLoads === "uninterruptible" - ? // Registered after the load's fiber, so the end of a failed test does not wait for it. - Scope.addFinalizer(scope, Queue.shutdown(releases)).pipe( - Effect.andThen(Effect.uninterruptible(Queue.take(releases))), - ) - : early?.holdLoads === true - ? Queue.take(releases) - : Effect.void; const client = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: unknown) => Stream.unwrap( @@ -1258,12 +1237,8 @@ describe("environment shell cold start", () => { }), ), } as unknown as WsRpcProtocolClient; - const activeSession = yield* SubscriptionRef.make( - early === undefined ? Option.some(session(client)) : Option.none(), - ); - const prepared = yield* SubscriptionRef.make( - Option.some(early === undefined ? PREPARED : { ...PREPARED, descriptor: FAMILY_DESCRIPTOR }), - ); + const activeSession = yield* SubscriptionRef.make(Option.some(session(client))); + const prepared = yield* SubscriptionRef.make(Option.some(PREPARED)); const connectionState = yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE); const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: TARGET, @@ -1277,13 +1252,11 @@ describe("environment shell cold start", () => { } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); const cache = Persistence.EnvironmentCacheStore.of({ loadShell: () => - early?.emptyCache === true - ? Effect.succeedNone - : Effect.succeedSome({ - ...v2ShellSnapshot, - snapshotSequence: CACHED_SEQUENCE, - ...(origin === undefined ? {} : { origin }), - }), + Effect.succeedSome({ + ...v2ShellSnapshot, + snapshotSequence: CACHED_SEQUENCE, + ...(origin === undefined ? {} : { origin }), + }), saveShell: (_environmentId, snapshot, origin?: Persistence.ShellCacheOrigin) => Queue.offer(saved, { snapshot, origin }).pipe(Effect.asVoid), loadThread: () => Effect.succeedNone, @@ -1298,20 +1271,14 @@ describe("environment shell cold start", () => { clear: () => Effect.void, }); const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({ - load: (_prepared, options = {}) => - Queue.offer(loadOptions, options).pipe( - Effect.andThen(holdLoad), - Effect.andThen(Ref.updateAndGet(httpLoads, (count) => count + 1)), + load: () => + Ref.updateAndGet(httpLoads, (count) => count + 1).pipe( Effect.map((count) => - Option.some( - early?.serverResumes === true && options.resumeFrom !== undefined - ? { resumable: true } - : { - ...v2ShellSnapshot, - snapshotSequence: (early?.snapshotSequence ?? HTTP_SEQUENCE) + count - 1, - projectIdentities: `identities-${count}`, - }, - ), + Option.some({ + ...v2ShellSnapshot, + snapshotSequence: HTTP_SEQUENCE + count - 1, + projectIdentities: `identities-${count}`, + }), ), ), }); @@ -1324,12 +1291,6 @@ describe("environment shell cold start", () => { report: (event) => Queue.offerUnsafe(reports, event), }), ); - const nextConnection = Effect.suspend(() => - SubscriptionRef.set( - prepared, - Option.some({ ...PREPARED, descriptor: { ...FAMILY_DESCRIPTOR } }), - ), - ); return { shellState, subscriptions, @@ -1342,34 +1303,7 @@ describe("environment shell cold start", () => { }), saved, httpLoads, - loadOptions, - releaseLoads: Queue.offer(releases, undefined), - nextConnection, - // A connection attempt that ended, then the next one. - prepareAgain: SubscriptionRef.set(prepared, Option.none()).pipe( - Effect.andThen(nextConnection), - ), - // Resolves `configRead` when the subscription reads the config, just before it claims the load. - connect: (config: object, configRead?: Deferred.Deferred) => - SubscriptionRef.set( - activeSession, - Option.some({ - ...session(client), - initialConfig: (configRead === undefined - ? Effect.void - : Deferred.succeed(configRead, undefined) - ).pipe(Effect.as(config as never)), - }), - ), reconnect: SubscriptionRef.set(activeSession, Option.some(session(client))), - // The registry swaps a rotated bearer into the prepared connection of a live session. - rotateCredential: SubscriptionRef.update( - prepared, - Option.map((current) => ({ - ...current, - httpAuthorization: { _tag: "Bearer" as const, token: "rotated" }, - })), - ), liveAt: (sequence: number) => SubscriptionRef.changes(shellState).pipe( Stream.filter( @@ -1469,274 +1403,6 @@ describe("environment shell cold start", () => { }), ); - it.effect("associates a delayed HTTP bootstrap snapshot with the socket that claims it", () => - Effect.gen(function* () { - const h = yield* makeColdStart(undefined, { - serverResumes: false, - holdLoads: true, - snapshotSequence: CACHED_SEQUENCE, - }); - yield* Queue.take(h.loadOptions); - const configRead = yield* Deferred.make(); - yield* h.connect(FAMILY_CONFIG, configRead); - yield* Deferred.await(configRead); - // Let the socket claim the in-flight HTTP load before its answer is released. - yield* TestClock.adjust("1 millis"); - yield* h.releaseLoads; - const subscription = yield* Queue.take(h.subscriptions); - expect(subscription.input).toMatchObject({ afterSequence: CACHED_SEQUENCE }); - yield* Queue.offer(subscription.events, { kind: "synchronized" }); - const live = yield* h.liveAt(CACHED_SEQUENCE); - expect(live.commandHistory?.synchronizedSession).toBeDefined(); - expect(live.commandHistory?.rewind).toEqual({ - generation: live.generation, - session: live.commandHistory?.synchronizedSession, - bootstrap: true, - }); - }), - ); - - it.effect.each([ - { - label: "no rows to resume", - origin: undefined, - serverResumes: false, - config: FAMILY_CONFIG, - loads: [FAMILY_FLAGS], - subscribes: { afterSequence: HTTP_SEQUENCE, knownProjectIdentities: "identities-1" }, - }, - { - label: "rows the server can replay from", - origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, - serverResumes: true, - config: FAMILY_CONFIG, - loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], - subscribes: { afterSequence: CACHED_SEQUENCE, httpSnapshotFallback: true }, - }, - { - label: "rows the server cannot replay from", - origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, - serverResumes: false, - config: FAMILY_CONFIG, - loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], - subscribes: { afterSequence: HTTP_SEQUENCE, knownProjectIdentities: "identities-1" }, - }, - { - // The server answered that it can replay, then the rows passed their age limit. - label: "rows that expire before the socket is ready", - origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS, snapshotAt: NOW - 12 * HOUR + 1 }, - serverResumes: true, - config: FAMILY_CONFIG, - loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], - subscribes: {}, - expires: true, - }, - { - // The rows loaded with the descriptor's omissions are replaced, never kept. - label: "a live config with other omissions", - origin: undefined, - serverResumes: false, - config: { environment: { serverVersion: "1.0.0" } }, - loads: [FAMILY_FLAGS, { omitIdleSubagents: false, omitOlderSettled: false }], - subscribes: { afterSequence: HTTP_SEQUENCE + 1, knownProjectIdentities: "identities-2" }, - }, - ])( - "asks for the shell once the connection is prepared, with $label", - ({ origin, serverResumes, config, loads, subscribes, expires }) => - Effect.gen(function* () { - const h = yield* makeColdStart(origin, { serverResumes }); - expect(yield* Queue.take(h.loadOptions)).toEqual(loads[0]); - if (!serverResumes) { - // The rows are on screen before a socket exists, and are not live yet. - const early = yield* SubscriptionRef.changes(h.shellState).pipe( - Stream.filter((state) => - Option.exists( - state.snapshot, - (snapshot) => snapshot.snapshotSequence === HTTP_SEQUENCE, - ), - ), - Stream.runHead, - Effect.map(Option.getOrThrow), - ); - expect(early.status).not.toBe("live"); - expect(early.generation).toBeGreaterThan(0); - } - expect(yield* Queue.size(h.subscriptions)).toBe(0); - - if (expires) yield* TestClock.adjust("1 millis"); - yield* h.connect(config); - const first = yield* Queue.take(h.subscriptions); - expect(first.input).toMatchObject(subscribes); - for (const key of [ - "afterSequence", - "httpSnapshotFallback", - "knownProjectIdentities", - ] as const) { - if (!(key in subscribes)) expect(first.input).not.toHaveProperty(key); - } - expect(yield* Queue.clear(h.loadOptions)).toEqual(loads.slice(1)); - expect(yield* Ref.get(h.httpLoads)).toBe(loads.length); - // The socket sends the full snapshot these rows asked for; the rest needs a cursor. - if (!("afterSequence" in subscribes)) return; - - yield* Queue.offer(first.events, { kind: "synchronized" }); - yield* h.liveAt(subscribes.afterSequence); - if (loads.length > 1) { - yield* TestClock.adjust("500 millis"); - const saves = yield* Queue.takeAll(h.saved); - expect(saves.at(-1)).toMatchObject({ - snapshot: { snapshotSequence: subscribes.afterSequence }, - origin: { ...CURRENT_ORIGIN, snapshotAt: NOW }, - }); - } - - // A rotated credential keeps the session, so its events still apply and nothing reloads. - yield* h.rotateCredential; - yield* Queue.offer(first.events, { - kind: "thread.removed", - sequence: subscribes.afterSequence + 1, - location: "active", - threadId: ThreadId.make("no-such-thread"), - }); - yield* h.liveAt(subscribes.afterSequence + 1); - expect(yield* Ref.get(h.httpLoads)).toBe(loads.length); - }), - ); - - it.effect("a replaced session waits for the load its connection already started", () => - Effect.gen(function* () { - const h = yield* makeColdStart(undefined, { - serverResumes: false, - holdLoads: "uninterruptible", - }); - expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); - const claimed = yield* Deferred.make(); - yield* h.connect(FAMILY_CONFIG, claimed); - yield* Deferred.await(claimed); - // Lets the first subscription run on from its config read to its wait for the load. - yield* TestClock.adjust("1 millis"); - // The first subscription waits for the load. A second request could answer first, and - // the older answer would then replace its rows under a cursor the socket has passed. - yield* h.connect(FAMILY_CONFIG); - yield* TestClock.adjust("1 millis"); - expect(yield* Queue.size(h.loadOptions)).toBe(0); - - // The connection changes twice while the first load ends. The next session reads the - // last connection before its load exists, so it replaces the load of the one between. - yield* h.nextConnection; - yield* TestClock.adjust("1 millis"); - yield* h.nextConnection; - yield* h.connect(FAMILY_CONFIG); - yield* TestClock.adjust("1 millis"); - yield* h.releaseLoads; - expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); - yield* TestClock.adjust("1 millis"); - // That session is replaced while it waits for the load between to end. The load it then - // starts must stay the one load of the last connection. - yield* h.connect(FAMILY_CONFIG); - yield* TestClock.adjust("1 millis"); - yield* h.releaseLoads; - expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); - yield* TestClock.adjust("1 millis"); - expect(yield* Queue.size(h.loadOptions)).toBe(0); - - yield* h.releaseLoads; - const subscribed = yield* Queue.take(h.subscriptions); - expect(subscribed.input).toMatchObject({ afterSequence: HTTP_SEQUENCE }); - expect(yield* Queue.size(h.loadOptions)).toBe(0); - expect(yield* Ref.get(h.httpLoads)).toBe(1); - }), - ); - - it.effect("resumes held rows as soon as the socket is ready while HTTP is pending", () => - Effect.gen(function* () { - const h = yield* makeColdStart( - { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, - { serverResumes: false, holdLoads: true }, - ); - yield* Queue.take(h.loadOptions); - const claimed = yield* Deferred.make(); - yield* h.connect(FAMILY_CONFIG, claimed); - yield* Deferred.await(claimed); - const first = yield* Queue.take(h.subscriptions); - expect(first.input).toMatchObject({ - afterSequence: CACHED_SEQUENCE, - httpSnapshotFallback: true, - }); - yield* Queue.offer(first.events, { - kind: "thread.removed", - sequence: HTTP_SEQUENCE + 1, - location: "active", - threadId: ThreadId.make("no-such-thread"), - }); - yield* Queue.offer(first.events, { kind: "synchronized" }); - yield* h.liveAt(HTTP_SEQUENCE + 1); - - // The late answer is an older snapshot. It must not replace the rows the socket moved on. - yield* h.releaseLoads; - yield* TestClock.adjust("1 millis"); - expect(yield* Ref.get(h.httpLoads)).toBe(0); - expect(yield* SubscriptionRef.get(h.shellState)).toMatchObject({ - status: "live", - snapshot: Option.some({ snapshotSequence: HTTP_SEQUENCE + 1 }), - }); - }), - ); - - it.effect("takes a socket snapshot when the early HTTP load stalls without a usable cursor", () => - Effect.gen(function* () { - const h = yield* makeColdStart(undefined, { - serverResumes: false, - holdLoads: true, - emptyCache: true, - }); - yield* Queue.take(h.loadOptions); - const claimed = yield* Deferred.make(); - yield* h.connect(FAMILY_CONFIG, claimed); - yield* Deferred.await(claimed); - yield* TestClock.adjust("30 millis"); - const first = yield* Queue.take(h.subscriptions); - expect(first.input).toEqual({ ...FAMILY_FLAGS, requestCompletionMarker: true }); - yield* Queue.offerAll(first.events, [ - { kind: "snapshot", snapshot: { ...v2ShellSnapshot, snapshotSequence: HTTP_SEQUENCE + 1 } }, - { kind: "synchronized" }, - ]); - yield* h.liveAt(HTTP_SEQUENCE + 1); - - yield* h.releaseLoads; - yield* TestClock.adjust("1 millis"); - expect(yield* Ref.get(h.httpLoads)).toBe(0); - expect(yield* Queue.size(h.loadOptions)).toBe(0); - expect(yield* SubscriptionRef.get(h.shellState)).toMatchObject({ - status: "live", - snapshot: Option.some({ snapshotSequence: HTTP_SEQUENCE + 1 }), - }); - }), - ); - - it.effect("drops the load of a connection that ended and waits for the next one", () => - Effect.gen(function* () { - const h = yield* makeColdStart(undefined, { serverResumes: false, holdLoads: true }); - yield* Queue.take(h.loadOptions); - yield* h.prepareAgain; - yield* Queue.take(h.loadOptions); - - // The socket is ready while the second load is in flight. - yield* h.connect(FAMILY_CONFIG); - yield* h.releaseLoads; - const first = yield* Queue.take(h.subscriptions); - expect(first.input).toMatchObject({ - afterSequence: HTTP_SEQUENCE, - knownProjectIdentities: "identities-1", - }); - // The first load ended with its connection and never answered. - expect(yield* Ref.get(h.httpLoads)).toBe(1); - - yield* Queue.offer(first.events, { kind: "synchronized" }); - yield* h.liveAt(HTTP_SEQUENCE); - }), - ); - it.effect("resubscribes a connected shell whose completion marker never arrives", () => Effect.gen(function* () { const h = yield* makeColdStart(RECENT_ORIGIN); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 25cfdfdbff..3fff5e2eff 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -16,7 +16,6 @@ import * as Clock from "effect/Clock"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; -import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -24,7 +23,6 @@ import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; -import * as SynchronizedRef from "effect/SynchronizedRef"; import { AsyncResult, Atom } from "effect/reactivity"; import { observeServerTime } from "../clock.ts"; @@ -181,11 +179,6 @@ function shellIdentity( }; } -function sameConnection(left: PreparedConnection, right: PreparedConnection): boolean { - const keys = Object.keys({ ...left, ...right }) as Array; - return keys.every((key) => key === "httpAuthorization" || left[key] === right[key]); -} - /** Null for a server whose descriptor does not name its shell flags; only its config does. */ function descriptorShellIdentity( descriptor: ExecutionEnvironmentDescriptor | undefined, @@ -219,14 +212,6 @@ type HttpShellOutcome = | { readonly kind: "resumable" } | { readonly kind: "failed" }; -interface EarlyShellLoad { - readonly prepared: PreparedConnection; - readonly identity: ShellOriginIdentity; - readonly fiber: Fiber.Fiber; - // One subscription uses a load; a later one on the same connection decides again. - readonly session: Ref.Ref; -} - interface LiveShell { readonly snapshot: OrchestrationV2ShellSnapshot; // Read together with the rows, so a save never pairs them with another snapshot's origin. @@ -668,7 +653,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") const loadOverHttp = Effect.fn("EnvironmentShellState.loadOverHttp")(function* ( prepared: PreparedConnection, identity: ShellOriginIdentity | null, - session: Effect.Effect, + session: RpcSession, ) { const held = yield* SubscriptionRef.get(state); const resumeFrom = @@ -684,88 +669,20 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }); if (Option.isNone(answer)) return { kind: "failed" } satisfies HttpShellOutcome; if ("resumable" in answer.value) return { kind: "resumable" } satisfies HttpShellOutcome; - yield* applyHttpSnapshot(answer.value, identity, yield* session); + yield* applyHttpSnapshot(answer.value, identity, session); return { kind: "snapshot", projectIdentities: answer.value.projectIdentities, } satisfies HttpShellOutcome; }); - // A server whose descriptor names its shell flags is asked for the shell as soon as the - // connection is prepared, while the socket opens and the config downloads. When the supervisor - // exposes an opening socket, the socket pipelines the shell subscription alongside initial - // config instead of racing a second HTTP snapshot on the same host. + // When the supervisor exposes an opening socket for a server whose descriptor names its shell + // flags, the socket pipelines the shell subscription alongside initial config instead of racing + // a second HTTP snapshot on the same host. const canPipelineDirectSocket = (prepared: PreparedConnection | null) => supervisor.openingSession !== undefined && prepared !== null && descriptorShellIdentity(prepared.descriptor) !== null; - const earlyLoad = yield* SynchronizedRef.make(null); - const useEarlyLoad = (prepared: PreparedConnection | null, claim?: RpcSession) => - SynchronizedRef.modifyEffect( - earlyLoad, - Effect.fnUntraced(function* (current) { - // A rotated credential replaces the prepared connection of a session that stays up. - if (current !== null && prepared !== null && sameConnection(current.prepared, prepared)) { - const claimed = yield* Ref.get(current.session); - if (claim !== undefined) yield* Ref.set(current.session, claim); - const next = { ...current, prepared }; - // A claimed load that still runs is handed out again. A second request could - // answer first, and this one would then replace its rows under a passed cursor. - const done = current.fiber.pollUnsafe() !== undefined; - return [claimed !== undefined && done ? null : current, next] as const; - } - if (current !== null) yield* Fiber.interrupt(current.fiber); - const identity = descriptorShellIdentity(prepared?.descriptor); - if (prepared === null || identity === null || canPipelineDirectSocket(prepared)) { - return [null, null] as const; - } - // Items a closed session still has in flight must not land on the rows this loads. - yield* replaceActiveSubscription(null); - const session = yield* Ref.make(claim); - const fiber = yield* loadOverHttp(prepared, identity, Ref.get(session)).pipe( - Effect.forkIn(stateScope), - ); - const next: EarlyShellLoad = { prepared, identity, fiber, session }; - return [next, next] as const; - }), - ).pipe( - // Covers the store too. A cancel that lands during the wait above would otherwise take - // effect before the store, and the load just started would run on with no record. - Effect.uninterruptible, - ); - /** - * A ready socket can validate a held cursor itself. When it needs a full snapshot, give the - * already-started HTTP load a short head start before falling back to the socket snapshot. - */ - const awaitEarlyLoad = Effect.fnUntraced(function* ( - early: EarlyShellLoad, - identity: ShellOriginIdentity | null, - ) { - const resumable = - Option.isSome((yield* SubscriptionRef.get(state)).snapshot) && - canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis); - const answered = early.fiber.pollUnsafe(); - if (answered !== undefined) return answered; - if (!resumable && identity !== null && sameShellIdentity(early.identity, identity)) { - const completed = yield* Fiber.await(early.fiber).pipe(Effect.timeoutOption("30 millis")); - if (Option.isSome(completed)) return completed.value; - } - // Returns after an answer that is being applied has finished, so the cursor below is read - // from rows that no longer change under it. - yield* Fiber.interrupt(early.fiber); - return yield* Fiber.await(early.fiber); - }); - - yield* SubscriptionRef.changes(supervisor.prepared).pipe( - // Reads the connection of this moment: a change handled late must not start a load for a - // connection that ended, which would also drop the items of the session that replaced it. - Stream.runForEach(() => - SubscriptionRef.get(supervisor.prepared).pipe( - Effect.flatMap((prepared) => useEarlyLoad(Option.getOrNull(prepared))), - ), - ), - Effect.forkScoped, - ); const resubscriptions = Stream.merge( Stream.fromQueue(reloadRequests), @@ -873,8 +790,6 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") ); verifiedConfigIdentity.set(session, identity); } - const early = yield* useEarlyLoad(currentPrepared, session); - const earlyExit = early === null ? null : yield* awaitEarlyLoad(early, identity); if (verification !== undefined) { const settled = yield* pollOpeningVerification(verification); if (Option.isSome(settled)) { @@ -892,17 +807,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") omitIdleSubagents: false, omitOlderSettled: false, }; - // Rows the descriptor's flags or build loaded are not kept when the live config differs: - // their origin then cannot resume, so the load below replaces them. - let loaded = - early !== null && - earlyExit !== null && - identity !== null && - sameShellIdentity(early.identity, identity) - ? Exit.isSuccess(earlyExit) - ? earlyExit.value - : ({ kind: "failed" } satisfies HttpShellOutcome) - : null; + let loaded: HttpShellOutcome | null = null; yield* replaceActiveSubscription({ session, identity, @@ -919,13 +824,11 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") // Rows from a recent server snapshot with the same omissions and server build resume // from their cursor, in memory or from the cache. Anything else reloads the HTTP - // snapshot so a valid cursor cannot preserve stale or incomplete data. A `resumable` - // answer is checked again too: the rows can pass their age limit while the socket opens. + // snapshot so a valid cursor cannot preserve stale or incomplete data. const resumingHeldRows = - loaded?.kind !== "snapshot" && Option.isSome((yield* SubscriptionRef.get(state)).snapshot) && canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis); - if (!resumingHeldRows && loaded === null && !canPipelineDirectSocket(currentPrepared)) { + if (!resumingHeldRows && !canPipelineDirectSocket(currentPrepared)) { const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( Effect.flatMap( Option.match({ @@ -940,7 +843,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }), ), ); - loaded = yield* loadOverHttp(prepared, identity, Effect.succeed(session)); + loaded = yield* loadOverHttp(prepared, identity, session); } const current = yield* SubscriptionRef.get(state); diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index ccdc56710a..b732c47788 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -2547,6 +2547,8 @@ export const WsSubscribeServerConfigRpc = Rpc.make(WS_METHODS.subscribeServerCon providerCatalogDigests: Schema.optional(Schema.Boolean), /** Send provider changes as `providerStatusDeltas`; older clients reject the event type. */ providerStatusDeltas: Schema.optional(Schema.Boolean), + /** Send late editor discovery as `editorsUpdated` instead of a second full snapshot; older clients reject the event type. */ + editorUpdates: Schema.optional(Schema.Boolean), }), success: ServerConfigStreamEvent, error: Schema.Union([KeybindingsConfigError, ServerSettingsError, EnvironmentAuthorizationError]), diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index cb866c60ae..cc8801ed47 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -972,6 +972,21 @@ export const ServerConfigStreamHostPressureUpdatedEvent = Schema.Struct({ export type ServerConfigStreamHostPressureUpdatedEvent = typeof ServerConfigStreamHostPressureUpdatedEvent.Type; +export const ServerConfigEditorsUpdatedPayload = Schema.Struct({ + availableEditors: ForwardCompatibleArray(EditorId), + shellRevealInFileManager: Schema.optionalKey(Schema.Boolean), + shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind), +}); +export type ServerConfigEditorsUpdatedPayload = typeof ServerConfigEditorsUpdatedPayload.Type; + +export const ServerConfigStreamEditorsUpdatedEvent = Schema.Struct({ + version: Schema.Literal(1), + type: Schema.Literal("editorsUpdated"), + payload: ServerConfigEditorsUpdatedPayload, +}); +export type ServerConfigStreamEditorsUpdatedEvent = + typeof ServerConfigStreamEditorsUpdatedEvent.Type; + export const ServerConfigStreamEvent = Schema.Union([ ServerConfigStreamSnapshotEvent, ServerConfigStreamKeybindingsUpdatedEvent, @@ -981,6 +996,7 @@ export const ServerConfigStreamEvent = Schema.Union([ ServerConfigStreamEnvironmentThemesUpdatedEvent, ServerConfigStreamUsageLimitSourcesUpdatedEvent, ServerConfigStreamHostPressureUpdatedEvent, + ServerConfigStreamEditorsUpdatedEvent, ]); export type ServerConfigStreamEvent = typeof ServerConfigStreamEvent.Type;