feat(sessions): tell the user what a session start is waiting on

Creating or opening a session could stall for reasons the daemon knew
about and never shared. The browser invented the whole message it showed
while waiting -- "Creating session: Waiting for the backend session to be
ready" -- which says that we are waiting but never what for. A shared
ModelRuntime read during startup can be handed a network refresh that is
already in flight, and extensions may do their own network I/O while
loading, so the wait is real and previously unattributable.

The pre-session gap turned out to be a missing shared key rather than a
missing channel: publishActivity needs the PiAgentSession being built, but
the session id and cwd are both known before the first await. So create()
now publishes a new global session.startup event carrying an ordinary
SessionActivity, routed by cwd -- the one identity a browser row waiting
for a session id can match, since the client-invented pending id is
unknown to the daemon and the daemon's id is unknown to the browser.

Two phases are reported, each published before the await it describes so
the label changes during the wait rather than after it: "Starting the Pi
session" and "Loading session extensions". Both are facts, because the
service awaits exactly one call for each. A concurrent background catalog
refresh is appended as a note ("provider model lists are refreshing"),
never as the cause: the refresher can prove a refresh is running but not
that this startup joined it. ModelCatalogRefresher gains only a read-only
isRefreshInFlight() getter; cadence, timeout, and coalescing are untouched.

Reporting is event-only and synchronous. It writes no activities entry, no
workspace activity, and no unread state, so a failed creation leaves
nothing stranded, no await is added, and creation ordering and semantics
are unchanged. The window-ending idle report is skipped when a real
activity was published during startup, so an extension error survives.

The browser applies startup progress only when it can prove the target:
one non-discarded pending start in that cwd on the selected machine, or a
session whose id it already knows. A foreign workspace, another machine,
or two concurrent starts in one workspace keep today's generic wording
rather than showing one row the phase of another. An idle report restores
that generic wording, including the queued-messages variant.

docs/config.md said nothing a request triggers waits on a catalog fetch.
That is not strictly true for a refresh already in flight, so both it and
the generated docs/config.html now state the exception and say PI WEB
reports it while it happens.
This commit is contained in:
Federico Jaramillo Martinez
2026-07-26 16:19:05 +02:00
parent 36d67262ec
commit 49e7c390f3
15 changed files with 677 additions and 9 deletions
+3
View File
@@ -79,6 +79,9 @@ await runSessionDaemonStartup({
subsessionsEnabled: spawnTargets !== undefined && config.subsessions,
notificationStore,
unreadStore,
// Read-only, so session startup can tell a waiting user that provider
// model lists are refreshing at the same time.
catalogRefreshStatus: catalogRefresher,
sessionManager: createPiSessionManagerGateway({
agentDir: activeAgentProfile.dir,
env: daemonEnvironment,
@@ -329,6 +329,35 @@ describe("ModelCatalogRefresher", () => {
refresher.dispose();
});
it("reports an in-flight network refresh only while one is actually running", async () => {
const gate = deferred<RefreshResult>();
const refresh = vi.fn(() => gate.promise);
const refresher = new ModelCatalogRefresher({ runtime: { refresh } });
expect(refresher.isRefreshInFlight()).toBe(false);
refresher.requestRefresh();
expect(refresher.isRefreshInFlight()).toBe(true);
gate.resolve(okResult());
await flushMicrotasks();
expect(refresher.isRefreshInFlight()).toBe(false);
refresher.dispose();
});
it("never reports a refresh in flight in offline mode, where no refresh is ever run", async () => {
const runtime = createRuntime();
const refresher = new ModelCatalogRefresher({ runtime, offline: true, initialDelayMs: 1_000, intervalMs: 60_000 });
refresher.start();
refresher.requestRefresh();
await vi.advanceTimersByTimeAsync(300_000);
expect(refresher.isRefreshInFlight()).toBe(false);
refresher.dispose();
});
it("never touches the network when offline mode is enabled", async () => {
const runtime = createRuntime();
const { logger, info } = createLogger();
@@ -138,6 +138,15 @@ export class ModelCatalogRefresher {
this.queueRefresh("forced");
}
/**
* Whether a network catalog refresh is running right now. Read-only: callers
* that report what a slow operation is concurrent with need this fact, and
* must not be able to change the refresh schedule by asking for it.
*/
isRefreshInFlight(): boolean {
return this.inflight !== undefined;
}
/** Terminal: stops the schedule, drops any queued follow-up, and aborts an in-flight run. */
dispose(): void {
this.disposed = true;
@@ -0,0 +1,208 @@
import { describe, expect, it } from "vitest";
import { PiSessionService, type PiSessionRuntime } from "./piSessionService.js";
import { CapturingSessionEventHub, emptyArchiveStore, fakeRuntime, sessionGateway, sessionRecord, sessionRef, testModelRuntime } from "./piSessionService.testSupport.js";
import type { SessionActivity, SessionStartupProgressEvent } from "../../shared/apiTypes.js";
const TEST_AGENT_DIR = "/tmp/pi-web-test-agent";
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((promiseResolve, promiseReject) => {
resolve = promiseResolve;
reject = promiseReject;
});
return { promise, resolve, reject };
}
function startupEvents(hub: CapturingSessionEventHub): SessionStartupProgressEvent[] {
return hub.globalEvents.filter((event): event is SessionStartupProgressEvent => event.type === "session.startup");
}
function startupText(hub: CapturingSessionEventHub): string[] {
return startupEvents(hub).map(({ activity }) => activity.detail === undefined ? activity.label : `${activity.label}: ${activity.detail}`);
}
function activityUpdates(hub: CapturingSessionEventHub): SessionActivity[] {
return hub.globalEvents.flatMap((event) => event.type === "activity.update" ? [event.activity] : []);
}
/** Records whether the startup channel wrote any per-workspace activity state. */
function recordingWorkspaceActivity() {
const calls: string[] = [];
return {
calls,
workspaceActivity: {
applySessionStatus: () => { calls.push("applySessionStatus"); },
applySessionActivity: () => { calls.push("applySessionActivity"); },
removeSession: () => { calls.push("removeSession"); },
reconcileSessionActivity: () => { calls.push("reconcileSessionActivity"); },
},
};
}
interface StartupServiceOptions {
createAgentRuntime?: () => Promise<PiSessionRuntime>;
catalogRefreshInFlight?: boolean;
sessionRecords?: ReturnType<typeof sessionRecord>[];
workspaceActivity?: ReturnType<typeof recordingWorkspaceActivity>["workspaceActivity"];
}
function startupService(options: StartupServiceOptions = {}) {
const hub = new CapturingSessionEventHub();
const fake = fakeRuntime();
const service = new PiSessionService(hub, {
agentDir: TEST_AGENT_DIR,
modelRuntime: testModelRuntime,
archiveStore: emptyArchiveStore(),
createAgentRuntime: options.createAgentRuntime ?? (() => Promise.resolve(fake.runtime)),
sessionManager: sessionGateway(options.sessionRecords ?? []),
heartbeatIntervalMs: 60_000,
...(options.workspaceActivity === undefined ? {} : { workspaceActivity: options.workspaceActivity }),
...(options.catalogRefreshInFlight === undefined ? {} : {
catalogRefreshStatus: { isRefreshInFlight: () => options.catalogRefreshInFlight === true },
}),
});
return { hub, fake, service };
}
describe("PiSessionService session startup progress", () => {
it("reports the runtime construction phase while that construction is still pending", async () => {
const runtimeResult = deferred<PiSessionRuntime>();
const { hub, fake, service } = startupService({ createAgentRuntime: () => runtimeResult.promise });
const started = service.start("/workspace");
await new Promise<void>((resolve) => setImmediate(resolve));
// The proof that matters: the user is told what is being waited on before
// the wait ends, not after it.
expect(startupText(hub)).toEqual(["Creating session: Starting the Pi session"]);
expect(startupEvents(hub).at(0)).toMatchObject({ cwd: "/workspace", activity: { sessionId: "session-1", phase: "active" } });
runtimeResult.resolve(fake.runtime);
await started;
await service.dispose();
});
it("reports the extension loading phase while extension binding is still pending", async () => {
const bindResult = deferred<undefined>();
const { hub, fake, service } = startupService();
fake.session.bindExtensions = () => bindResult.promise;
const started = service.start("/workspace");
await new Promise<void>((resolve) => setImmediate(resolve));
expect(startupText(hub)).toEqual([
"Creating session: Starting the Pi session",
"Creating session: Loading session extensions",
]);
bindResult.resolve(undefined);
await started;
await service.dispose();
});
it("notes a concurrent provider model list refresh without claiming it is the cause", async () => {
const runtimeResult = deferred<PiSessionRuntime>();
const { hub, fake, service } = startupService({
createAgentRuntime: () => runtimeResult.promise,
catalogRefreshInFlight: true,
});
const started = service.start("/workspace");
await new Promise<void>((resolve) => setImmediate(resolve));
runtimeResult.resolve(fake.runtime);
await started;
expect(startupText(hub)).toEqual([
"Creating session: Starting the Pi session · provider model lists are refreshing",
"Creating session: Loading session extensions · provider model lists are refreshing",
"idle",
]);
await service.dispose();
});
it("states the phase alone when no refresh is running, and when nothing reports refresh state", async () => {
const withStatus = startupService({ catalogRefreshInFlight: false });
await withStatus.service.start("/workspace");
const withoutStatus = startupService();
await withoutStatus.service.start("/workspace");
for (const hub of [withStatus.hub, withoutStatus.hub]) {
expect(startupText(hub)).toEqual([
"Creating session: Starting the Pi session",
"Creating session: Loading session extensions",
"idle",
]);
}
await withStatus.service.dispose();
await withoutStatus.service.dispose();
});
it("says opening rather than creating when an existing session is opened", async () => {
const { service, hub } = startupService({ sessionRecords: [sessionRecord("session-1")] });
await service.status(sessionRef("session-1"));
expect(startupText(hub)).toEqual([
"Opening session: Starting the Pi session",
"Opening session: Loading session extensions",
"idle",
]);
await service.dispose();
});
it("ends the startup window with an idle report when creation succeeds", async () => {
const { hub, service } = startupService();
await service.start("/workspace");
expect(startupEvents(hub).at(-1)).toMatchObject({ cwd: "/workspace", activity: { sessionId: "session-1", phase: "idle", label: "idle" } });
expect(startupEvents(hub).at(-1)?.activity.detail).toBeUndefined();
await service.dispose();
});
it("ends the startup window when the runtime construction itself fails", async () => {
const failure = new Error("runtime unavailable");
const { hub, service } = startupService({ createAgentRuntime: () => Promise.reject(failure) });
await expect(service.start("/workspace")).rejects.toBe(failure);
expect(startupText(hub)).toEqual(["Creating session: Starting the Pi session", "idle"]);
await service.dispose();
});
it("keeps a real activity published during startup instead of clearing it", async () => {
const { hub, fake, service } = startupService();
fake.session.bindExtensions = (bindings) => {
bindings.onError?.({ extensionPath: "/ext/broken.js", event: "session_start", error: "boom" });
return Promise.resolve();
};
await service.start("/workspace");
expect(activityUpdates(hub).some((activity) => activity.label === "extension error")).toBe(true);
// No idle startup report, so the extension error a user needs to see stays.
expect(startupEvents(hub).some((event) => event.activity.phase === "idle")).toBe(false);
await service.dispose();
});
it("keeps startup reporting event-only, writing no session or workspace activity state", async () => {
const recorder = recordingWorkspaceActivity();
const failure = new Error("runtime unavailable");
const { hub, service } = startupService({
createAgentRuntime: () => Promise.reject(failure),
workspaceActivity: recorder.workspaceActivity,
});
await expect(service.start("/workspace")).rejects.toBe(failure);
expect(startupEvents(hub)).toHaveLength(2);
expect(activityUpdates(hub)).toEqual([]);
expect(recorder.calls).toEqual([]);
// Startup progress is global-only: it must never reach a per-session socket,
// because no session exists to have subscribers yet.
expect(hub.sessionEvents).toEqual([]);
await service.dispose();
});
});
+113
View File
@@ -78,6 +78,20 @@ export interface PiSessionLogger {
const noopLogger: PiSessionLogger = { info() { /* no-op */ } };
const DEFAULT_UNREAD_PUBLICATION_RETRY_MS = 1_000;
/**
* User-facing names for the two phases of session startup PI WEB can prove it
* is inside: it awaits exactly one call for each, so the phase is a fact rather
* than a guess. Deliberately free of internal symbol names and file paths.
*/
const STARTUP_PHASE_RUNTIME = "Starting the Pi session";
const STARTUP_PHASE_EXTENSIONS = "Loading session extensions";
/**
* Appended to whichever phase is running when a background provider catalog
* refresh happens to be in flight. It is stated as a concurrent fact, never as
* the cause: PI WEB can verify that a refresh is running, but not that this
* particular startup is waiting on it.
*/
const STARTUP_CONCURRENT_CATALOG_REFRESH = "provider model lists are refreshing";
const MAX_UNREAD_PUBLICATION_RETRY_MS = 30_000;
const MAX_PENDING_UNREAD_MUTATIONS = SESSION_UNREAD_LIMIT + 1;
@@ -379,6 +393,30 @@ interface PendingSessionOpen {
interface CreateSessionRuntimeOptions extends Pick<InternalStartSessionOptions, "initialModel" | "creationProvenance"> {
notificationGeneration?: SessionNotificationGeneration;
notifications?: "enabled" | "disabled";
/**
* What the user asked for, so startup progress can say "Creating" instead of
* "Opening". Only `startSession()` creates a brand new session; every other
* caller opens an existing one, so "open" is the default.
*/
startupIntent?: "create" | "open";
}
/**
* Read-only view of the background catalog refresher, so session startup can
* state what it is concurrent with without being able to influence it.
*/
export interface CatalogRefreshStatus {
isRefreshInFlight(): boolean;
}
/**
* Publishes what a session startup is waiting on while it waits. Every call is
* synchronous and event-only, so reporting never adds an await to session
* creation and leaves no per-session state to unwind if creation fails.
*/
interface SessionStartupProgressReporter {
report(phase: string): void;
end(): void;
}
type NotificationClosePolicy =
@@ -658,6 +696,11 @@ export interface PiSessionServiceDependencies {
unreadStore?: SessionUnreadStore;
/** Initial retry delay for durable unread publication failures. */
unreadPublicationRetryDelayMs?: number;
/**
* Lets session startup report that provider model lists are refreshing while
* a session is being constructed. Omit to report the startup phase alone.
*/
catalogRefreshStatus?: CatalogRefreshStatus;
}
export class PiSessionService implements SessionRouteService {
@@ -705,6 +748,7 @@ export class PiSessionService implements SessionRouteService {
private readonly notificationStore: SessionNotificationStore;
private readonly notificationGenerationBySession = new WeakMap<PiAgentSession, SessionNotificationGeneration>();
private readonly unreadStore: SessionUnreadStore;
private readonly catalogRefreshStatus: CatalogRefreshStatus | undefined;
private readonly unreadPublicationRetryInitialMs: number;
private readonly pendingUnreadMutations: SessionUnreadMutation[] = [];
private unreadPublication: Promise<void> | undefined;
@@ -724,6 +768,7 @@ export class PiSessionService implements SessionRouteService {
this.now = deps.now ?? (() => new Date());
this.notificationStore = deps.notificationStore ?? new SessionNotificationStore();
this.unreadStore = deps.unreadStore ?? new SessionUnreadStore();
this.catalogRefreshStatus = deps.catalogRefreshStatus;
this.unreadPublicationRetryInitialMs = Math.max(
0,
deps.unreadPublicationRetryDelayMs ?? DEFAULT_UNREAD_PUBLICATION_RETRY_MS,
@@ -946,6 +991,7 @@ export class PiSessionService implements SessionRouteService {
this.sessionManager.create(cwd, options.parentSession === undefined ? undefined : { parentSession: options.parentSession }),
cwd,
{
startupIntent: "create",
...(options.initialModel === undefined ? {} : { initialModel: options.initialModel }),
...(options.creationProvenance === undefined ? {} : { creationProvenance: options.creationProvenance }),
},
@@ -2295,11 +2341,33 @@ export class PiSessionService implements SessionRouteService {
return undefined;
}
/**
* Construct a session while telling waiting browsers which phase of startup
* they are waiting on. The reporting wraps the *whole* construction rather
* than the inner bookkeeping `try`, because the runtime construction that runs
* first is both the slowest phase and one that can fail on its own; a clear
* that only ran for the later phases would leave a stale label behind.
*/
private async create(
sessionManager: PiSessionManager,
cwd: string,
options: CreateSessionRuntimeOptions = {},
): Promise<ActiveSession<PiSessionRuntime>> {
const startup = this.startupProgress(sessionManager, cwd, options.startupIntent ?? "open");
try {
return await this.createSessionRuntime(sessionManager, cwd, options, startup);
} finally {
startup.end();
}
}
private async createSessionRuntime(
sessionManager: PiSessionManager,
cwd: string,
options: CreateSessionRuntimeOptions,
startup: SessionStartupProgressReporter,
): Promise<ActiveSession<PiSessionRuntime>> {
startup.report(STARTUP_PHASE_RUNTIME);
const delegationToolsEnabled = options.creationProvenance !== "tracked-subsession"
&& await sessionAllowsDelegationTools(sessionManager, this.sessionManager);
const runtime = await this.createAgentRuntime(this.createRuntime, {
@@ -2347,6 +2415,7 @@ export class PiSessionService implements SessionRouteService {
} else {
await this.recoverSubsessionTrackingForOpenedSession(runtime.session);
}
startup.report(STARTUP_PHASE_EXTENSIONS);
await this.bindSessionExtensions(runtime.session, notificationGeneration);
this.bindRuntime(active);
runtime.setRebindSession(async (session) => {
@@ -2927,6 +2996,50 @@ export class PiSessionService implements SessionRouteService {
if (this.hasActiveWork(session)) this.publishActivity(session, eventType.replaceAll("_", " "), "active");
}
/**
* Build the reporter for one session construction.
*
* The session id and cwd are both known before any await — a `SessionManager`
* has its id from construction — so the daemon can name what it is starting
* even though the `PiAgentSession` that {@link publishActivity} needs does not
* exist yet. When either is missing there is nothing honest to route on, so
* the reporter stays silent and the browser keeps its own generic wording.
*/
private startupProgress(sessionManager: PiSessionManager, cwd: string, intent: "create" | "open"): SessionStartupProgressReporter {
const sessionId = sessionManager.getSessionId();
if (sessionId === "" || cwd === "") return { report: noop, end: noop };
const label = intent === "create" ? "Creating session" : "Opening session";
return {
report: (phase) => { this.publishStartupProgress(sessionId, cwd, label, "active", this.startupDetail(phase)); },
end: () => {
// A real activity published during the window (an extension error, say)
// is the truth about this session and must survive the clear.
if (this.activities.has(sessionId)) return;
this.publishStartupProgress(sessionId, cwd, "idle", "idle", undefined);
},
};
}
private startupDetail(phase: string): string {
return this.catalogRefreshStatus?.isRefreshInFlight() === true
? `${phase} · ${STARTUP_CONCURRENT_CATALOG_REFRESH}`
: phase;
}
/**
* Report startup progress on the global channel only, keyed by `cwd` so a
* browser row that has no session id yet can find it.
*
* Unlike {@link publishActivity} this deliberately records nothing: no
* `activities` entry, no workspace activity, no unread observation. There is
* no session to own that state, and a failed creation would leave it stranded.
*/
private publishStartupProgress(sessionId: string, cwd: string, label: string, phase: "active" | "idle", detail: string | undefined): void {
const at = new Date().toISOString();
const activity = detail === undefined ? { sessionId, phase, label, at } : { sessionId, phase, label, detail, at };
this.events.publishGlobal({ type: "session.startup", cwd, activity });
}
private publishActivity(session: PiAgentSession, label: string, phase: "active" | "idle" | "error", detail?: string): void {
const at = new Date().toISOString();
const stored = detail === undefined ? { phase, label, at } : { phase, label, detail, at };