Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/mobile/src/connection/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 3 additions & 1 deletion apps/mobile/src/lib/pullRequestNavigation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ export function pullRequestFileLinkRoute(
export function nativePullRequestDestination(
url: string,
context: { environmentId: string; projectId: string } | null,
projects: ReadonlyArray<Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity">>,
projects: ReadonlyArray<
Pick<EnvironmentProject, "id" | "environmentId" | "repositoryIdentity" | "trackedFolders">
>,
configLoaded: (environmentId: EnvironmentId) => boolean,
) {
if (!context) return null;
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/src/state/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export const serverEnvironment = createServerEnvironmentAtoms(connectionAtomRunt
providerCatalogsOnDemand: true,
providerCatalogDigests: true,
providerStatusDeltas: true,
editorUpdates: true,
omitRefreshedProviders: true,
});
export const describeOutdatedServer = createOutdatedServerDescriptionCommand(connectionAtomRuntime);
Expand Down
3 changes: 2 additions & 1 deletion apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -615,6 +615,7 @@ export interface OrchestratorV2Shape {
readonly threadId?: ThreadId;
readonly afterSequence?: number;
readonly eventType?: OrchestrationV2DomainEvent["type"];
readonly bounded?: boolean;
}) => Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;
readonly streamDomainEvents: Stream.Stream<OrchestrationV2DomainEvent, OrchestratorV2Error>;
}
Expand Down Expand Up @@ -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({
Expand Down
105 changes: 105 additions & 0 deletions apps/server/src/peer/handoff/ThreadHandoff.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ReadonlyArray<CapturedTurn>>([]);
const releases = yield* Queue.unbounded<void>();
const packing = yield* Deferred.make<void>();
const releasePack = yield* Deferred.make<void>();
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)),
);
91 changes: 59 additions & 32 deletions apps/server/src/peer/handoff/ThreadHandoff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -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";
Expand Down Expand Up @@ -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<void>();
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 });
});
Expand Down
17 changes: 17 additions & 0 deletions apps/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
42 changes: 42 additions & 0 deletions apps/server/src/ws.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>();
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" }];
Expand Down
Loading