Archived
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:
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PI_WEB_CAPABILITIES } from "../../../shared/capabilities";
|
||||
import { SESSION_NOTIFICATION_LIMIT, SESSION_NOTIFICATION_MESSAGE_BYTES, SESSION_UNREAD_CATALOG_ID_MAX_LENGTH } from "../../../shared/apiTypes";
|
||||
import { parseAuthProvidersResponse, parseCommandResult, parseFileContentResponse, parseFileSuggestion, parseGitStatusResponse, parseMachineRuntime, parseMessagePage, parseOAuthFlowState, parsePiPackageMutationResponse, parsePiPackagesResponse, parsePiWebConfigResponse, parsePiWebPluginsResponse, parsePiWebRuntimeResponse, parsePiWebStatusResponse, parseSessionBulkArchiveResponse, parseSessionBulkDeleteArchivedResponse, parseSessionCleanupExecuteResponse, parseSessionCleanupPreviewResponse, parseSessionInfo, parseSessionNotificationInboxEvent, parseSessionNotificationInboxSnapshot, parseSessionStatus, parseSessionStreamSnapshot, parseSessionTreeNavigateResult, parseSessionTreeSnapshot, parseSessionUnreadCatalogSnapshot, parseSessionUnreadEvent, parseSlashCommand, parseTerminalCommandRun, parseTerminalInfo, parseWorkspace, parseWorkspaceActivityResponse } from "./parsers";
|
||||
import { parseAuthProvidersResponse, parseCommandResult, parseFileContentResponse, parseFileSuggestion, parseGitStatusResponse, parseMachineRuntime, parseMessagePage, parseOAuthFlowState, parsePiPackageMutationResponse, parsePiPackagesResponse, parsePiWebConfigResponse, parsePiWebPluginsResponse, parsePiWebRuntimeResponse, parsePiWebStatusResponse, parseSessionBulkArchiveResponse, parseSessionBulkDeleteArchivedResponse, parseSessionCleanupExecuteResponse, parseSessionCleanupPreviewResponse, parseSessionInfo, parseSessionNotificationInboxEvent, parseSessionNotificationInboxSnapshot, parseSessionStartupProgressEvent, parseSessionStatus, parseSessionStreamSnapshot, parseSessionTreeNavigateResult, parseSessionTreeSnapshot, parseSessionUnreadCatalogSnapshot, parseSessionUnreadEvent, parseSlashCommand, parseTerminalCommandRun, parseTerminalInfo, parseWorkspace, parseWorkspaceActivityResponse } from "./parsers";
|
||||
|
||||
describe("API parsers", () => {
|
||||
it("preserves additive interactive API-key flow hints and defaults legacy options", () => {
|
||||
@@ -289,6 +289,36 @@ describe("API parsers", () => {
|
||||
})).toThrow("positive safe integer");
|
||||
});
|
||||
|
||||
it("parses session startup progress with and without a wait detail", () => {
|
||||
const activity = { sessionId: "session-1", phase: "active", label: "Creating session", detail: "Starting the Pi session", at: "2026-07-20T00:00:01.000Z" };
|
||||
|
||||
expect(parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity })).toEqual({
|
||||
type: "session.startup",
|
||||
cwd: "/repo",
|
||||
activity,
|
||||
});
|
||||
const idle = { sessionId: "session-1", phase: "idle", label: "idle", at: "2026-07-20T00:00:02.000Z" };
|
||||
expect(parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: idle })).toEqual({
|
||||
type: "session.startup",
|
||||
cwd: "/repo",
|
||||
activity: idle,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects session startup progress that cannot be routed or rendered honestly", () => {
|
||||
const activity = { sessionId: "session-1", phase: "active", label: "Creating session", at: "2026-07-20T00:00:01.000Z" };
|
||||
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "activity.update", cwd: "/repo", activity })).toThrow("Invalid session startup event type");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", activity })).toThrow("Expected string field: cwd");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "", activity })).toThrow("Expected non-empty string field: cwd");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo" })).toThrow("Expected object response");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, phase: "waiting" } })).toThrow("Expected session activity phase field: phase");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, label: 7 } })).toThrow("Expected string field: label");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, label: "" } })).toThrow("Expected non-empty string field: label");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, detail: 7 } })).toThrow("Expected optional string field: detail");
|
||||
expect(() => parseSessionStartupProgressEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, sessionId: "" } })).toThrow("Expected non-empty string field: sessionId");
|
||||
});
|
||||
|
||||
it("parses session cleanup preview and execute responses", () => {
|
||||
const preview = {
|
||||
generatedAt: "2026-06-25T12:00:00.000Z",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SESSION_NOTIFICATION_LIMIT, SESSION_NOTIFICATION_MESSAGE_BYTES, SESSION_UNREAD_CATALOG_ID_MAX_LENGTH, SESSION_UNREAD_COMPLETED_AT_MAX_LENGTH, SESSION_UNREAD_CWD_MAX_LENGTH, SESSION_UNREAD_LIMIT, SESSION_UNREAD_SESSION_ID_MAX_LENGTH, type ArchiveSessionsResponse, type AuthProviderOption, type AuthProviderStatus, type AuthProvidersResponse, type AuthStatusSource, type AuthType, type CommandOption, type CommandResult, type DeleteWorkspaceFileResponse, type FileContentResponse, type FileSuggestion, type FileTreeEntry, type FileTreeResponse, type GitDiffResponse, type GitFileState, type GitStatusFile, type GitStatusResponse, type Machine, type MachineHealth, type MachineKind, type MachineRuntime, type MachineStatus, type MessagePage, type ModelSelectionResponse, type MoveWorkspaceFileResponse, type OAuthFlowState, type PiWebAgentDirEnvSource, type PiWebCapability, type PiWebComponentStatus, type PiWebConfigEnvOverrides, type PiWebConfigResponse, type PiWebConfigValues, type PiWebInstallationInfo, type PiWebPluginConfigMap, type PiWebPluginInfo, type PiWebPluginsResponse, type PiWebPluginScope, type PiWebReleaseStatus, type PiWebRuntimeComponent, type PiWebRuntimeResponse, type PiWebServiceComponent, type PiWebShortcutConfig, type PiWebStatusMessage, type PiWebStatusResponse, type PiWebStatusSeverity, type Project, type QueuedSessionMessage, type SavedPromptAttachment, type SessionBulkArchiveResponse, type SessionBulkDeleteArchivedResponse, type SessionBulkFailure, type SessionCleanupExecuteResponse, type SessionCleanupPreviewResponse, type SessionCleanupProjectSummary, type SessionCleanupThresholds, type SessionCleanupTotals, type SessionInfo, type SessionModel, type SessionNotification, type SessionNotificationClearReason, type SessionNotificationDismissThrough, type SessionNotificationInboxDelta, type SessionNotificationInboxEvent, type SessionNotificationInboxSnapshot, type SessionNotificationSeverity, type SessionNotificationSummary, type SessionStatus, type SessionStreamSnapshot, type SessionUnreadCatalogSnapshot, type SessionUnreadEvent, type SessionUnreadSummary, type SessionWarning, type SessionWarningSeverity, type SlashCommand, type TerminalCommandRun, type TerminalCommandRunStatus, type TerminalInfo, type ThinkingLevelsResponse, type WriteWorkspaceFileResponse, type Workspace, type WorkspaceActivity, type WorkspaceActivityResponse } from "../../../shared/apiTypes";
|
||||
import type { PiPackageInfo, PiPackageMutationAction, PiPackageMutationResponse, PiPackageScope, PiPackagesResponse, SessionTreeNavigateResult, SessionTreeNode, SessionTreeNodeKind, SessionTreeSnapshot } from "../../../shared/apiTypes";
|
||||
import type { PiPackageInfo, PiPackageMutationAction, PiPackageMutationResponse, PiPackageScope, PiPackagesResponse, SessionActivity, SessionStartupProgressEvent, SessionTreeNavigateResult, SessionTreeNode, SessionTreeNodeKind, SessionTreeSnapshot } from "../../../shared/apiTypes";
|
||||
import { parseActiveAgentProfileDescriptor } from "../../../shared/activeAgentProfile";
|
||||
import { parseKnownPiWebCapabilities } from "../../../shared/capabilities";
|
||||
|
||||
@@ -272,6 +272,39 @@ export function parseSessionUnreadEvent(value: unknown): SessionUnreadEvent {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a startup progress frame. The browser substitutes its own wording
|
||||
* from this event, so a malformed frame must be dropped rather than rendered:
|
||||
* `cwd` is the routing key, and an activity missing its phase or label could
|
||||
* otherwise blank out or freeze the text a user is reading while they wait.
|
||||
*/
|
||||
export function parseSessionStartupProgressEvent(value: unknown): SessionStartupProgressEvent {
|
||||
const record = requireRecord(value);
|
||||
if (record["type"] !== "session.startup") throw new Error("Invalid session startup event type");
|
||||
return {
|
||||
type: "session.startup",
|
||||
cwd: requireNonEmptyString(record, "cwd"),
|
||||
activity: parseSessionActivity(record["activity"]),
|
||||
};
|
||||
}
|
||||
|
||||
function parseSessionActivity(value: unknown): SessionActivity {
|
||||
const record = requireRecord(value);
|
||||
return {
|
||||
sessionId: requireNonEmptyString(record, "sessionId"),
|
||||
phase: requireSessionActivityPhase(record, "phase"),
|
||||
label: requireNonEmptyString(record, "label"),
|
||||
...optionalField("detail", optionalString(record, "detail")),
|
||||
at: requireNonEmptyString(record, "at"),
|
||||
};
|
||||
}
|
||||
|
||||
function requireSessionActivityPhase(record: Record<string, unknown>, key: string): SessionActivity["phase"] {
|
||||
const value = requireString(record, key);
|
||||
if (value !== "active" && value !== "idle" && value !== "error") throw new Error(`Expected session activity phase field: ${key}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function parseSessionUnreadSummary(value: unknown): SessionUnreadSummary {
|
||||
const record = requireRecord(value);
|
||||
const completedAt = requireBoundedNonEmptyString(
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { initialAppState } from "../appState";
|
||||
import { SessionController } from "./sessionController";
|
||||
import { defaultApi, deferred, emptyPage, FakeSocket, oldSession, runPendingAnimationFrames, sessionLookupId, status, workspace, type AppState, type SessionActivity, type SessionInfo } from "./sessionController.testSupport";
|
||||
|
||||
const REMOTE_MACHINE = { id: "remote", name: "Remote", kind: "remote" as const, createdAt: "now", updatedAt: "now" };
|
||||
|
||||
function startupActivity(patch: Partial<SessionActivity> = {}): SessionActivity {
|
||||
return {
|
||||
sessionId: "backend-session",
|
||||
phase: "active",
|
||||
label: "Creating session",
|
||||
detail: "Starting the Pi session",
|
||||
at: "2026-07-20T00:00:01.000Z",
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
/** The end-of-window report: no phase left to name, so no detail either. */
|
||||
function idleStartupActivity(): SessionActivity {
|
||||
return { sessionId: "backend-session", phase: "idle", label: "idle", at: "2026-07-20T00:00:02.000Z" };
|
||||
}
|
||||
|
||||
function pendingStartController(state: { current: AppState }, api: Partial<typeof defaultApi> = {}) {
|
||||
const startRequest = deferred<SessionInfo>();
|
||||
const controller = new SessionController(
|
||||
() => state.current,
|
||||
(patch) => { state.current = { ...state.current, ...patch }; },
|
||||
() => undefined,
|
||||
undefined,
|
||||
{
|
||||
api: {
|
||||
...defaultApi,
|
||||
startSession: () => startRequest.promise,
|
||||
messages: () => Promise.resolve(emptyPage),
|
||||
status: (session) => Promise.resolve(status(sessionLookupId(session))),
|
||||
...api,
|
||||
},
|
||||
socket: new FakeSocket(),
|
||||
},
|
||||
);
|
||||
return { controller, startRequest };
|
||||
}
|
||||
|
||||
describe("SessionController session startup progress", () => {
|
||||
it("shows the daemon's startup phase on a pending row while its start request is still open", async () => {
|
||||
const state = { current: { ...initialAppState(), selectedWorkspace: workspace, sessions: [] } };
|
||||
const { controller, startRequest } = pendingStartController(state);
|
||||
|
||||
const start = controller.startSession();
|
||||
const temporaryId = state.current.selectedSession?.id;
|
||||
if (temporaryId === undefined) throw new Error("Expected temporary session id");
|
||||
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: startupActivity() });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
// The label changes while the user is waiting, before the start resolves,
|
||||
// and it is attributed to the row the user is actually looking at.
|
||||
expect(state.current.activity).toMatchObject({ sessionId: temporaryId, phase: "active", label: "Creating session", detail: "Starting the Pi session" });
|
||||
expect(state.current.sessionActivities[temporaryId]).toMatchObject({ detail: "Starting the Pi session" });
|
||||
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: startupActivity({ detail: "Loading session extensions" }) });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
expect(state.current.activity?.detail).toBe("Loading session extensions");
|
||||
|
||||
startRequest.resolve({ ...oldSession, id: "backend-session", path: "/tmp/backend-session.jsonl" });
|
||||
await start;
|
||||
});
|
||||
|
||||
it("restores the generic wording when the daemon has nothing left to attribute", async () => {
|
||||
const state = { current: { ...initialAppState(), selectedWorkspace: workspace, sessions: [] } };
|
||||
const { controller, startRequest } = pendingStartController(state);
|
||||
|
||||
const start = controller.startSession();
|
||||
const temporaryId = state.current.selectedSession?.id;
|
||||
if (temporaryId === undefined) throw new Error("Expected temporary session id");
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: startupActivity() });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: idleStartupActivity() });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
expect(state.current.activity).toMatchObject({
|
||||
sessionId: temporaryId,
|
||||
phase: "active",
|
||||
label: "Creating session",
|
||||
detail: "Waiting for the backend session to be ready",
|
||||
});
|
||||
|
||||
startRequest.resolve({ ...oldSession, id: "backend-session", path: "/tmp/backend-session.jsonl" });
|
||||
await start;
|
||||
});
|
||||
|
||||
it("restores the queued-message wording when a pending row has sends waiting", async () => {
|
||||
const state = { current: { ...initialAppState(), selectedWorkspace: workspace, sessions: [] } };
|
||||
const { controller, startRequest } = pendingStartController(state);
|
||||
|
||||
const start = controller.startSession();
|
||||
await controller.send("queued while starting");
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: idleStartupActivity() });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
expect(state.current.activity?.detail).toBe("1 queued message will send when the backend session is ready");
|
||||
|
||||
startRequest.resolve({ ...oldSession, id: "backend-session", path: "/tmp/backend-session.jsonl" });
|
||||
await start;
|
||||
});
|
||||
|
||||
it("applies startup progress for an existing session it already knows the id of", () => {
|
||||
let state: AppState = { ...initialAppState(), selectedSession: oldSession, sessions: [oldSession] };
|
||||
const controller = new SessionController(
|
||||
() => state,
|
||||
(patch) => { state = { ...state, ...patch }; },
|
||||
() => undefined,
|
||||
undefined,
|
||||
{ socket: new FakeSocket() },
|
||||
);
|
||||
|
||||
controller.applyGlobalEvent({
|
||||
type: "session.startup",
|
||||
cwd: oldSession.cwd,
|
||||
activity: startupActivity({ sessionId: oldSession.id, label: "Opening session" }),
|
||||
});
|
||||
runPendingAnimationFrames();
|
||||
|
||||
expect(state.activity).toMatchObject({ sessionId: oldSession.id, label: "Opening session", detail: "Starting the Pi session" });
|
||||
});
|
||||
|
||||
it("keeps the generic wording when the startup progress cannot be attributed to one row", async () => {
|
||||
const state = { current: { ...initialAppState(), selectedWorkspace: workspace, sessions: [] } };
|
||||
const { controller, startRequest } = pendingStartController(state);
|
||||
|
||||
const start = controller.startSession();
|
||||
const temporaryId = state.current.selectedSession?.id;
|
||||
if (temporaryId === undefined) throw new Error("Expected temporary session id");
|
||||
|
||||
// Another workspace's startup.
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: "/elsewhere", activity: startupActivity() });
|
||||
// The selected machine's socket is the only feed for these events, so a cwd
|
||||
// that matches while another machine is selected belongs to a different row.
|
||||
state.current = { ...state.current, selectedMachine: REMOTE_MACHINE };
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: startupActivity() });
|
||||
state.current = { ...state.current, selectedMachine: undefined };
|
||||
runPendingAnimationFrames();
|
||||
|
||||
expect(state.current.activity?.detail).toBe("Waiting for the backend session to be ready");
|
||||
|
||||
// A second concurrent start in the same workspace makes the target ambiguous,
|
||||
// so neither row is given a phase that might belong to the other.
|
||||
const secondStart = controller.startSession();
|
||||
controller.applyGlobalEvent({ type: "session.startup", cwd: workspace.path, activity: startupActivity() });
|
||||
runPendingAnimationFrames();
|
||||
|
||||
const secondTemporaryId = state.current.selectedSession?.id;
|
||||
expect(secondTemporaryId).not.toBe(temporaryId);
|
||||
expect(state.current.sessionActivities[temporaryId]?.detail).toBe("Waiting for the backend session to be ready");
|
||||
expect(state.current.sessionActivities[secondTemporaryId ?? ""]?.detail).toBe("Waiting for the backend session to be ready");
|
||||
|
||||
startRequest.resolve({ ...oldSession, id: "backend-session", path: "/tmp/backend-session.jsonl" });
|
||||
await Promise.all([start, secondStart]);
|
||||
});
|
||||
});
|
||||
@@ -11,7 +11,7 @@ import { SessionSocket, type GlobalSessionEvent, type SessionUiEvent } from "../
|
||||
import { isArchivableSessionInfo, isTransientNewSessionInfo, sessionPersistenceOptionsForRuntime } from "../sessionPersistence";
|
||||
import { isSessionActive } from "../../../shared/activity";
|
||||
import { PI_WEB_CAPABILITIES, supportsPiWebCapability } from "../../../shared/capabilities";
|
||||
import type { PromptAttachmentDelivery, SessionNotificationInboxEvent } from "../../../shared/apiTypes";
|
||||
import type { PromptAttachmentDelivery, SessionNotificationInboxEvent, SessionStartupProgressEvent } from "../../../shared/apiTypes";
|
||||
import { InMemorySessionSelectionMemory, markSessionArchived, markSessionsArchived, selectPreferredSession, selectionAfterArchivingSession, selectionAfterArchivingSessions, shouldDeselectAfterArchivedCollapse, type SessionSelectionMemory } from "./sessionSelection";
|
||||
import { selectedMachineId, type GetState, type SetState, type UpdateUrl } from "./types";
|
||||
import { TrailingRefreshCoordinator } from "./trailingRefreshCoordinator";
|
||||
@@ -140,6 +140,7 @@ export class SessionController {
|
||||
else if (event.type === "activity.update") this.queueActivityUpdate(event.activity);
|
||||
else if (event.type === "session.created") this.applyCreatedSession(event.session);
|
||||
else if (event.type === "session.name") this.applySessionName(event.sessionId, event.name);
|
||||
else if (event.type === "session.startup") this.queueStartupProgress(event);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
@@ -1307,6 +1308,36 @@ export class SessionController {
|
||||
this.schedulePendingFlush();
|
||||
}
|
||||
|
||||
// Session startup progress arrives while the daemon is still constructing the
|
||||
// session, so it is routed by workspace path: a pending start knows its cwd
|
||||
// but not the session id the daemon is creating. Once the target row is
|
||||
// resolved the progress goes through the normal activity buffer, so it renders
|
||||
// exactly like any other activity and stays batched per frame.
|
||||
private queueStartupProgress(event: SessionStartupProgressEvent): void {
|
||||
const pending = this.startupProgressPendingStart(event.cwd);
|
||||
if (pending !== undefined) {
|
||||
// An idle startup phase means the daemon has nothing left to attribute, so
|
||||
// restore this row's own generic wording rather than clearing the text of a
|
||||
// creation request that has not returned yet.
|
||||
this.queueActivityUpdate(event.activity.phase === "idle"
|
||||
? creatingPendingSessionActivity(pending.tempId, pending.queuedSends.length)
|
||||
: { ...event.activity, sessionId: pending.tempId });
|
||||
return;
|
||||
}
|
||||
// Opening a session the browser already knows the id of: the event applies as
|
||||
// published. Anything else (a foreign workspace, or several pending starts in
|
||||
// one workspace, where the row this belongs to cannot be proved) is dropped
|
||||
// rather than attributed to a guess.
|
||||
if (this.getState().sessions.some((session) => session.id === event.activity.sessionId)) this.queueActivityUpdate(event.activity);
|
||||
}
|
||||
|
||||
private startupProgressPendingStart(cwd: string): PendingSessionStart | undefined {
|
||||
const machineId = selectedMachineId(this.getState());
|
||||
const matches = Array.from(this.pendingSessionStarts.values())
|
||||
.filter((pending) => pending.cwd === cwd && pending.machineId === machineId && !pending.discarded);
|
||||
return matches.length === 1 ? matches[0] : undefined;
|
||||
}
|
||||
|
||||
private schedulePendingFlush(): void {
|
||||
if (this.pendingFrame !== undefined) return;
|
||||
this.pendingFrame = requestAnimationFrame(() => {
|
||||
|
||||
@@ -90,6 +90,19 @@ describe("notification socket guards", () => {
|
||||
})).toBeUndefined();
|
||||
});
|
||||
|
||||
it("accepts validated session startup progress and drops malformed frames", () => {
|
||||
const activity = { sessionId: "session-1", phase: "active", label: "Creating session", detail: "Starting the Pi session", at: "2026-07-20T00:00:01.000Z" };
|
||||
|
||||
expect(parseRealtimeSocketEvent({ type: "session.startup", cwd: "/repo", activity }))
|
||||
.toMatchObject({ type: "session.startup", cwd: "/repo", activity });
|
||||
expect(parseRealtimeSocketEvent({ type: "session.startup", cwd: "", activity })).toBeUndefined();
|
||||
expect(parseRealtimeSocketEvent({ type: "session.startup", cwd: "/repo" })).toBeUndefined();
|
||||
expect(parseRealtimeSocketEvent({ type: "session.startup", cwd: "/repo", activity: { ...activity, phase: "waiting" } })).toBeUndefined();
|
||||
// Startup progress is global-only, so it must not be accepted as a
|
||||
// per-session frame even when it is well formed.
|
||||
expect(parseSessionSocketEvent({ type: "session.startup", cwd: "/repo", activity })).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves existing event acceptance without treating unknown types as realtime events", () => {
|
||||
expect(parseSessionSocketEvent({ type: "command.output", level: "info", message: "legacy" })).toMatchObject({ type: "command.output" });
|
||||
expect(parseRealtimeSocketEvent({ type: "future.notification", payload: {} })).toBeUndefined();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { realtimeEvents, sessionEvents } from "./api";
|
||||
import { parseSessionNotificationInboxEvent, parseSessionUnreadEvent } from "./api/parsers";
|
||||
import { parseSessionNotificationInboxEvent, parseSessionStartupProgressEvent, parseSessionUnreadEvent } from "./api/parsers";
|
||||
import type { GlobalSessionEvent, RealtimeEvent, SessionRef, SessionUiEvent } from "../../shared/apiTypes";
|
||||
|
||||
export type { GlobalSessionEvent, RealtimeEvent, SessionUiEvent } from "../../shared/apiTypes";
|
||||
@@ -160,6 +160,7 @@ export function parseSessionSocketEvent(event: unknown): SessionUiEvent | undefi
|
||||
|
||||
export function parseRealtimeSocketEvent(event: unknown): BrowserRealtimeEvent | undefined {
|
||||
if (eventType(event) === "sessions.unread") return safelyParseValidatedEvent(() => parseSessionUnreadEvent(event));
|
||||
if (eventType(event) === "session.startup") return safelyParseValidatedEvent(() => parseSessionStartupProgressEvent(event));
|
||||
if (isLegacyGlobalSessionEvent(event) || isLegacyRealtimeEvent(event)) return event;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user