Archived
feat: add machine federation
This commit is contained in:
@@ -15,6 +15,7 @@ import {
|
||||
parseGitDiffResponse,
|
||||
parseGitStatusResponse,
|
||||
parseMachine,
|
||||
parseMachineHealth,
|
||||
parseMachinesResponse,
|
||||
parseMessagePage,
|
||||
parseModelSelectionResponse,
|
||||
@@ -44,6 +45,7 @@ export const machinesApi = {
|
||||
machines: () => request("/api/machines", parseMachinesResponse),
|
||||
addMachine: (input: { name: string; baseUrl: string; token?: string }) => request("/api/machines", parseMachine, { method: "POST", body: JSON.stringify(input) }),
|
||||
deleteMachine: (machineId: string) => request(`/api/machines/${encodeURIComponent(machineId)}`, (value) => value, { method: "DELETE" }),
|
||||
health: (machineId: string) => request(`/api/machines/${encodeURIComponent(machineId)}/health`, parseMachineHealth),
|
||||
};
|
||||
|
||||
export const activityApi = {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ArchiveSessionsResponse, AuthProviderOption, AuthProviderStatus, AuthProvidersResponse, AuthStatusSource, AuthType, CommandOption, CommandResult, FileContentResponse, FileSuggestion, FileTreeEntry, FileTreeResponse, GitDiffResponse, GitFileState, GitStatusFile, GitStatusResponse, Machine, MachineKind, MachineStatus, MessagePage, ModelSelectionResponse, OAuthFlowState, PiWebComponentStatus, PiWebInstallationInfo, PiWebReleaseStatus, PiWebServiceComponent, PiWebStatusMessage, PiWebStatusResponse, PiWebStatusSeverity, Project, QueuedSessionMessage, SessionInfo, SessionModel, SessionStatus, SlashCommand, TerminalCommandRun, TerminalCommandRunStatus, TerminalInfo, ThinkingLevel, ThinkingLevelsResponse, Workspace, WorkspaceActivity, WorkspaceActivityResponse } from "../../../shared/apiTypes";
|
||||
import type { ArchiveSessionsResponse, AuthProviderOption, AuthProviderStatus, AuthProvidersResponse, AuthStatusSource, AuthType, CommandOption, CommandResult, FileContentResponse, FileSuggestion, FileTreeEntry, FileTreeResponse, GitDiffResponse, GitFileState, GitStatusFile, GitStatusResponse, Machine, MachineHealth, MachineKind, MachineStatus, MessagePage, ModelSelectionResponse, OAuthFlowState, PiWebComponentStatus, PiWebInstallationInfo, PiWebReleaseStatus, PiWebServiceComponent, PiWebStatusMessage, PiWebStatusResponse, PiWebStatusSeverity, Project, QueuedSessionMessage, SessionInfo, SessionModel, SessionStatus, SlashCommand, TerminalCommandRun, TerminalCommandRunStatus, TerminalInfo, ThinkingLevel, ThinkingLevelsResponse, Workspace, WorkspaceActivity, WorkspaceActivityResponse } from "../../../shared/apiTypes";
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
@@ -80,6 +80,21 @@ export function parseMachine(value: unknown): Machine {
|
||||
};
|
||||
}
|
||||
|
||||
export function parseMachineHealth(value: unknown): MachineHealth {
|
||||
const record = requireRecord(value);
|
||||
const status = optionalMachineStatus(record, "status");
|
||||
const error = optionalString(record, "error");
|
||||
return {
|
||||
machineId: requireString(record, "machineId"),
|
||||
ok: requireBoolean(record, "ok"),
|
||||
checkedAt: requireString(record, "checkedAt"),
|
||||
...(status === undefined ? {} : { status }),
|
||||
...(record["web"] === undefined ? {} : { web: parsePiWebComponentStatus(record["web"]) }),
|
||||
...(record["sessiond"] === undefined ? {} : { sessiond: parsePiWebComponentStatus(record["sessiond"]) }),
|
||||
...(error === undefined ? {} : { error }),
|
||||
};
|
||||
}
|
||||
|
||||
function requireMachineKind(record: Record<string, unknown>, key: string): MachineKind {
|
||||
const value = requireString(record, key);
|
||||
if (value !== "local" && value !== "remote") throw new Error(`Expected machine kind field: ${key}`);
|
||||
|
||||
@@ -44,7 +44,7 @@ describe("cached new sessions", () => {
|
||||
it("stores and reloads new sessions with a browser-cache marker", () => {
|
||||
const storage = new MemoryStorage();
|
||||
|
||||
rememberCachedNewSession(baseSession, storage);
|
||||
rememberCachedNewSession(baseSession, "local", storage);
|
||||
|
||||
const cached = loadCachedNewSessions(storage);
|
||||
expect(cached).toHaveLength(1);
|
||||
@@ -54,21 +54,30 @@ describe("cached new sessions", () => {
|
||||
|
||||
it("merges cached sessions for the selected cwd without duplicating server sessions", () => {
|
||||
const storage = new MemoryStorage();
|
||||
rememberCachedNewSession(baseSession, storage);
|
||||
rememberCachedNewSession({ ...baseSession, id: "other", cwd: "/other" }, storage);
|
||||
rememberCachedNewSession(baseSession, "local", storage);
|
||||
rememberCachedNewSession({ ...baseSession, id: "other", cwd: "/other" }, "local", storage);
|
||||
|
||||
expect(mergeCachedNewSessions("/repo", [], storage).map((session) => session.id)).toEqual(["session-1"]);
|
||||
expect(mergeCachedNewSessions("/repo", [baseSession], storage).map((session) => session.id)).toEqual(["session-1"]);
|
||||
expect(isCachedNewSessionInfo(mergeCachedNewSessions("/repo", [baseSession], storage)[0])).toBe(false);
|
||||
expect(mergeCachedNewSessions("/repo", [], "local", storage).map((session) => session.id)).toEqual(["session-1"]);
|
||||
expect(mergeCachedNewSessions("/repo", [baseSession], "local", storage).map((session) => session.id)).toEqual(["session-1"]);
|
||||
expect(isCachedNewSessionInfo(mergeCachedNewSessions("/repo", [baseSession], "local", storage)[0])).toBe(false);
|
||||
expect(loadCachedNewSessions(storage).map((session) => session.id)).toEqual(["other"]);
|
||||
});
|
||||
|
||||
it("forgets cached sessions", () => {
|
||||
const storage = new MemoryStorage();
|
||||
rememberCachedNewSession(baseSession, storage);
|
||||
rememberCachedNewSession(baseSession, "local", storage);
|
||||
|
||||
forgetCachedNewSession("session-1", storage);
|
||||
forgetCachedNewSession("session-1", "local", storage);
|
||||
|
||||
expect(loadCachedNewSessions(storage)).toEqual([]);
|
||||
});
|
||||
|
||||
it("keeps browser-cached sessions scoped by machine", () => {
|
||||
const storage = new MemoryStorage();
|
||||
rememberCachedNewSession(baseSession, "local", storage);
|
||||
rememberCachedNewSession({ ...baseSession, id: "session-2" }, "remote", storage);
|
||||
|
||||
expect(mergeCachedNewSessions("/repo", [], "local", storage).map((session) => session.id)).toEqual(["session-1"]);
|
||||
expect(mergeCachedNewSessions("/repo", [], "remote", storage).map((session) => session.id)).toEqual(["session-2"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,8 +2,9 @@ import type { SessionInfo } from "./api";
|
||||
|
||||
const storageKey = "pi-web:cached-new-sessions:v1";
|
||||
const markerProperty = "browserCachedNew";
|
||||
const defaultMachineId = "local";
|
||||
|
||||
export type CachedNewSessionInfo = SessionInfo & { browserCachedNew: true };
|
||||
export type CachedNewSessionInfo = SessionInfo & { browserCachedNew: true; machineId: string };
|
||||
|
||||
function browserStorage(): Storage | undefined {
|
||||
try {
|
||||
@@ -13,27 +14,27 @@ function browserStorage(): Storage | undefined {
|
||||
}
|
||||
}
|
||||
|
||||
export function rememberCachedNewSession(session: SessionInfo, storage = browserStorage()): void {
|
||||
export function rememberCachedNewSession(session: SessionInfo, machineId = defaultMachineId, storage = browserStorage()): void {
|
||||
if (session.messageCount !== 0 || session.archived === true) return;
|
||||
const sessions = loadCachedNewSessions(storage).filter((candidate) => candidate.id !== session.id);
|
||||
saveCachedNewSessions([markCachedNewSessionInfo(session), ...sessions], storage);
|
||||
const sessions = loadCachedNewSessions(storage).filter((candidate) => candidate.id !== session.id || candidate.machineId !== machineId);
|
||||
saveCachedNewSessions([markCachedNewSessionInfo(session, machineId), ...sessions], storage);
|
||||
}
|
||||
|
||||
export function markCachedNewSessionInfo(session: SessionInfo): CachedNewSessionInfo {
|
||||
return { ...session, browserCachedNew: true };
|
||||
export function markCachedNewSessionInfo(session: SessionInfo, machineId = defaultMachineId): CachedNewSessionInfo {
|
||||
return { ...session, browserCachedNew: true, machineId };
|
||||
}
|
||||
|
||||
export function forgetCachedNewSession(sessionId: string, storage = browserStorage()): void {
|
||||
const sessions = loadCachedNewSessions(storage).filter((session) => session.id !== sessionId);
|
||||
export function forgetCachedNewSession(sessionId: string, machineId = defaultMachineId, storage = browserStorage()): void {
|
||||
const sessions = loadCachedNewSessions(storage).filter((session) => session.id !== sessionId || session.machineId !== machineId);
|
||||
saveCachedNewSessions(sessions, storage);
|
||||
}
|
||||
|
||||
export function mergeCachedNewSessions(cwd: string, sessions: SessionInfo[], storage = browserStorage()): SessionInfo[] {
|
||||
export function mergeCachedNewSessions(cwd: string, sessions: SessionInfo[], machineId = defaultMachineId, storage = browserStorage()): SessionInfo[] {
|
||||
const sessionIds = new Set(sessions.map((session) => session.id));
|
||||
const cachedSessions = loadCachedNewSessions(storage);
|
||||
const retainedCachedSessions = cachedSessions.filter((session) => !sessionIds.has(session.id));
|
||||
const retainedCachedSessions = cachedSessions.filter((session) => session.machineId !== machineId || !sessionIds.has(session.id));
|
||||
if (retainedCachedSessions.length !== cachedSessions.length) saveCachedNewSessions(retainedCachedSessions, storage);
|
||||
const cached = retainedCachedSessions.filter((session) => session.cwd === cwd);
|
||||
const cached = retainedCachedSessions.filter((session) => session.machineId === machineId && session.cwd === cwd);
|
||||
return [...cached, ...sessions];
|
||||
}
|
||||
|
||||
@@ -53,6 +54,7 @@ export function stripCachedNewSessionMarker(session: SessionInfo): SessionInfo {
|
||||
messageCount: session.messageCount,
|
||||
firstMessage: session.firstMessage,
|
||||
...(session.parentSessionPath === undefined ? {} : { parentSessionPath: session.parentSessionPath }),
|
||||
...("machineId" in session && typeof session.machineId === "string" ? { machineId: session.machineId } : { machineId: defaultMachineId }),
|
||||
...(session.archived === true ? { archived: true } : {}),
|
||||
...(session.archivedAt === undefined ? {} : { archivedAt: session.archivedAt }),
|
||||
};
|
||||
@@ -91,6 +93,7 @@ function parseCachedSession(value: unknown): CachedNewSessionInfo[] {
|
||||
if (id === undefined || path === undefined || cwd === undefined || created === undefined || modified === undefined || firstMessage === undefined || messageCount !== 0) return [];
|
||||
const name = optionalStringField(value, "name");
|
||||
const parentSessionPath = optionalStringField(value, "parentSessionPath");
|
||||
const machineId = optionalStringField(value, "machineId") ?? defaultMachineId;
|
||||
return [{
|
||||
id,
|
||||
path,
|
||||
@@ -101,6 +104,7 @@ function parseCachedSession(value: unknown): CachedNewSessionInfo[] {
|
||||
messageCount,
|
||||
firstMessage,
|
||||
...(parentSessionPath === undefined ? {} : { parentSessionPath }),
|
||||
machineId,
|
||||
browserCachedNew: true,
|
||||
}];
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { LitElement, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators.js";
|
||||
import type { Machine } from "../api";
|
||||
import type { Machine, MachineHealth } from "../api";
|
||||
import { activateSelectableRow, activateSelectableRowFromKeyboard } from "./selectableRow";
|
||||
import { listStyles } from "./shared";
|
||||
|
||||
@@ -8,6 +8,7 @@ import { listStyles } from "./shared";
|
||||
export class MachineList extends LitElement {
|
||||
@property({ attribute: false }) machines: Machine[] = [];
|
||||
@property({ attribute: false }) selected?: Machine;
|
||||
@property({ attribute: false }) statuses: Record<string, MachineHealth> = {};
|
||||
@property({ type: Boolean, reflect: true }) collapsible = false;
|
||||
@property({ type: Boolean, reflect: true }) collapsed = false;
|
||||
@property({ attribute: false }) onSelect?: (machine: Machine) => void;
|
||||
@@ -17,19 +18,23 @@ export class MachineList extends LitElement {
|
||||
return html`
|
||||
<section>
|
||||
<h2>${this.renderHeading()}</h2>
|
||||
${this.collapsed ? null : this.machines.map((machine) => html`
|
||||
<div
|
||||
class=${`action-row ${this.selected?.id === machine.id ? "selected" : ""}`}
|
||||
tabindex="0"
|
||||
title=${machine.kind === "remote" ? "Remote project browsing is not available yet" : machine.baseUrl ?? machine.name}
|
||||
@click=${(event: MouseEvent) => { activateSelectableRow(event, () => this.onSelect?.(machine)); }}
|
||||
@keydown=${(event: KeyboardEvent) => { activateSelectableRowFromKeyboard(event, () => this.onSelect?.(machine)); }}
|
||||
>
|
||||
<div class="action-main">
|
||||
<span class="action-name">${machine.name}</span><small>${machine.kind === "local" ? "Local Pi Web" : `${machine.baseUrl ?? "Remote Pi Web"} · projects coming soon`}</small>
|
||||
${this.collapsed ? null : this.machines.map((machine) => {
|
||||
const status = this.statuses[machine.id]?.status ?? machine.status ?? "unknown";
|
||||
const statusLabel = status === "online" ? "online" : status === "offline" ? "offline" : status === "error" ? "error" : "unknown";
|
||||
return html`
|
||||
<div
|
||||
class=${`action-row ${this.selected?.id === machine.id ? "selected" : ""}`}
|
||||
tabindex="0"
|
||||
title=${machine.baseUrl ?? machine.name}
|
||||
@click=${(event: MouseEvent) => { activateSelectableRow(event, () => this.onSelect?.(machine)); }}
|
||||
@keydown=${(event: KeyboardEvent) => { activateSelectableRowFromKeyboard(event, () => this.onSelect?.(machine)); }}
|
||||
>
|
||||
<div class="action-main">
|
||||
<span class="action-name">${machine.name}</span><small>${machine.kind === "local" ? "Local Pi Web" : machine.baseUrl ?? "Remote Pi Web"} · ${statusLabel}</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`)}
|
||||
`;
|
||||
})}
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
@@ -258,6 +258,7 @@ export class PiWebApp extends LitElement {
|
||||
this.state = { ...this.state, ...patch };
|
||||
this.handleActivityTransition(previous, this.state);
|
||||
this.handleWorkspaceChange(previous, this.state);
|
||||
this.handleMachineChange(previous, this.state);
|
||||
}
|
||||
|
||||
private async loadProjectsAndRestoreRoute() {
|
||||
@@ -435,14 +436,18 @@ export class PiWebApp extends LitElement {
|
||||
private rememberSelectedTerminal(terminalId: string | undefined): void {
|
||||
const workspace = this.state.selectedWorkspace;
|
||||
if (workspace === undefined) return;
|
||||
if (terminalId === undefined) this.terminalSelection.forgetWorkspace(workspace.path);
|
||||
else this.terminalSelection.rememberTerminal(workspace.path, terminalId);
|
||||
if (terminalId === undefined) this.terminalSelection.forgetWorkspace(this.terminalWorkspaceKey(workspace));
|
||||
else this.terminalSelection.rememberTerminal(this.terminalWorkspaceKey(workspace), terminalId);
|
||||
}
|
||||
|
||||
private writeSelectedTerminalToUrl(terminalId: string | undefined, options?: { replace?: boolean | undefined }): void {
|
||||
setNamespacedQueryKey(TERMINAL_ROUTE_NAMESPACE, "terminal", terminalId, options);
|
||||
}
|
||||
|
||||
private terminalWorkspaceKey(workspace: Workspace): string {
|
||||
return `${selectedMachineId(this.state)}:${workspace.path}`;
|
||||
}
|
||||
|
||||
private selectMainView(view: AppState["mainView"]) {
|
||||
if (view !== "navigation" && view !== "chat") {
|
||||
this.openWorkspaceTool(view);
|
||||
@@ -457,7 +462,7 @@ export class PiWebApp extends LitElement {
|
||||
if (previous.selectedWorkspace?.id === next.selectedWorkspace?.id) return;
|
||||
this.terminalAutoStartWorkspaceId = undefined;
|
||||
this.activeTerminalIds.clear();
|
||||
const selectedTerminalId = this.routeRestoreInProgress ? this.restoringRouteTerminalId : next.selectedWorkspace === undefined ? undefined : this.terminalSelection.latestTerminalId(next.selectedWorkspace.path);
|
||||
const selectedTerminalId = this.routeRestoreInProgress ? this.restoringRouteTerminalId : next.selectedWorkspace === undefined ? undefined : this.terminalSelection.latestTerminalId(this.terminalWorkspaceKey(next.selectedWorkspace));
|
||||
this.setState({ activeTerminalCount: 0, selectedTerminalId });
|
||||
if (!this.routeRestoreInProgress) this.writeSelectedTerminalToUrl(selectedTerminalId, { replace: true });
|
||||
if (next.selectedWorkspace === undefined) return;
|
||||
@@ -524,6 +529,15 @@ export class PiWebApp extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private handleMachineChange(previous: AppState, next: AppState): void {
|
||||
if ((previous.selectedMachine?.id ?? "local") === (next.selectedMachine?.id ?? "local")) return;
|
||||
this.sessions.clearActiveSession();
|
||||
this.realtime.close();
|
||||
this.connectRealtime();
|
||||
this.activeTerminalIds.clear();
|
||||
this.git.updatePolling();
|
||||
}
|
||||
|
||||
private refreshSelectedWorkspaceTool(tool: QualifiedContributionId): void {
|
||||
if (tool === "core:workspace.files") void this.files.refreshFiles();
|
||||
if (tool === "core:workspace.git") void this.git.refreshGit();
|
||||
@@ -554,6 +568,7 @@ export class PiWebApp extends LitElement {
|
||||
<machine-list
|
||||
.machines=${this.state.machines}
|
||||
.selected=${this.state.selectedMachine}
|
||||
.statuses=${this.state.machineStatuses}
|
||||
.collapsible=${this.isMobileNavigationLayout}
|
||||
.collapsed=${this.isNavigationSectionCollapsed("machines")}
|
||||
.onToggleCollapsed=${() => { this.toggleNavigationSection("machines"); }}
|
||||
@@ -758,6 +773,10 @@ export class PiWebApp extends LitElement {
|
||||
openActionPalette: () => { this.setState({ actionPaletteOpen: true }); },
|
||||
focusPrompt: () => { this.promptEditor?.focusInput(); },
|
||||
addProject: () => { this.setState({ projectDialogOpen: true }); },
|
||||
addMachine: () => this.addMachineFromPrompt(),
|
||||
refreshSelectedMachine: () => this.machines.refreshMachineHealth(),
|
||||
removeSelectedMachine: () => this.removeSelectedMachine(),
|
||||
openSelectedMachine: () => { this.openSelectedMachine(); },
|
||||
configureAuth: () => this.auth.openLogin(),
|
||||
logoutAuth: () => this.auth.openLogout(),
|
||||
openThemePicker: () => { this.openThemeDialog(); },
|
||||
@@ -878,6 +897,28 @@ export class PiWebApp extends LitElement {
|
||||
}
|
||||
}
|
||||
|
||||
private async addMachineFromPrompt(): Promise<void> {
|
||||
const name = window.prompt("Machine name", "Dev Box")?.trim();
|
||||
if (name === undefined || name === "") return;
|
||||
const baseUrl = window.prompt("Remote PI WEB base URL", "http://127.0.0.1:8504")?.trim();
|
||||
if (baseUrl === undefined || baseUrl === "") return;
|
||||
const token = window.prompt("Bearer token (optional)", "")?.trim();
|
||||
await this.machines.addMachine({ name, baseUrl, ...(token === undefined || token === "" ? {} : { token }) });
|
||||
}
|
||||
|
||||
private async removeSelectedMachine(): Promise<void> {
|
||||
const machine = this.state.selectedMachine;
|
||||
if (machine === undefined || machine.kind === "local") return;
|
||||
if (!window.confirm(`Remove ${machine.name}?\n\nThis only removes it from this PI WEB gateway.`)) return;
|
||||
await this.machines.deleteMachine(machine);
|
||||
}
|
||||
|
||||
private openSelectedMachine(): void {
|
||||
const machine = this.state.selectedMachine;
|
||||
if (machine?.kind !== "remote" || machine.baseUrl === undefined) return;
|
||||
window.open(machine.baseUrl, "_blank", "noopener,noreferrer");
|
||||
}
|
||||
|
||||
private runAction(action: AppAction): void {
|
||||
void Promise.resolve()
|
||||
.then(() => action.run())
|
||||
@@ -1025,9 +1066,11 @@ export class PiWebApp extends LitElement {
|
||||
}
|
||||
|
||||
private renderContextBar() {
|
||||
const machine = this.state.selectedMachine;
|
||||
const project = this.state.selectedProject;
|
||||
const workspace = this.state.selectedWorkspace;
|
||||
const session = this.state.selectedSession;
|
||||
const machineLabel = machineContextLabel(machine);
|
||||
const projectLabel = projectContextLabel(project);
|
||||
const showRefresh = this.shouldShowAppRefreshInContextBar();
|
||||
const workspaceLabel = workspaceContextLabel(workspace);
|
||||
@@ -1036,6 +1079,12 @@ export class PiWebApp extends LitElement {
|
||||
<nav class=${this.contextBarClass()} aria-label="Current location">
|
||||
<span class="context-bar-label">Location</span>
|
||||
<ol class="context-items" @scroll=${this.onContextScroll}>
|
||||
<li class="context-item">
|
||||
<button type="button" class=${machine === undefined ? "context-chip empty" : "context-chip"} title=${machineContextTitle(machine)} aria-label=${`Machine: ${machineLabel}. Open machine selection.`} @click=${() => { this.openNavigationSection("machines"); }}>
|
||||
<span class="context-kind">Machine</span>
|
||||
<span class="context-value">${machineLabel}</span>
|
||||
</button>
|
||||
</li>
|
||||
<li class="context-item">
|
||||
<button type="button" class=${project === undefined ? "context-chip empty" : "context-chip"} title=${projectContextTitle(project)} aria-label=${`Project: ${projectLabel}. Open project selection.`} @click=${() => { this.openNavigationSection("projects"); }}>
|
||||
<span class="context-kind">Project</span>
|
||||
@@ -1244,7 +1293,7 @@ export class PiWebApp extends LitElement {
|
||||
${state.selectedSession ? html`
|
||||
<chat-view .sessionId=${state.selectedSession.id} .messages=${state.messages} .messageStart=${state.messagePageStart} .messageTotal=${state.messagePageTotal} .hasMore=${state.messagePageStart > 0} .loadingMore=${state.isLoadingEarlierMessages} .isReceivingPartialStream=${state.isReceivingPartialStream} .isCompacting=${state.status?.isCompacting === true} .pendingMessageCount=${state.status?.pendingMessageCount ?? 0} .status=${state.status} .activity=${state.activity} .onLoadMore=${() => this.withChatPrependTransition(() => this.sessions.loadEarlierMessages())}></chat-view>
|
||||
<prompt-editor .sessionId=${state.selectedSession.id} .cwd=${state.selectedWorkspace?.path} .machineId=${selectedMachineId(state)} .disabled=${state.selectedSession.archived === true} .canSteer=${state.status?.isStreaming === true} .isCompacting=${state.status?.isCompacting === true} .canStop=${state.status?.isStreaming === true || state.status?.isBashRunning === true || state.status?.isCompacting === true || (state.status?.pendingMessageCount ?? 0) > 0} .status=${state.status} .onSend=${(text: string, streamingBehavior?: "steer" | "followUp") => { this.sendPrompt(text, streamingBehavior); }} .onStop=${() => this.sessions.stopActiveWork()} .onSelectModel=${() => { void this.openModelDialog(); }} .onSelectThinking=${() => { void this.openThinkingDialog(); }}></prompt-editor>
|
||||
<status-bar .status=${state.status} .workspace=${state.selectedWorkspace} .workspaceLabelItems=${state.selectedWorkspace === undefined ? [] : this.plugins.getWorkspaceLabelItems(state, state.selectedWorkspace)}></status-bar>
|
||||
<status-bar .status=${state.status} .machine=${state.selectedMachine} .workspace=${state.selectedWorkspace} .workspaceLabelItems=${state.selectedWorkspace === undefined ? [] : this.plugins.getWorkspaceLabelItems(state, state.selectedWorkspace)}></status-bar>
|
||||
${state.commandDialog !== undefined ? html`<command-picker .title=${state.commandDialog.title} .options=${state.commandDialog.options} .onPick=${(value: string) => this.sessions.respondToCommand(state.commandDialog?.requestId ?? "", value)} .onCancel=${() => { this.sessions.cancelCommand(); }}></command-picker>` : null}
|
||||
${state.modelDialog !== undefined ? html`<command-picker title=${state.modelDialog.title} .searchable=${true} .options=${state.modelDialog.options} .selectedValue=${state.modelDialog.selectedValue} .onPick=${(value: string) => { void this.pickModel(value); }} .onCancel=${() => { this.setState({ modelDialog: undefined }); }}></command-picker>` : null}
|
||||
${state.thinkingDialog !== undefined ? html`<command-picker title=${state.thinkingDialog.title} .options=${state.thinkingDialog.options} .selectedValue=${state.thinkingDialog.selectedValue} .onPick=${(value: string) => { void this.pickThinking(value); }} .onCancel=${() => { this.setState({ thinkingDialog: undefined }); }}></command-picker>` : null}
|
||||
@@ -1270,6 +1319,14 @@ function createPluginRegistry(): PluginRegistry {
|
||||
return registry;
|
||||
}
|
||||
|
||||
function machineContextLabel(machine: Machine | undefined): string {
|
||||
return machine === undefined ? "No machine" : `${machine.name}${machine.kind === "remote" ? " · remote" : ""}`;
|
||||
}
|
||||
|
||||
function machineContextTitle(machine: Machine | undefined): string {
|
||||
return machine === undefined ? "No machine selected" : machine.baseUrl ?? machine.name;
|
||||
}
|
||||
|
||||
function projectContextLabel(project: Project | undefined): string {
|
||||
return project?.name ?? "No project";
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { LitElement, html, type PropertyValues } from "lit";
|
||||
import { customElement, property, query, state } from "lit/decorators.js";
|
||||
import { api, type FileSuggestion, type SessionStatus, type SlashCommand } from "../api";
|
||||
import { inputModeForDraft } from "../inputModes";
|
||||
import { machineSessionKey } from "../machineKeys";
|
||||
import { clearDraft, loadDraft, saveDraft } from "../promptDraftStorage";
|
||||
import { promptEditorStyles, type CompletionItem } from "./shared";
|
||||
import "./AutocompleteMenu";
|
||||
@@ -35,10 +36,13 @@ export class PromptEditor extends LitElement {
|
||||
private readonly readOnlyCompartment = new Compartment();
|
||||
|
||||
protected override willUpdate(changed: PropertyValues<this>) {
|
||||
if (!changed.has("sessionId")) return;
|
||||
const previousSessionId = changed.get("sessionId");
|
||||
if (previousSessionId !== undefined && previousSessionId !== "") saveDraft(previousSessionId, this.draft);
|
||||
this.draft = this.sessionId !== undefined && this.sessionId !== "" ? loadDraft(this.sessionId) : "";
|
||||
if (!changed.has("sessionId") && !changed.has("machineId")) return;
|
||||
const previousSessionId = changed.has("sessionId") ? changed.get("sessionId") : this.sessionId;
|
||||
const previousMachineId = changed.has("machineId") ? changed.get("machineId") : this.machineId;
|
||||
const previousKey = draftStorageKey(previousMachineId, previousSessionId);
|
||||
if (previousKey !== undefined) saveDraft(previousKey, this.draft);
|
||||
const currentKey = draftStorageKey(this.machineId, this.sessionId);
|
||||
this.draft = currentKey !== undefined ? loadDraft(currentKey) : "";
|
||||
this.completions = [];
|
||||
this.selectedIndex = 0;
|
||||
}
|
||||
@@ -49,7 +53,7 @@ export class PromptEditor extends LitElement {
|
||||
|
||||
protected override updated(changed: PropertyValues) {
|
||||
if (changed.has("disabled")) this.updateEditorDisabledState();
|
||||
if (changed.has("draft") || changed.has("sessionId")) this.syncEditorDoc();
|
||||
if (changed.has("draft") || changed.has("sessionId") || changed.has("machineId")) this.syncEditorDoc();
|
||||
}
|
||||
|
||||
override disconnectedCallback(): void {
|
||||
@@ -156,7 +160,8 @@ export class PromptEditor extends LitElement {
|
||||
|
||||
private updateDraft(value: string) {
|
||||
this.draft = value;
|
||||
if (this.sessionId !== undefined && this.sessionId !== "") saveDraft(this.sessionId, this.draft);
|
||||
const key = draftStorageKey(this.machineId, this.sessionId);
|
||||
if (key !== undefined) saveDraft(key, this.draft);
|
||||
void this.refreshCompletions();
|
||||
}
|
||||
|
||||
@@ -279,7 +284,8 @@ export class PromptEditor extends LitElement {
|
||||
const text = this.draft.trim();
|
||||
if (text === "" || this.disabled) return;
|
||||
this.draft = "";
|
||||
if (this.sessionId !== undefined && this.sessionId !== "") clearDraft(this.sessionId);
|
||||
const key = draftStorageKey(this.machineId, this.sessionId);
|
||||
if (key !== undefined) clearDraft(key);
|
||||
this.completions = [];
|
||||
this.onSend?.(text, this.canSteer || this.isCompacting ? streamingBehavior : undefined);
|
||||
}
|
||||
@@ -287,6 +293,12 @@ export class PromptEditor extends LitElement {
|
||||
static override styles = promptEditorStyles;
|
||||
}
|
||||
|
||||
function draftStorageKey(machineId: unknown, sessionId: unknown): string | undefined {
|
||||
if (typeof machineId !== "string" || machineId === "") return undefined;
|
||||
if (typeof sessionId !== "string" || sessionId === "") return undefined;
|
||||
return machineSessionKey(machineId, sessionId);
|
||||
}
|
||||
|
||||
function fileInsertText(path: string, pathMode: boolean, quoted: boolean): string {
|
||||
const prefix = pathMode ? "" : "@";
|
||||
if (!quoted && !path.includes(" ")) return `${prefix}${path}`;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { LitElement, html } from "lit";
|
||||
import { customElement, property } from "lit/decorators.js";
|
||||
import type { SessionStatus, Workspace } from "../api";
|
||||
import type { Machine, SessionStatus, Workspace } from "../api";
|
||||
import type { WorkspaceLabelItem } from "../plugins/types";
|
||||
import { formatCost, formatTokenCount } from "../utils/format";
|
||||
import { statusBarStyles } from "./shared";
|
||||
@@ -9,6 +9,7 @@ import { renderWorkspaceLabel } from "./workspaceLabel";
|
||||
@customElement("status-bar")
|
||||
export class StatusBar extends LitElement {
|
||||
@property({ attribute: false }) status?: SessionStatus;
|
||||
@property({ attribute: false }) machine?: Machine;
|
||||
@property({ attribute: false }) workspace?: Workspace;
|
||||
@property({ attribute: false }) workspaceLabelItems: WorkspaceLabelItem[] = [];
|
||||
|
||||
@@ -24,6 +25,7 @@ export class StatusBar extends LitElement {
|
||||
const tokens = status.tokens;
|
||||
return html`
|
||||
<div class="bar">
|
||||
<span>${this.machine?.name ?? "Local"}</span>
|
||||
<span>${renderWorkspaceLabel(this.workspace?.label ?? "workspace", this.workspaceLabelItems, this.workspace?.path)}</span>
|
||||
<span>↑${formatTokenCount(tokens.input)}</span>
|
||||
<span>↓${formatTokenCount(tokens.output)}</span>
|
||||
|
||||
@@ -92,8 +92,8 @@ export class AuthController {
|
||||
const { providers } = await this.api.authProviders({ mode: "logout", machineId: selectedMachineId(this.getState()) });
|
||||
if (providerId !== undefined && providerId !== "") {
|
||||
const provider = providers.find((candidate) => candidate.id === providerId);
|
||||
if (provider !== undefined) await this.logoutProvider(provider.id);
|
||||
else this.setState({ error: `No stored credentials for ${providerId}` });
|
||||
if (provider !== undefined && !this.rejectRemoteOAuth("logout", provider)) await this.logoutProvider(provider.id);
|
||||
else if (provider === undefined) this.setState({ error: `No stored credentials for ${providerId}` });
|
||||
return;
|
||||
}
|
||||
this.setState({ authDialog: { step: "logout", providers } });
|
||||
@@ -103,6 +103,9 @@ export class AuthController {
|
||||
}
|
||||
|
||||
async logoutProvider(providerId: string): Promise<void> {
|
||||
const dialog = this.getState().authDialog;
|
||||
const provider = dialog?.step === "logout" ? dialog.providers.find((candidate) => candidate.id === providerId) : undefined;
|
||||
if (provider !== undefined && this.rejectRemoteOAuth("logout", provider)) return;
|
||||
try {
|
||||
await this.api.logoutProvider(providerId, selectedMachineId(this.getState()));
|
||||
this.closeDialog();
|
||||
@@ -179,6 +182,7 @@ export class AuthController {
|
||||
}
|
||||
|
||||
private async startOAuth(provider: AuthProviderOption): Promise<void> {
|
||||
if (this.rejectRemoteOAuth("login", provider)) return;
|
||||
try {
|
||||
const flow = await this.api.startOAuthLogin(provider.id, selectedMachineId(this.getState()));
|
||||
this.updateOAuthFlow(flow);
|
||||
@@ -188,6 +192,14 @@ export class AuthController {
|
||||
}
|
||||
}
|
||||
|
||||
private rejectRemoteOAuth(action: "login" | "logout", provider: AuthProviderOption): boolean {
|
||||
const machine = this.getState().selectedMachine;
|
||||
if (provider.authType !== "oauth" || machine?.kind !== "remote") return false;
|
||||
const where = machine.baseUrl ?? "that remote PI WEB instance";
|
||||
this.setState({ error: `OAuth ${action} for remote machines must be configured directly on ${where}.` });
|
||||
return true;
|
||||
}
|
||||
|
||||
private updateOAuthFlow(flow: OAuthFlowState): void {
|
||||
if (flow.status === "complete") {
|
||||
this.stopPolling();
|
||||
|
||||
@@ -12,6 +12,7 @@ export class MachineController {
|
||||
const machines = await api.machines();
|
||||
const selectedMachine = machines.find((machine) => machine.id === (routeMachineId ?? "local")) ?? machines.find((machine) => machine.id === "local") ?? machines[0];
|
||||
this.setState({ machines, selectedMachine });
|
||||
void this.refreshMachineHealthFor(machines);
|
||||
} catch (error) {
|
||||
this.setState({ error: String(error) });
|
||||
} finally {
|
||||
@@ -33,9 +34,61 @@ export class MachineController {
|
||||
messagePageTotal: 0,
|
||||
status: undefined,
|
||||
activity: undefined,
|
||||
sessionStatuses: {},
|
||||
sessionActivities: {},
|
||||
workspaceActivities: {},
|
||||
workspacesByProjectId: {},
|
||||
...resetWorkspaceScopedState(),
|
||||
});
|
||||
if (options.updateUrl !== false) this.updateUrl();
|
||||
await this.projects.loadProjects();
|
||||
void this.refreshMachineHealth(machine.id);
|
||||
}
|
||||
|
||||
async addMachine(input: { name: string; baseUrl: string; token?: string }): Promise<void> {
|
||||
this.setState({ error: "" });
|
||||
try {
|
||||
const machine = await api.addMachine(input);
|
||||
this.setState({ machines: [...this.getState().machines.filter((candidate) => candidate.id !== machine.id), machine] });
|
||||
await this.selectMachine(machine);
|
||||
} catch (error) {
|
||||
this.setState({ error: String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
async deleteMachine(machine: Machine | undefined = this.getState().selectedMachine): Promise<void> {
|
||||
if (machine === undefined) return;
|
||||
if (machine.kind === "local") {
|
||||
this.setState({ error: "The local machine cannot be removed." });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await api.deleteMachine(machine.id);
|
||||
const machines = this.getState().machines.filter((candidate) => candidate.id !== machine.id);
|
||||
const local = machines.find((candidate) => candidate.id === "local") ?? machines[0];
|
||||
this.setState({ machines, machineStatuses: omitKey(this.getState().machineStatuses, machine.id) });
|
||||
if (this.getState().selectedMachine?.id === machine.id && local !== undefined) await this.selectMachine(local);
|
||||
} catch (error) {
|
||||
this.setState({ error: String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
async refreshMachineHealth(machineId = this.getState().selectedMachine?.id ?? "local"): Promise<void> {
|
||||
try {
|
||||
const health = await api.health(machineId);
|
||||
this.setState({ machineStatuses: { ...this.getState().machineStatuses, [health.machineId]: health } });
|
||||
} catch (error) {
|
||||
this.setState({ error: String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
private async refreshMachineHealthFor(machines: Machine[]): Promise<void> {
|
||||
const results = await Promise.allSettled(machines.map((machine) => api.health(machine.id)));
|
||||
const health = Object.fromEntries(results.flatMap((result) => result.status === "fulfilled" ? [[result.value.machineId, result.value] as const] : []));
|
||||
if (Object.keys(health).length > 0) this.setState({ machineStatuses: { ...this.getState().machineStatuses, ...health } });
|
||||
}
|
||||
}
|
||||
|
||||
function omitKey<T>(record: Record<string, T>, keyToOmit: string): Record<string, T> {
|
||||
return Object.fromEntries(Object.entries(record).filter(([key]) => key !== keyToOmit));
|
||||
}
|
||||
|
||||
@@ -6,11 +6,6 @@ export class ProjectController {
|
||||
constructor(private readonly getState: GetState, private readonly setState: SetState, private readonly workspaces: WorkspaceController) {}
|
||||
|
||||
async loadProjects() {
|
||||
const machine = this.getState().selectedMachine;
|
||||
if (machine?.kind === "remote") {
|
||||
this.setState({ projects: [], workspacesByProjectId: {}, error: "Remote project browsing is not available yet." });
|
||||
return;
|
||||
}
|
||||
this.setState({ error: "", isLoadingProjects: true });
|
||||
try {
|
||||
const projects = await api.projects(selectedMachineId(this.getState()));
|
||||
@@ -25,10 +20,6 @@ export class ProjectController {
|
||||
}
|
||||
|
||||
async addProject(path: string, create?: boolean) {
|
||||
if (this.getState().selectedMachine?.kind === "remote") {
|
||||
this.setState({ error: "Adding projects to remote machines is not available yet." });
|
||||
return;
|
||||
}
|
||||
if (path.trim() === "") return;
|
||||
try {
|
||||
const project = await api.addProject(path.trim(), undefined, create, selectedMachineId(this.getState()));
|
||||
|
||||
@@ -2,6 +2,7 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import { api as defaultApi, type MessagePage, type SessionActivity, type SessionInfo, type SessionStatus, type Workspace } from "../api";
|
||||
import { isCachedNewSessionInfo, loadCachedNewSessions, markCachedNewSessionInfo, rememberCachedNewSession } from "../cachedNewSessions";
|
||||
import { initialAppState, type AppState } from "../appState";
|
||||
import { machineSessionKey } from "../machineKeys";
|
||||
import { loadDraft, saveDraft } from "../promptDraftStorage";
|
||||
import { SessionController, type SessionEventSocket } from "./sessionController";
|
||||
import { InMemorySessionSelectionMemory } from "./sessionSelection";
|
||||
@@ -170,7 +171,7 @@ describe("SessionController", () => {
|
||||
const storage = new MemoryStorage();
|
||||
Object.defineProperty(globalThis, "localStorage", { value: storage, configurable: true });
|
||||
rememberCachedNewSession(oldSession);
|
||||
saveDraft(oldSession.id, "draft text");
|
||||
saveDraft(sessionKey(oldSession.id), "draft text");
|
||||
|
||||
let state: AppState = { ...initialAppState(), selectedWorkspace: workspace, sessions: [markCachedNewSessionInfo(oldSession)] };
|
||||
const urlUpdates: ({ replace?: boolean | undefined } | undefined)[] = [];
|
||||
@@ -197,8 +198,8 @@ describe("SessionController", () => {
|
||||
expect(state.selectedSession?.id).toBe(replacementSession.id);
|
||||
expect(state.sessions.map((session) => session.id)).toEqual([replacementSession.id]);
|
||||
expect(socket.connectedSessionIds).toEqual([oldSession.id, replacementSession.id]);
|
||||
expect(loadDraft(oldSession.id)).toBe("");
|
||||
expect(loadDraft(replacementSession.id)).toBe("draft text");
|
||||
expect(loadDraft(sessionKey(oldSession.id))).toBe("");
|
||||
expect(loadDraft(sessionKey(replacementSession.id))).toBe("draft text");
|
||||
expect(loadCachedNewSessions().map((session) => session.id)).toEqual([replacementSession.id]);
|
||||
expect(urlUpdates).toEqual([{ replace: true }]);
|
||||
});
|
||||
@@ -232,7 +233,7 @@ describe("SessionController", () => {
|
||||
await controller.respondToCommand("r1", "m1");
|
||||
|
||||
expect(state.commandDialog).toBeUndefined();
|
||||
expect(loadDraft(replacementSession.id)).toBe("fork me");
|
||||
expect(loadDraft(sessionKey(replacementSession.id))).toBe("fork me");
|
||||
});
|
||||
|
||||
it("forgets the selected active session when archiving leaves only archived sessions", async () => {
|
||||
@@ -315,3 +316,7 @@ describe("SessionController", () => {
|
||||
expect(urlUpdates).toEqual([undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
function sessionKey(sessionId: string): string {
|
||||
return machineSessionKey("local", sessionId);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { api as defaultApi, type CommandResult, type SessionActivity, type Sessi
|
||||
import type { AppState } from "../appState";
|
||||
import { forgetCachedNewSession, isCachedNewSessionInfo, markCachedNewSessionInfo, rememberCachedNewSession, stripCachedNewSessionMarker } from "../cachedNewSessions";
|
||||
import { textMessage } from "../chatMessages";
|
||||
import { machineSessionKey } from "../machineKeys";
|
||||
import { clearDraft, moveDraft, saveDraft } from "../promptDraftStorage";
|
||||
import { ChatTranscriptStore } from "../chatTranscriptStore";
|
||||
import { isShellInput } from "../inputModes";
|
||||
@@ -67,7 +68,7 @@ export class SessionController {
|
||||
deselectSession(options?: { forgetRememberedSelection?: boolean | undefined; updateUrl?: boolean | undefined }) {
|
||||
const state = this.getState();
|
||||
const cwd = state.selectedSession?.cwd ?? state.selectedWorkspace?.path;
|
||||
if (options?.forgetRememberedSelection === true && cwd !== undefined) this.sessionSelection.forgetWorkspace(cwd);
|
||||
if (options?.forgetRememberedSelection === true && cwd !== undefined) this.sessionSelection.forgetWorkspace(this.workspaceSelectionKey(cwd));
|
||||
this.clearActiveSession();
|
||||
if (options?.updateUrl !== false) this.updateUrl();
|
||||
}
|
||||
@@ -82,9 +83,10 @@ export class SessionController {
|
||||
const workspace = this.getState().selectedWorkspace;
|
||||
if (!workspace) return;
|
||||
try {
|
||||
const session = await this.api.startSession(workspace.path, selectedMachineId(this.getState()));
|
||||
rememberCachedNewSession(session);
|
||||
const cachedSession = markCachedNewSessionInfo(session);
|
||||
const machineId = selectedMachineId(this.getState());
|
||||
const session = await this.api.startSession(workspace.path, machineId);
|
||||
rememberCachedNewSession(session, machineId);
|
||||
const cachedSession = markCachedNewSessionInfo(session, machineId);
|
||||
this.setState({ sessions: [cachedSession, ...this.getState().sessions] });
|
||||
await this.selectSession(cachedSession);
|
||||
} catch (error) {
|
||||
@@ -93,16 +95,17 @@ export class SessionController {
|
||||
}
|
||||
|
||||
preferredSession(cwd: string, sessions: SessionInfo[], targetSessionId: string | undefined): SessionInfo | undefined {
|
||||
return selectPreferredSession(sessions, { targetSessionId, latestSessionId: this.sessionSelection.latestSessionId(cwd) });
|
||||
return selectPreferredSession(sessions, { targetSessionId, latestSessionId: this.sessionSelection.latestSessionId(this.workspaceSelectionKey(cwd)) });
|
||||
}
|
||||
|
||||
async selectSession(session: SessionInfo, options?: { updateUrl?: boolean | undefined }) {
|
||||
this.sessionSelection.rememberSession(session);
|
||||
this.sessionSelection.rememberSession({ ...session, cwd: this.workspaceSelectionKey(session.cwd) });
|
||||
const seq = ++this.selectionSeq;
|
||||
this.socket.close();
|
||||
this.catchupStreamSessionId = undefined;
|
||||
this.clearPendingTranscriptEvents();
|
||||
const cached = this.transcripts.cachedView(session.id);
|
||||
const transcriptKey = this.sessionCacheKey(session.id);
|
||||
const cached = this.transcripts.cachedView(transcriptKey);
|
||||
this.setState({
|
||||
selectedSession: session,
|
||||
...cached,
|
||||
@@ -115,7 +118,7 @@ export class SessionController {
|
||||
if (session.archived === true) {
|
||||
const page = await this.api.messages(session.id, { limit: MESSAGE_PAGE_SIZE }, selectedMachineId(this.getState()));
|
||||
if (seq !== this.selectionSeq || this.getState().selectedSession?.id !== session.id) return;
|
||||
const history = this.transcripts.mergeHistory(session.id, page);
|
||||
const history = this.transcripts.mergeHistory(transcriptKey, page);
|
||||
this.setState({ ...history, isLoadingEarlierMessages: false, isReceivingPartialStream: false, status: undefined, activity: undefined });
|
||||
if (options?.updateUrl !== false) this.updateUrl();
|
||||
return;
|
||||
@@ -129,7 +132,7 @@ export class SessionController {
|
||||
);
|
||||
const [page, status] = await Promise.all([this.api.messages(session.id, { limit: MESSAGE_PAGE_SIZE }, selectedMachineId(this.getState())), this.api.status(session.id, selectedMachineId(this.getState()))]);
|
||||
if (seq !== this.selectionSeq || this.getState().selectedSession?.id !== session.id) return;
|
||||
const history = this.transcripts.mergeHistory(session.id, page);
|
||||
const history = this.transcripts.mergeHistory(transcriptKey, page);
|
||||
const isReceivingPartialStream = status.isStreaming;
|
||||
this.catchupStreamSessionId = isReceivingPartialStream ? session.id : undefined;
|
||||
this.setState({ ...history, isLoadingEarlierMessages: false, isReceivingPartialStream, status, activity: this.getState().sessionActivities[session.id] });
|
||||
@@ -155,7 +158,7 @@ export class SessionController {
|
||||
try {
|
||||
const page = await this.api.messages(session.id, { before: state.messagePageStart, limit: MESSAGE_PAGE_SIZE }, selectedMachineId(this.getState()));
|
||||
if (this.getState().selectedSession?.id !== session.id) return;
|
||||
const history = this.transcripts.mergeHistory(session.id, page);
|
||||
const history = this.transcripts.mergeHistory(this.sessionCacheKey(session.id), page);
|
||||
this.setState(history);
|
||||
} catch (error) {
|
||||
this.setState({ error: String(error) });
|
||||
@@ -263,8 +266,8 @@ export class SessionController {
|
||||
void this.api.stop(session.id, selectedMachineId(this.getState())).catch(() => {
|
||||
// Best-effort cleanup for browser-cached sessions that may not exist server-side anymore.
|
||||
});
|
||||
forgetCachedNewSession(session.id);
|
||||
clearDraft(session.id);
|
||||
forgetCachedNewSession(session.id, selectedMachineId(this.getState()));
|
||||
clearDraft(this.sessionCacheKey(session.id));
|
||||
const sessions = this.getState().sessions.filter((candidate) => candidate.id !== session.id);
|
||||
this.setState({ sessions });
|
||||
if (this.getState().selectedSession?.id !== session.id) return;
|
||||
@@ -381,7 +384,7 @@ export class SessionController {
|
||||
this.flushPendingTranscriptEvents();
|
||||
const [page, status] = await Promise.all([this.api.messages(sessionId, { limit: MESSAGE_PAGE_SIZE }, selectedMachineId(this.getState())), this.api.status(sessionId, selectedMachineId(this.getState()))]);
|
||||
if (this.getState().selectedSession?.id !== sessionId) return;
|
||||
const history = this.transcripts.mergeHistory(sessionId, page);
|
||||
const history = this.transcripts.mergeHistory(this.sessionCacheKey(sessionId), page);
|
||||
this.setState({
|
||||
...history,
|
||||
status,
|
||||
@@ -394,6 +397,14 @@ export class SessionController {
|
||||
}
|
||||
}
|
||||
|
||||
private sessionCacheKey(sessionId: string): string {
|
||||
return machineSessionKey(selectedMachineId(this.getState()), sessionId);
|
||||
}
|
||||
|
||||
private workspaceSelectionKey(cwd: string): string {
|
||||
return `${selectedMachineId(this.getState())}:${cwd}`;
|
||||
}
|
||||
|
||||
private replaceSession(session: SessionInfo) {
|
||||
const current = this.getState().selectedSession;
|
||||
this.setState({
|
||||
@@ -404,11 +415,12 @@ export class SessionController {
|
||||
|
||||
private async recreateCachedNewSession(session: SessionInfo, options?: { updateUrl?: boolean | undefined }): Promise<void> {
|
||||
try {
|
||||
const replacement = await this.api.startSession(session.cwd, selectedMachineId(this.getState()));
|
||||
rememberCachedNewSession(replacement);
|
||||
moveDraft(session.id, replacement.id);
|
||||
forgetCachedNewSession(session.id);
|
||||
const cachedReplacement = markCachedNewSessionInfo(replacement);
|
||||
const machineId = selectedMachineId(this.getState());
|
||||
const replacement = await this.api.startSession(session.cwd, machineId);
|
||||
rememberCachedNewSession(replacement, machineId);
|
||||
moveDraft(this.sessionCacheKey(session.id), this.sessionCacheKey(replacement.id));
|
||||
forgetCachedNewSession(session.id, machineId);
|
||||
const cachedReplacement = markCachedNewSessionInfo(replacement, machineId);
|
||||
this.setState({ sessions: [cachedReplacement, ...this.getState().sessions.filter((candidate) => candidate.id !== session.id)], error: "" });
|
||||
await this.selectSession(cachedReplacement, { updateUrl: false });
|
||||
this.updateUrl(options?.updateUrl === false ? { replace: true } : undefined);
|
||||
@@ -431,7 +443,7 @@ export class SessionController {
|
||||
const message = result.type === "unsupported" ? result.message : result.message;
|
||||
if (message !== undefined && message !== "") this.setState({ messages: [...this.getState().messages, textMessage(result.type === "unsupported" ? "system" : "tool", message)] });
|
||||
if (result.type === "done" && result.session) {
|
||||
if (result.promptDraft !== undefined) saveDraft(result.session.id, result.promptDraft);
|
||||
if (result.promptDraft !== undefined) saveDraft(this.sessionCacheKey(result.session.id), result.promptDraft);
|
||||
const current = this.getState().selectedSession;
|
||||
const sessions = [result.session, ...this.getState().sessions.filter((session) => session.id !== result.session?.id)];
|
||||
this.setState({ sessions, selectedSession: current?.id === result.session.id ? result.session : current });
|
||||
@@ -538,7 +550,7 @@ export class SessionController {
|
||||
try {
|
||||
const page = await this.api.messages(sessionId, { limit: MESSAGE_PAGE_SIZE }, selectedMachineId(this.getState()));
|
||||
if (this.getState().selectedSession?.id !== sessionId) return;
|
||||
this.setState(this.transcripts.mergeHistory(sessionId, page));
|
||||
this.setState(this.transcripts.mergeHistory(this.sessionCacheKey(sessionId), page));
|
||||
} catch (error) {
|
||||
if (this.getState().selectedSession?.id === sessionId) this.setState({ error: String(error) });
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import type { AppState } from "../appState";
|
||||
import { LOCAL_MACHINE_ID } from "../machineKeys";
|
||||
|
||||
export function selectedMachineId(state: Pick<AppState, "selectedMachine">): string {
|
||||
return state.selectedMachine?.id ?? "local";
|
||||
return state.selectedMachine?.id ?? LOCAL_MACHINE_ID;
|
||||
}
|
||||
|
||||
export type GetState = () => AppState;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { api as defaultApi, type Project, type Workspace } from "../api";
|
||||
import { resetWorkspaceScopedState } from "../appState";
|
||||
import { mergeCachedNewSessions } from "../cachedNewSessions";
|
||||
import { machineProjectKey } from "../machineKeys";
|
||||
import { selectedMachineId, type GetState, type RouteTarget, type SetState, type UpdateUrl } from "./types";
|
||||
import type { SessionController } from "./sessionController";
|
||||
import { InMemoryWorkspaceSelectionMemory, selectPreferredWorkspace, type WorkspaceSelectionMemory } from "./workspaceSelection";
|
||||
@@ -30,7 +31,7 @@ export class WorkspaceController {
|
||||
}
|
||||
|
||||
forgetProject(projectId: string): void {
|
||||
this.workspaceSelection.forgetProject(projectId);
|
||||
this.workspaceSelection.forgetProject(machineProjectKey(selectedMachineId(this.getState()), projectId));
|
||||
const workspacesByProjectId = Object.fromEntries(Object.entries(this.getState().workspacesByProjectId).filter(([candidate]) => candidate !== projectId));
|
||||
this.setState({ workspacesByProjectId });
|
||||
}
|
||||
@@ -39,9 +40,10 @@ export class WorkspaceController {
|
||||
this.sessions.clearActiveSession();
|
||||
this.setState({ selectedProject: project, selectedWorkspace: undefined, workspaces: [], isLoadingWorkspaces: true, ...resetWorkspaceScopedState() });
|
||||
try {
|
||||
const workspaces = await api.workspaces(project.id, selectedMachineId(this.getState()));
|
||||
const machineId = selectedMachineId(this.getState());
|
||||
const workspaces = await api.workspaces(project.id, machineId);
|
||||
this.setState({ workspaces, workspacesByProjectId: { ...this.getState().workspacesByProjectId, [project.id]: workspaces }, isLoadingWorkspaces: false });
|
||||
const workspace = selectPreferredWorkspace(workspaces, { targetWorkspaceId: target?.workspaceId, latestWorkspaceId: this.workspaceSelection.latestWorkspaceId(project.id) });
|
||||
const workspace = selectPreferredWorkspace(workspaces, { targetWorkspaceId: target?.workspaceId, latestWorkspaceId: this.workspaceSelection.latestWorkspaceId(machineProjectKey(machineId, project.id)) });
|
||||
if (workspace) await this.selectWorkspace(workspace, { sessionId: target?.sessionId, updateUrl: target?.updateUrl });
|
||||
else if (target?.updateUrl !== false) this.updateUrl();
|
||||
} catch (error) {
|
||||
@@ -50,11 +52,12 @@ export class WorkspaceController {
|
||||
}
|
||||
|
||||
async selectWorkspace(workspace: Workspace, target?: { sessionId?: string | undefined; updateUrl?: boolean | undefined }) {
|
||||
this.workspaceSelection.rememberWorkspace(workspace);
|
||||
const machineId = selectedMachineId(this.getState());
|
||||
this.workspaceSelection.rememberWorkspace({ ...workspace, projectId: machineProjectKey(machineId, workspace.projectId) });
|
||||
this.sessions.clearActiveSession();
|
||||
this.setState({ selectedWorkspace: workspace, isLoadingWorkspaces: false, ...resetWorkspaceScopedState() });
|
||||
try {
|
||||
const sessions = mergeCachedNewSessions(workspace.path, await api.sessions(workspace.path, selectedMachineId(this.getState())));
|
||||
const sessions = mergeCachedNewSessions(workspace.path, await api.sessions(workspace.path, machineId), machineId);
|
||||
this.setState({ sessions });
|
||||
const session = this.sessions.preferredSession(workspace.path, sessions, target?.sessionId);
|
||||
if (session) await this.sessions.selectSession(session, { updateUrl: target?.updateUrl });
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
export const LOCAL_MACHINE_ID = "local";
|
||||
|
||||
export function machineProjectKey(machineId: string, projectId: string): string {
|
||||
return `${machineId}:${projectId}`;
|
||||
}
|
||||
|
||||
export function machineWorkspaceKey(machineId: string, projectId: string, workspaceId: string): string {
|
||||
return `${machineId}:${projectId}:${workspaceId}`;
|
||||
}
|
||||
|
||||
export function machineSessionKey(machineId: string, sessionId: string): string {
|
||||
return `${machineId}:${sessionId}`;
|
||||
}
|
||||
@@ -21,6 +21,36 @@ export function createCoreActions(): PluginAction[] {
|
||||
enabled: (context) => context.state.selectedSession !== undefined,
|
||||
run: (context) => { context.focusPrompt(); },
|
||||
},
|
||||
{
|
||||
id: "machine.add",
|
||||
title: "Add Machine",
|
||||
description: "Register another PI WEB runtime reachable from this gateway",
|
||||
group: "Machine",
|
||||
run: (context) => context.addMachine(),
|
||||
},
|
||||
{
|
||||
id: "machine.refresh",
|
||||
title: "Refresh Selected Machine",
|
||||
description: "Check whether the selected PI WEB runtime is online",
|
||||
group: "Machine",
|
||||
run: (context) => context.refreshSelectedMachine(),
|
||||
},
|
||||
{
|
||||
id: "machine.open",
|
||||
title: "Open Selected Machine PI WEB",
|
||||
description: "Open the selected remote PI WEB directly in a new tab",
|
||||
group: "Machine",
|
||||
enabled: (context) => context.state.selectedMachine?.kind === "remote" && context.state.selectedMachine.baseUrl !== undefined,
|
||||
run: (context) => context.openSelectedMachine(),
|
||||
},
|
||||
{
|
||||
id: "machine.remove",
|
||||
title: "Remove Selected Machine",
|
||||
description: "Remove the selected remote machine from this gateway",
|
||||
group: "Machine",
|
||||
enabled: (context) => context.state.selectedMachine?.kind === "remote",
|
||||
run: (context) => context.removeSelectedMachine(),
|
||||
},
|
||||
{
|
||||
id: "project.add",
|
||||
title: "Add Project",
|
||||
|
||||
@@ -21,6 +21,10 @@ function createContext(statePatch: Partial<AppState> = {}) {
|
||||
openActionPalette: vi.fn(() => { calls.push("openActionPalette"); }),
|
||||
focusPrompt: vi.fn(() => { calls.push("focusPrompt"); }),
|
||||
addProject: vi.fn(() => { calls.push("addProject"); }),
|
||||
addMachine: vi.fn(() => { calls.push("addMachine"); }),
|
||||
refreshSelectedMachine: vi.fn(() => { calls.push("refreshSelectedMachine"); }),
|
||||
removeSelectedMachine: vi.fn(() => { calls.push("removeSelectedMachine"); }),
|
||||
openSelectedMachine: vi.fn(() => { calls.push("openSelectedMachine"); }),
|
||||
configureAuth: vi.fn(() => { calls.push("configureAuth"); }),
|
||||
logoutAuth: vi.fn(() => { calls.push("logoutAuth"); }),
|
||||
openThemePicker: vi.fn(() => { calls.push("openThemePicker"); }),
|
||||
|
||||
@@ -53,6 +53,10 @@ export interface PluginRuntimeContext {
|
||||
openActionPalette: () => void;
|
||||
focusPrompt: () => void;
|
||||
addProject: () => void | Promise<void>;
|
||||
addMachine: () => void | Promise<void>;
|
||||
refreshSelectedMachine: () => void | Promise<void>;
|
||||
removeSelectedMachine: () => void | Promise<void>;
|
||||
openSelectedMachine: () => void | Promise<void>;
|
||||
configureAuth: () => void | Promise<void>;
|
||||
logoutAuth: () => void | Promise<void>;
|
||||
openThemePicker: () => void;
|
||||
|
||||
Reference in New Issue
Block a user