Archived
test: close selected coverage gaps
This commit is contained in:
@@ -67,6 +67,7 @@ describe("federated route contract", () => {
|
||||
ignoreParseFailure(sessionsApi.cycleThinkingLevel(session, machineId)),
|
||||
ignoreParseFailure(sessionsApi.commands(session, machineId)),
|
||||
ignoreParseFailure(sessionsApi.prompt(session, "hello", "followUp", machineId)),
|
||||
ignoreParseFailure(sessionsApi.saveAttachments(session, [{ kind: "image", mimeType: "image/png", data: "QUJD", name: "shot.png" }], machineId, "uploads")),
|
||||
ignoreParseFailure(sessionsApi.shell(session, "ls", machineId)),
|
||||
ignoreParseFailure(sessionsApi.runCommand(session, "/help", machineId)),
|
||||
ignoreParseFailure(sessionsApi.respondToCommand(session, "req 1", "yes", machineId)),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { PI_WEB_CAPABILITIES } from "../../../shared/capabilities";
|
||||
import { configApi, pluginsApi, type Machine, type MachineRuntime, type PiWebConfigResponse, type PiWebConfigValues, type PiWebPluginInfo, type PiWebPluginsResponse } from "../api";
|
||||
import { configApi, piPackagesApi, pluginsApi, type Machine, type MachineRuntime, type PiPackageInfo, type PiPackageMutationResponse, type PiWebConfigResponse, type PiWebConfigValues, type PiWebPluginInfo, type PiWebPluginsResponse } from "../api";
|
||||
import { SettingsDialog } from "./SettingsDialog";
|
||||
|
||||
afterEach(() => {
|
||||
@@ -319,6 +319,76 @@ describe("settings-dialog general settings machine targeting", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings-dialog Pi package orchestration", () => {
|
||||
it("loads package data from the selected machine and ignores stale target responses", async () => {
|
||||
const remotePackages = { packages: [packageInfo("npm:@acme/tools")] };
|
||||
const staleLoad = deferred<typeof remotePackages>();
|
||||
const packagesSpy = vi.spyOn(piPackagesApi, "packages").mockReturnValue(staleLoad.promise);
|
||||
const dialog = new SettingsDialog();
|
||||
dialog.machine = remoteMachine;
|
||||
dialog.machineRuntime = runtimeWithPackageManagement;
|
||||
|
||||
const loadPromise = callDialogPromise(dialog, "loadPackagesForTarget");
|
||||
expect(packagesSpy.mock.calls).toEqual([["remote-a"]]);
|
||||
expect(getDialogProperty(dialog, "packageLoading")).toBe(true);
|
||||
|
||||
dialog.machine = secondRemoteMachine;
|
||||
callDialogUpdated(dialog, new Map([["machine", remoteMachine]]));
|
||||
staleLoad.resolve(remotePackages);
|
||||
await loadPromise;
|
||||
|
||||
expect(getDialogProperty(dialog, "packagesResponse")).toBeUndefined();
|
||||
expect(getDialogProperty(dialog, "packageError")).toBe("");
|
||||
expect(getDialogProperty(dialog, "packageMessage")).toBe("");
|
||||
expect(getDialogProperty(dialog, "packageLoading")).toBe(false);
|
||||
});
|
||||
|
||||
it("runs remote package mutations against the selected machine without refreshing gateway plugins", async () => {
|
||||
const installedPackages = [packageInfo("npm:@acme/new-tools")];
|
||||
const install = deferred<PiPackageMutationResponse>();
|
||||
const installSpy = vi.spyOn(piPackagesApi, "install").mockReturnValue(install.promise);
|
||||
const pluginsSpy = vi.spyOn(pluginsApi, "plugins").mockResolvedValue(pluginsResponse([pluginInfo("gateway", true)]));
|
||||
const dialog = new SettingsDialog();
|
||||
dialog.machine = remoteMachine;
|
||||
dialog.machineRuntime = runtimeWithPackageManagement;
|
||||
|
||||
const installPromise = callDialogPromise(dialog, "installPiPackage", "npm:@acme/new-tools");
|
||||
|
||||
expect(installSpy.mock.calls).toEqual([["npm:@acme/new-tools", "remote-a"]]);
|
||||
expect(getDialogProperty(dialog, "saving")).toBe(true);
|
||||
expect(getDialogProperty(dialog, "packageOperation")).toEqual({ kind: "install", source: "npm:@acme/new-tools" });
|
||||
|
||||
install.resolve(packageMutationResponse("install", installedPackages, "npm:@acme/new-tools"));
|
||||
await installPromise;
|
||||
|
||||
expect(pluginsSpy).not.toHaveBeenCalled();
|
||||
expect(getDialogProperty(dialog, "packagesResponse")).toEqual({ packages: installedPackages });
|
||||
expect(getDialogProperty(dialog, "packageMessage")).toContain("Pi package installed on Lab Mac");
|
||||
expect(getDialogProperty(dialog, "packageMessage")).toContain("each idle PI WEB session on Lab Mac");
|
||||
expect(getDialogProperty(dialog, "packageError")).toBe("");
|
||||
expect(getDialogProperty(dialog, "packageOperation")).toBeUndefined();
|
||||
expect(getDialogProperty(dialog, "saving")).toBe(false);
|
||||
});
|
||||
|
||||
it("refreshes gateway plugins after a local package mutation", async () => {
|
||||
const updatedPackages = [packageInfo("npm:@acme/tools")];
|
||||
const refreshedPlugins = pluginsResponse([pluginInfo("browser-helper", true)]);
|
||||
const updateSpy = vi.spyOn(piPackagesApi, "update").mockResolvedValue(packageMutationResponse("update", updatedPackages));
|
||||
const pluginsSpy = vi.spyOn(pluginsApi, "plugins").mockResolvedValue(refreshedPlugins);
|
||||
const dialog = new SettingsDialog();
|
||||
|
||||
await callDialogPromise(dialog, "updatePiPackage");
|
||||
|
||||
expect(updateSpy.mock.calls).toEqual([[undefined, "local"]]);
|
||||
expect(pluginsSpy.mock.calls).toEqual([[]]);
|
||||
expect(getDialogProperty(dialog, "packagesResponse")).toEqual({ packages: updatedPackages });
|
||||
expect(getDialogProperty(dialog, "pluginsResponse")).toBe(refreshedPlugins);
|
||||
expect(getDialogProperty(dialog, "packageMessage")).toContain("Reload the browser page separately for PI WEB browser plugin changes");
|
||||
expect(getDialogProperty(dialog, "packageError")).toBe("");
|
||||
expect(getDialogProperty(dialog, "saving")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings-dialog plugin settings machine targeting", () => {
|
||||
it("loads plugin config and plugin list from the selected machine", async () => {
|
||||
const config = configResponse({ plugins: { info: { enabled: true } } });
|
||||
@@ -502,13 +572,15 @@ const secondRemoteMachine: Machine = {
|
||||
updatedAt: "2026-07-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
const runtimeWithoutSelectedMachineSettings: MachineRuntime = {
|
||||
const runtimeWithPackageManagement: MachineRuntime = {
|
||||
machineId: "remote-a",
|
||||
ok: true,
|
||||
checkedAt: "2026-07-01T00:00:00.000Z",
|
||||
capabilities: [PI_WEB_CAPABILITIES.piPackagesManage],
|
||||
};
|
||||
|
||||
const runtimeWithoutSelectedMachineSettings: MachineRuntime = runtimeWithPackageManagement;
|
||||
|
||||
function getDialogProperty(dialog: SettingsDialog, property: string): unknown {
|
||||
return Reflect.get(dialog, property);
|
||||
}
|
||||
@@ -600,6 +672,14 @@ function pluginInfo(id: string, enabled: boolean): PiWebPluginInfo {
|
||||
};
|
||||
}
|
||||
|
||||
function packageInfo(source: string): PiPackageInfo {
|
||||
return { source, scope: "user", filtered: false, installedPath: `/pi/packages/${source}` };
|
||||
}
|
||||
|
||||
function packageMutationResponse(action: PiPackageMutationResponse["action"], packages: PiPackageInfo[], source?: string): PiPackageMutationResponse {
|
||||
return source === undefined ? { action, packages } : { action, source, packages };
|
||||
}
|
||||
|
||||
interface Deferred<T> {
|
||||
promise: Promise<T>;
|
||||
resolve: (value: T) => void;
|
||||
|
||||
@@ -1,6 +1,43 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { initialAppState } from "../appState";
|
||||
import type { WorkspacePanelContext } from "../plugins/types";
|
||||
import type { WorkspaceUploadBatchState } from "../workspaceUploadState";
|
||||
import { startDirectWorkspaceUpload, uploadBatchProgressValue, uploadBatchStatusLabel, workspaceUploadBatchesForScope, workspaceUploadReviewDefaults, workspaceUploadReviewError } from "./WorkspaceFilesPanel";
|
||||
import { WorkspaceFilesPanel, startDirectWorkspaceUpload, uploadBatchProgressValue, uploadBatchStatusLabel, workspaceUploadBatchesForScope, workspaceUploadReviewDefaults, workspaceUploadReviewError } from "./WorkspaceFilesPanel";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("workspace-files-panel upload review", () => {
|
||||
it("opens review from the hidden file input and submits selected files with defaults", () => {
|
||||
vi.stubGlobal("HTMLInputElement", FakeHTMLInputElement);
|
||||
const files = [new File(["a"], "a.txt"), new File(["b"], "b.txt")];
|
||||
const onStartWorkspaceUpload = vi.fn<WorkspacePanelContext["onStartWorkspaceUpload"]>(() => ({ batchId: "batch-1", done: Promise.resolve() }));
|
||||
const panel = new WorkspaceFilesPanel();
|
||||
panel.context = workspacePanelContext({ workspaceUploadDefaultFolder: "project/uploads", onStartWorkspaceUpload });
|
||||
|
||||
const inputChange = findTemplateEventHandler<Event>(panel.render(), `id="workspace-upload-input"`);
|
||||
const input = new FakeHTMLInputElement(files);
|
||||
inputChange(new EventWithCurrentTarget("change", input));
|
||||
|
||||
expect(input.value).toBe("");
|
||||
expect(onStartWorkspaceUpload).not.toHaveBeenCalled();
|
||||
|
||||
const submit = findTemplateEventHandler<SubmitEvent>(panel.render(), "<form @submit=");
|
||||
const submitEvent = new FakeSubmitEvent("submit", { cancelable: true });
|
||||
submit(submitEvent);
|
||||
|
||||
expect(submitEvent.defaultPrevented).toBe(true);
|
||||
expect(onStartWorkspaceUpload).toHaveBeenCalledWith(files, {
|
||||
destinationFolder: "project/uploads",
|
||||
createDirs: true,
|
||||
overwrite: false,
|
||||
selectUploadedFile: true,
|
||||
});
|
||||
expect(findOptionalTemplateEventHandler<SubmitEvent>(panel.render(), "<form @submit=")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspaceUploadBatchesForScope", () => {
|
||||
it("filters upload batches to the selected project, workspace, and machine", () => {
|
||||
@@ -80,6 +117,152 @@ describe("workspaceUploadReviewError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
type TemplateEventHandler<E extends Event> = (event: E) => void;
|
||||
|
||||
function findTemplateEventHandler<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> {
|
||||
const handler = findOptionalTemplateEventHandler<E>(template, marker);
|
||||
if (handler === undefined) throw new Error(`Expected template event handler after ${marker}`);
|
||||
return handler;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandler<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> | undefined {
|
||||
return findInTemplate(template);
|
||||
|
||||
function findInTemplate(current: TemplateResult): TemplateEventHandler<E> | undefined {
|
||||
const strings = templateStrings(current);
|
||||
const values = templateValues(current);
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
const staticChunk = strings[index];
|
||||
const value = values[index];
|
||||
if (staticChunk !== undefined && staticChunk.includes(marker) && isTemplateEventHandler<E>(value)) return value;
|
||||
const nestedHandler = findInValue(value);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findInValue(value: unknown): TemplateEventHandler<E> | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const nestedHandler = findInValue(item);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (isTemplateResult(value)) return findInTemplate(value);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function templateStrings(template: TemplateResult): readonly string[] {
|
||||
const strings = Reflect.get(template, "strings");
|
||||
if (!isStringArray(strings)) throw new Error("TemplateResult strings were unavailable");
|
||||
return strings;
|
||||
}
|
||||
|
||||
function templateValues(template: TemplateResult): readonly unknown[] {
|
||||
const values = Reflect.get(template, "values");
|
||||
if (!Array.isArray(values)) throw new Error("TemplateResult values were unavailable");
|
||||
return values.map((value: unknown) => value);
|
||||
}
|
||||
|
||||
function isTemplateResult(value: unknown): value is TemplateResult {
|
||||
return typeof value === "object" && value !== null && isStringArray(Reflect.get(value, "strings")) && Array.isArray(Reflect.get(value, "values"));
|
||||
}
|
||||
|
||||
function isTemplateEventHandler<E extends Event>(value: unknown): value is TemplateEventHandler<E> {
|
||||
return typeof value === "function";
|
||||
}
|
||||
|
||||
function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === "string");
|
||||
}
|
||||
|
||||
class FakeFileList implements FileList {
|
||||
readonly length: number;
|
||||
[index: number]: File;
|
||||
|
||||
constructor(private readonly files: readonly File[]) {
|
||||
this.length = files.length;
|
||||
files.forEach((file, index) => {
|
||||
this[index] = file;
|
||||
});
|
||||
}
|
||||
|
||||
item(index: number): File | null {
|
||||
return this.files[index] ?? null;
|
||||
}
|
||||
|
||||
[Symbol.iterator](): ArrayIterator<File> {
|
||||
return this.files[Symbol.iterator]();
|
||||
}
|
||||
}
|
||||
|
||||
class FakeHTMLInputElement extends EventTarget {
|
||||
readonly files: FileList;
|
||||
value = "selected-files";
|
||||
|
||||
constructor(files: readonly File[]) {
|
||||
super();
|
||||
this.files = new FakeFileList(files);
|
||||
}
|
||||
}
|
||||
|
||||
class EventWithCurrentTarget extends Event {
|
||||
constructor(type: string, private readonly eventCurrentTarget: EventTarget) {
|
||||
super(type);
|
||||
}
|
||||
|
||||
override get currentTarget(): EventTarget {
|
||||
return this.eventCurrentTarget;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeSubmitEvent extends Event implements SubmitEvent {
|
||||
readonly submitter: HTMLElement | null = null;
|
||||
}
|
||||
|
||||
function workspacePanelContext(patch: Partial<Pick<WorkspacePanelContext, "onStartWorkspaceUpload" | "workspaceUploadDefaultFolder">> = {}): WorkspacePanelContext {
|
||||
const workspace = { id: "workspace-1", projectId: "project-1", path: "/tmp/project", label: "main", isMain: true, isGitRepo: true, isGitWorktree: false };
|
||||
return {
|
||||
machine: { id: "local", name: "Local", kind: "local" },
|
||||
workspace,
|
||||
state: { ...initialAppState(), workspaceUploadBatches: {} },
|
||||
files: {
|
||||
readFile: vi.fn<WorkspacePanelContext["files"]["readFile"]>(() => Promise.reject(new Error("not implemented"))),
|
||||
writeFile: vi.fn<WorkspacePanelContext["files"]["writeFile"]>(() => Promise.reject(new Error("not implemented"))),
|
||||
deleteFile: vi.fn<WorkspacePanelContext["files"]["deleteFile"]>(() => Promise.reject(new Error("not implemented"))),
|
||||
moveFile: vi.fn<WorkspacePanelContext["files"]["moveFile"]>(() => Promise.reject(new Error("not implemented"))),
|
||||
},
|
||||
prompt: { insertText: vi.fn<WorkspacePanelContext["prompt"]["insertText"]>(), getText: vi.fn<WorkspacePanelContext["prompt"]["getText"]>(() => ""), getSelection: vi.fn<WorkspacePanelContext["prompt"]["getSelection"]>(() => null) },
|
||||
terminal: { open: vi.fn<WorkspacePanelContext["terminal"]["open"]>(), runCommand: vi.fn<WorkspacePanelContext["terminal"]["runCommand"]>(() => Promise.reject(new Error("not implemented"))) },
|
||||
host: { requestRender: vi.fn<WorkspacePanelContext["host"]["requestRender"]>() },
|
||||
fileTree: [],
|
||||
expandedDirs: {},
|
||||
selectedFilePath: undefined,
|
||||
selectedFileContent: undefined,
|
||||
fileTreeStale: false,
|
||||
gitStatus: undefined,
|
||||
selectedDiffPath: undefined,
|
||||
selectedDiff: undefined,
|
||||
selectedStagedDiff: undefined,
|
||||
gitStale: false,
|
||||
activeTerminalCount: 0,
|
||||
selectedTerminalId: undefined,
|
||||
terminalAutoStart: false,
|
||||
workspaceUploadDefaultFolder: patch.workspaceUploadDefaultFolder ?? ".pi-web/uploads",
|
||||
onRefreshFiles: vi.fn<WorkspacePanelContext["onRefreshFiles"]>(),
|
||||
onExpandDir: vi.fn<WorkspacePanelContext["onExpandDir"]>(),
|
||||
onSelectFile: vi.fn<WorkspacePanelContext["onSelectFile"]>(),
|
||||
onStartWorkspaceUpload: patch.onStartWorkspaceUpload ?? vi.fn<WorkspacePanelContext["onStartWorkspaceUpload"]>(() => undefined),
|
||||
onCancelWorkspaceUpload: vi.fn<WorkspacePanelContext["onCancelWorkspaceUpload"]>(),
|
||||
onClearWorkspaceUpload: vi.fn<WorkspacePanelContext["onClearWorkspaceUpload"]>(),
|
||||
onRefreshGit: vi.fn<WorkspacePanelContext["onRefreshGit"]>(),
|
||||
onSelectDiff: vi.fn<WorkspacePanelContext["onSelectDiff"]>(),
|
||||
onSelectTerminal: vi.fn<WorkspacePanelContext["onSelectTerminal"]>(),
|
||||
};
|
||||
}
|
||||
|
||||
function uploadBatch(patch: Partial<WorkspaceUploadBatchState> = {}): WorkspaceUploadBatchState {
|
||||
return {
|
||||
id: patch.id ?? "batch-1",
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { TemplateResult } from "lit";
|
||||
import type { AppAction } from "../../actions";
|
||||
import type { PiWebConfigResponse, PiWebConfigValues } from "../../api";
|
||||
import { SettingsShortcutsPanel } from "./SettingsShortcutsPanel";
|
||||
import type { SettingsNotice } from "./SettingsPanelFrame";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe("settings-shortcuts-panel layout", () => {
|
||||
it("renders header, ordered notices, and shortcut settings through the shared frame", () => {
|
||||
const panel = new SettingsShortcutsPanel();
|
||||
@@ -40,6 +45,34 @@ describe("settings-shortcuts-panel layout", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("settings-shortcuts-panel shortcut row actions", () => {
|
||||
it("saves edited shortcuts, disables them with None, and resets overrides", () => {
|
||||
vi.stubGlobal("HTMLInputElement", FakeHTMLInputElement);
|
||||
const onSave = vi.fn<SaveHandler>();
|
||||
const savePanel = panelWithShortcuts({ shortcuts: { "core:other": "mod+o" } }, onSave);
|
||||
|
||||
findTemplateEventHandler<Event>(savePanel.render(), "@input=")(
|
||||
new EventWithTarget("input", new FakeHTMLInputElement(" control + shift + p ")),
|
||||
);
|
||||
|
||||
expectTextOrder(flattenTemplateContent(savePanel.render()), ["Open palette", "Ctrl+Shift+P", "Custom · Unsaved"]);
|
||||
|
||||
findTemplateEventHandler<Event>(savePanel.render(), ">Save</button>")(new Event("click"));
|
||||
|
||||
const nonePanel = panelWithShortcuts({ shortcuts: { "core:open-palette": "mod+shift+p", "core:other": "mod+o" } }, onSave);
|
||||
findTemplateEventHandler<Event>(nonePanel.render(), ">None</button>")(new Event("click"));
|
||||
|
||||
const resetPanel = panelWithShortcuts({ shortcuts: { "core:open-palette": null, "core:other": "mod+o" } }, onSave);
|
||||
findTemplateEventHandler<Event>(resetPanel.render(), ">Reset</button>")(new Event("click"));
|
||||
|
||||
expect(onSave.mock.calls).toEqual([
|
||||
[{ shortcuts: { "core:other": "mod+o", "core:open-palette": "mod+shift+p" } }],
|
||||
[{ shortcuts: { "core:open-palette": null, "core:other": "mod+o" } }],
|
||||
[{ shortcuts: { "core:other": "mod+o" } }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
function frameNotices(template: TemplateResult): readonly SettingsNotice[] {
|
||||
const notices = collectTemplateValues(template).find(isSettingsNoticeArray);
|
||||
if (notices === undefined) throw new Error("Expected settings-panel-frame notices to be rendered");
|
||||
@@ -139,6 +172,86 @@ function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === "string");
|
||||
}
|
||||
|
||||
type SaveHandler = (config: PiWebConfigValues) => void | Promise<void>;
|
||||
type TemplateEventHandler<E extends Event> = (event: E) => void;
|
||||
|
||||
function panelWithShortcuts(config: PiWebConfigValues, onSave: SaveHandler): SettingsShortcutsPanel {
|
||||
const panel = new SettingsShortcutsPanel();
|
||||
panel.actions = [shortcutAction()];
|
||||
panel.configResponse = configResponse(config);
|
||||
panel.onSave = onSave;
|
||||
return panel;
|
||||
}
|
||||
|
||||
function shortcutAction(): AppAction {
|
||||
return {
|
||||
id: "core:open-palette",
|
||||
title: "Open palette",
|
||||
description: "Open the command palette.",
|
||||
shortcut: "mod+k",
|
||||
group: "Navigation",
|
||||
run: vi.fn(),
|
||||
};
|
||||
}
|
||||
|
||||
function findTemplateEventHandler<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> {
|
||||
const handler = findOptionalTemplateEventHandler<E>(template, marker);
|
||||
if (handler === undefined) throw new Error(`Expected template event handler near ${marker}`);
|
||||
return handler;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandler<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> | undefined {
|
||||
return findInTemplate(template);
|
||||
|
||||
function findInTemplate(current: TemplateResult): TemplateEventHandler<E> | undefined {
|
||||
const strings = templateStrings(current);
|
||||
const values = templateValues(current);
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
const value = values[index];
|
||||
if (isTemplateEventHandler<E>(value) && templateEventHandlerMatches(strings, index, marker)) return value;
|
||||
const nestedHandler = findInValue(value);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findInValue(value: unknown): TemplateEventHandler<E> | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const nestedHandler = findInValue(item);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (isTemplateResult(value)) return findInTemplate(value);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function templateEventHandlerMatches(strings: readonly string[], valueIndex: number, marker: string): boolean {
|
||||
return (strings[valueIndex] ?? "").includes(marker) || (strings[valueIndex + 1] ?? "").includes(marker);
|
||||
}
|
||||
|
||||
function isTemplateEventHandler<E extends Event>(value: unknown): value is TemplateEventHandler<E> {
|
||||
return typeof value === "function";
|
||||
}
|
||||
|
||||
class FakeHTMLInputElement extends EventTarget {
|
||||
constructor(readonly value: string) {
|
||||
super();
|
||||
}
|
||||
}
|
||||
|
||||
class EventWithTarget extends Event {
|
||||
constructor(type: string, private readonly eventTarget: EventTarget) {
|
||||
super(type);
|
||||
}
|
||||
|
||||
override get target(): EventTarget {
|
||||
return this.eventTarget;
|
||||
}
|
||||
}
|
||||
|
||||
function configResponse(config: PiWebConfigValues): PiWebConfigResponse {
|
||||
return {
|
||||
path: "/tmp/pi-web/config.json",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { api as defaultApi, type AuthProviderOption, type OAuthFlowState } from "../api";
|
||||
import { api as defaultApi, type AuthProviderOption, type OAuthFlowState, type SessionInfo, type SessionStatus } from "../api";
|
||||
import { initialAppState, type AppState } from "../appState";
|
||||
import { AuthController, parseAuthSlashCommand } from "./authController";
|
||||
|
||||
@@ -42,20 +42,226 @@ describe("AuthController", () => {
|
||||
|
||||
expect(getState().authDialog).toMatchObject({ step: "oauth", inputValue: "https://callback", responding: true });
|
||||
});
|
||||
|
||||
it("resets OAuth prompt input and submit state when the request id changes", async () => {
|
||||
const flow = oauthFlow({ prompt: { requestId: "request-1", message: "Paste callback", kind: "manual" } });
|
||||
const { controller, getState } = createController(
|
||||
{ authDialog: { step: "oauth", flow, inputValue: "https://callback", responding: true } },
|
||||
{
|
||||
respondOAuthFlow: () => Promise.resolve(oauthFlow({
|
||||
select: { requestId: "request-2", message: "Choose an account", options: [{ value: "acct-1", label: "Account 1" }] },
|
||||
progress: ["Need account selection"],
|
||||
})),
|
||||
},
|
||||
);
|
||||
|
||||
await controller.respondOAuth();
|
||||
|
||||
expect(getState().authDialog).toMatchObject({
|
||||
step: "oauth",
|
||||
flow: { select: { requestId: "request-2" } },
|
||||
inputValue: "",
|
||||
responding: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("closes the OAuth dialog and refreshes selected session status when the flow completes", async () => {
|
||||
const flow = oauthFlow({ prompt: { requestId: "request-1", message: "Paste callback", kind: "manual" } });
|
||||
const session = sessionInfo("session-1");
|
||||
const refreshedStatus = sessionStatus(session.id);
|
||||
const respondCalls: { flowId: string; requestId: string; value: string; machineId: string | undefined }[] = [];
|
||||
const statusCalls: { session: Parameters<typeof defaultApi.status>[0]; machineId: string | undefined }[] = [];
|
||||
const appliedStatuses: SessionStatus[] = [];
|
||||
const { controller, getState } = createController(
|
||||
{ selectedSession: session, authDialog: { step: "oauth", flow, inputValue: "https://callback" } },
|
||||
{
|
||||
respondOAuthFlow: (flowId, requestId, value, machineId) => {
|
||||
respondCalls.push({ flowId, requestId, value, machineId });
|
||||
return Promise.resolve(oauthFlow({ status: "complete" }));
|
||||
},
|
||||
status: (sessionArg, machineId) => {
|
||||
statusCalls.push({ session: sessionArg, machineId });
|
||||
return Promise.resolve(refreshedStatus);
|
||||
},
|
||||
},
|
||||
(status) => { appliedStatuses.push(status); },
|
||||
);
|
||||
|
||||
await controller.respondOAuth();
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(respondCalls).toEqual([{ flowId: "flow-1", requestId: "request-1", value: "https://callback", machineId: "local" }]);
|
||||
expect(getState().authDialog).toBeUndefined();
|
||||
expect(statusCalls).toEqual([{ session, machineId: "local" }]);
|
||||
expect(appliedStatuses).toEqual([refreshedStatus]);
|
||||
});
|
||||
|
||||
it("leaves the OAuth dialog ready to retry if responding fails", async () => {
|
||||
const flow = oauthFlow({ prompt: { requestId: "request-1", message: "Paste callback", kind: "manual" } });
|
||||
const { controller, getState } = createController(
|
||||
{ authDialog: { step: "oauth", flow, inputValue: "https://callback", responding: true } },
|
||||
{ respondOAuthFlow: () => Promise.reject(new Error("Invalid callback")) },
|
||||
);
|
||||
|
||||
await controller.respondOAuth();
|
||||
|
||||
expect(getState().authDialog).toMatchObject({
|
||||
step: "oauth",
|
||||
flow,
|
||||
inputValue: "https://callback",
|
||||
responding: false,
|
||||
error: "Error: Invalid callback",
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels the active OAuth flow and closes the dialog even when cancellation fails", async () => {
|
||||
const flow = oauthFlow({ prompt: { requestId: "request-1", message: "Paste callback", kind: "manual" } });
|
||||
const cancelCalls: { flowId: string; machineId: string | undefined }[] = [];
|
||||
const { controller, getState } = createController(
|
||||
{ authDialog: { step: "oauth", flow } },
|
||||
{
|
||||
cancelOAuthFlow: (flowId, machineId) => {
|
||||
cancelCalls.push({ flowId, machineId });
|
||||
return Promise.reject(new Error("Cancel unavailable"));
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await controller.cancelOAuth();
|
||||
|
||||
expect(cancelCalls).toEqual([{ flowId: "flow-1", machineId: "local" }]);
|
||||
expect(getState().authDialog).toBeUndefined();
|
||||
});
|
||||
|
||||
it("validates API key input before saving and clears the validation error when edited", async () => {
|
||||
const saveCalls: { providerId: string; key: string; machineId: string | undefined }[] = [];
|
||||
const provider = authProvider("openai", "api_key");
|
||||
const { controller, getState } = createController(
|
||||
{ authDialog: { step: "apiKey", provider, value: " " } },
|
||||
{
|
||||
saveApiKey: (providerId, key, machineId) => {
|
||||
saveCalls.push({ providerId, key, machineId });
|
||||
return Promise.resolve({ accepted: true });
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
await controller.saveApiKey();
|
||||
|
||||
expect(saveCalls).toEqual([]);
|
||||
expect(getState().authDialog).toMatchObject({ step: "apiKey", error: "API key is required" });
|
||||
|
||||
controller.updateApiKey("sk-live");
|
||||
|
||||
expect(getState().authDialog).toMatchObject({ step: "apiKey", value: "sk-live" });
|
||||
expect(getState().authDialog).not.toHaveProperty("error");
|
||||
});
|
||||
|
||||
it("saves a trimmed API key on the selected machine and refreshes selected session status", async () => {
|
||||
const saveCalls: { providerId: string; key: string; machineId: string | undefined }[] = [];
|
||||
const statusCalls: { session: Parameters<typeof defaultApi.status>[0]; machineId: string | undefined }[] = [];
|
||||
const appliedStatuses: SessionStatus[] = [];
|
||||
const provider = authProvider("openai", "api_key");
|
||||
const session = sessionInfo("session-1");
|
||||
const refreshedStatus = sessionStatus(session.id);
|
||||
const { controller, getState } = createController(
|
||||
{
|
||||
selectedMachine: remoteMachine("remote-1"),
|
||||
selectedSession: session,
|
||||
authDialog: { step: "apiKey", provider, value: " sk-live " },
|
||||
},
|
||||
{
|
||||
saveApiKey: (providerId, key, machineId) => {
|
||||
saveCalls.push({ providerId, key, machineId });
|
||||
return Promise.resolve({ accepted: true });
|
||||
},
|
||||
status: (sessionArg, machineId) => {
|
||||
statusCalls.push({ session: sessionArg, machineId });
|
||||
return Promise.resolve(refreshedStatus);
|
||||
},
|
||||
},
|
||||
(status) => { appliedStatuses.push(status); },
|
||||
);
|
||||
|
||||
await controller.saveApiKey();
|
||||
await flushMicrotasks();
|
||||
|
||||
expect(saveCalls).toEqual([{ providerId: "openai", key: "sk-live", machineId: "remote-1" }]);
|
||||
expect(getState().authDialog).toBeUndefined();
|
||||
expect(statusCalls).toEqual([{ session, machineId: "remote-1" }]);
|
||||
expect(appliedStatuses).toEqual([refreshedStatus]);
|
||||
});
|
||||
|
||||
it("keeps the API key dialog open with an error if saving fails", async () => {
|
||||
const provider = authProvider("openai", "api_key");
|
||||
const { controller, getState } = createController(
|
||||
{ authDialog: { step: "apiKey", provider, value: "sk-live" } },
|
||||
{ saveApiKey: () => Promise.reject(new Error("Denied")) },
|
||||
);
|
||||
|
||||
await controller.saveApiKey();
|
||||
|
||||
expect(getState().authDialog).toMatchObject({ step: "apiKey", value: "sk-live", saving: false, error: "Error: Denied" });
|
||||
});
|
||||
});
|
||||
|
||||
function createController(statePatch: Partial<AppState>, apiPatch: Partial<typeof defaultApi> = {}) {
|
||||
function createController(
|
||||
statePatch: Partial<AppState>,
|
||||
apiPatch: Partial<typeof defaultApi> = {},
|
||||
applyStatus: (status: SessionStatus) => void = () => undefined,
|
||||
) {
|
||||
let state: AppState = { ...initialAppState(), ...statePatch };
|
||||
const api = { ...defaultApi, ...apiPatch };
|
||||
const controller = new AuthController(
|
||||
() => state,
|
||||
(patch) => { state = { ...state, ...patch }; },
|
||||
() => undefined,
|
||||
applyStatus,
|
||||
{ api },
|
||||
);
|
||||
return { controller, getState: () => state };
|
||||
}
|
||||
|
||||
async function flushMicrotasks(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
function remoteMachine(id: string): NonNullable<AppState["selectedMachine"]> {
|
||||
return {
|
||||
id,
|
||||
name: "Remote",
|
||||
kind: "remote",
|
||||
baseUrl: "https://remote.example",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
};
|
||||
}
|
||||
|
||||
function sessionInfo(id: string): SessionInfo {
|
||||
return {
|
||||
id,
|
||||
cwd: "/repo",
|
||||
path: `/tmp/${id}.jsonl`,
|
||||
created: "2026-01-01T00:00:00.000Z",
|
||||
modified: "2026-01-01T00:00:00.000Z",
|
||||
messageCount: 0,
|
||||
firstMessage: "",
|
||||
};
|
||||
}
|
||||
|
||||
function sessionStatus(sessionId: string): SessionStatus {
|
||||
return {
|
||||
sessionId,
|
||||
isStreaming: false,
|
||||
isCompacting: false,
|
||||
isBashRunning: false,
|
||||
pendingMessageCount: 0,
|
||||
queuedMessages: [],
|
||||
tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
||||
cost: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function authProvider(id: string, authType: "oauth" | "api_key"): AuthProviderOption {
|
||||
return { id, authType, name: `${id} ${authType}`, status: { configured: false } };
|
||||
}
|
||||
|
||||
@@ -158,6 +158,22 @@ describe("FileExplorerController workspace uploads", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("clears an in-flight upload by cancelling the request and removing the batch", async () => {
|
||||
const upload = controllableUpload({ rejectOnCancel: true });
|
||||
const harness = createHarness({ uploadWorkspaceFiles: upload.fn });
|
||||
const run = harness.controller.startWorkspaceUpload([new File(["aa"], "a.txt")], { destinationFolder: "uploads" });
|
||||
|
||||
expect(run?.batchId).toBe("batch-1");
|
||||
expect(harness.state.workspaceUploadBatches["batch-1"]?.status).toBe("uploading");
|
||||
|
||||
harness.controller.clearWorkspaceUpload(run?.batchId ?? "missing");
|
||||
await run?.done;
|
||||
|
||||
expect(upload.cancel).toHaveBeenCalledTimes(1);
|
||||
expect(harness.state.workspaceUploadBatches).toEqual({});
|
||||
expect(harness.state.error).toBe("");
|
||||
});
|
||||
|
||||
it("keeps per-file errors accurate and refreshes after partial batch success", async () => {
|
||||
const upload = controllableUpload();
|
||||
const harness = createHarness({ uploadWorkspaceFiles: upload.fn, now: sequenceNow("start", "fail") });
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TemplateResult } from "lit";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { PromptEditor } from "./components/PromptEditor";
|
||||
import { capturePromptAttachments, DEFAULT_FILE_MIME_TYPE, effectivePromptAttachmentDelivery, READ_FAILURE_MESSAGE, type CapturableFile } from "./promptAttachmentCapture";
|
||||
|
||||
function file(name: string, type: string, size = 10): CapturableFile {
|
||||
@@ -79,3 +81,148 @@ describe("effectivePromptAttachmentDelivery", () => {
|
||||
])).toBe("folder");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PromptEditor attachment chips", () => {
|
||||
it("removes a pending attachment chip before sending the remaining attachments", () => {
|
||||
const editor = new PromptEditor();
|
||||
const onSend = vi.fn<NonNullable<PromptEditor["onSend"]>>();
|
||||
editor.onSend = onSend;
|
||||
setPromptEditorPrivate(editor, "draft", "please review");
|
||||
setPromptEditorPrivate(editor, "attachments", [
|
||||
{ id: "attachment-1", kind: "file", name: "report.pdf", mimeType: "application/pdf", data: "UkVQT1JU", size: 6 },
|
||||
{ id: "attachment-2", kind: "image", name: "shot.png", mimeType: "image/png", data: "UE5H", size: 3 },
|
||||
]);
|
||||
|
||||
const removeReport = findTemplateEventHandlerAfterValue<Event>(editor.render(), "Remove report.pdf", "@click=");
|
||||
removeReport(new Event("click"));
|
||||
|
||||
expect(templateContainsValue(editor.render(), "Remove report.pdf")).toBe(false);
|
||||
expect(templateContainsValue(editor.render(), "Remove shot.png")).toBe(true);
|
||||
|
||||
const send = findTemplateEventHandlerAfterMarker<Event>(editor.render(), "send-button");
|
||||
send(new Event("click"));
|
||||
|
||||
expect(onSend).toHaveBeenCalledTimes(1);
|
||||
expect(onSend).toHaveBeenCalledWith("please review", undefined, [
|
||||
{ kind: "image", mimeType: "image/png", data: "UE5H", name: "shot.png" },
|
||||
], "inline");
|
||||
});
|
||||
});
|
||||
|
||||
type TemplateEventHandler<E extends Event> = (event: E) => void;
|
||||
|
||||
function setPromptEditorPrivate(editor: PromptEditor, property: string, value: unknown): void {
|
||||
if (!Reflect.set(editor, property, value)) throw new Error(`Failed to set PromptEditor ${property}`);
|
||||
}
|
||||
|
||||
function findTemplateEventHandlerAfterMarker<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> {
|
||||
const handler = findOptionalTemplateEventHandlerAfterMarker<E>(template, marker);
|
||||
if (handler === undefined) throw new Error(`Expected template event handler after marker ${marker}`);
|
||||
return handler;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandlerAfterMarker<E extends Event>(template: TemplateResult, marker: string): TemplateEventHandler<E> | undefined {
|
||||
const strings = templateStrings(template);
|
||||
const values = templateValues(template);
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
const staticChunk = strings[index];
|
||||
if (staticChunk?.includes(marker) === true) {
|
||||
const handler = nextTemplateEventHandler<E>(values, index);
|
||||
if (handler !== undefined) return handler;
|
||||
}
|
||||
const nestedHandler = findOptionalTemplateEventHandlerAfterMarkerInValue<E>(values[index], marker);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandlerAfterMarkerInValue<E extends Event>(value: unknown, marker: string): TemplateEventHandler<E> | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const nestedHandler = findOptionalTemplateEventHandlerAfterMarkerInValue<E>(item, marker);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (isTemplateResult(value)) return findOptionalTemplateEventHandlerAfterMarker<E>(value, marker);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findTemplateEventHandlerAfterValue<E extends Event>(template: TemplateResult, expectedValue: unknown, marker: string): TemplateEventHandler<E> {
|
||||
const handler = findOptionalTemplateEventHandlerAfterValue<E>(template, expectedValue, marker);
|
||||
if (handler === undefined) throw new Error(`Expected template event handler after value ${String(expectedValue)}`);
|
||||
return handler;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandlerAfterValue<E extends Event>(template: TemplateResult, expectedValue: unknown, marker: string): TemplateEventHandler<E> | undefined {
|
||||
const strings = templateStrings(template);
|
||||
const values = templateValues(template);
|
||||
for (let index = 0; index < values.length; index += 1) {
|
||||
const value = values[index];
|
||||
if (value === expectedValue) {
|
||||
for (let handlerIndex = index + 1; handlerIndex < values.length; handlerIndex += 1) {
|
||||
const staticChunk = strings[handlerIndex];
|
||||
const maybeHandler = values[handlerIndex];
|
||||
if (staticChunk?.includes(marker) === true && isTemplateEventHandler<E>(maybeHandler)) return maybeHandler;
|
||||
}
|
||||
}
|
||||
const nestedHandler = findOptionalTemplateEventHandlerAfterValueInValue<E>(value, expectedValue, marker);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function findOptionalTemplateEventHandlerAfterValueInValue<E extends Event>(value: unknown, expectedValue: unknown, marker: string): TemplateEventHandler<E> | undefined {
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
const nestedHandler = findOptionalTemplateEventHandlerAfterValueInValue<E>(item, expectedValue, marker);
|
||||
if (nestedHandler !== undefined) return nestedHandler;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
if (isTemplateResult(value)) return findOptionalTemplateEventHandlerAfterValue<E>(value, expectedValue, marker);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function nextTemplateEventHandler<E extends Event>(values: readonly unknown[], startIndex: number): TemplateEventHandler<E> | undefined {
|
||||
for (let index = startIndex; index < values.length; index += 1) {
|
||||
const value = values[index];
|
||||
if (isTemplateEventHandler<E>(value)) return value;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function templateContainsValue(template: TemplateResult, expectedValue: unknown): boolean {
|
||||
return templateValues(template).some((value) => templateValueContains(value, expectedValue));
|
||||
}
|
||||
|
||||
function templateValueContains(value: unknown, expectedValue: unknown): boolean {
|
||||
if (value === expectedValue) return true;
|
||||
if (Array.isArray(value)) return value.some((item) => templateValueContains(item, expectedValue));
|
||||
if (isTemplateResult(value)) return templateContainsValue(value, expectedValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
function templateStrings(template: TemplateResult): readonly string[] {
|
||||
const strings = Reflect.get(template, "strings");
|
||||
if (!isStringArray(strings)) throw new Error("TemplateResult strings were unavailable");
|
||||
return strings;
|
||||
}
|
||||
|
||||
function templateValues(template: TemplateResult): readonly unknown[] {
|
||||
const values = Reflect.get(template, "values");
|
||||
if (!Array.isArray(values)) throw new Error("TemplateResult values were unavailable");
|
||||
return values.map((value: unknown) => value);
|
||||
}
|
||||
|
||||
function isTemplateResult(value: unknown): value is TemplateResult {
|
||||
return typeof value === "object" && value !== null && isStringArray(Reflect.get(value, "strings")) && Array.isArray(Reflect.get(value, "values"));
|
||||
}
|
||||
|
||||
function isTemplateEventHandler<E extends Event>(value: unknown): value is TemplateEventHandler<E> {
|
||||
return typeof value === "function";
|
||||
}
|
||||
|
||||
function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((item: unknown) => typeof item === "string");
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { RunTerminalCommandInput, TerminalCommandRun, Workspace } from "../api";
|
||||
import type { RunTerminalCommandInput, TerminalCommandRun, TerminalCommandRunFilter, Workspace } from "../api";
|
||||
import { createTerminalCommandRunsRuntime } from "./terminalRuntime";
|
||||
|
||||
const workspace: Workspace = {
|
||||
@@ -52,6 +52,32 @@ describe("terminal runtime", () => {
|
||||
await expect(handle.completed).resolves.toEqual(succeededRun);
|
||||
});
|
||||
|
||||
it("passes through command-run lookup helpers and open requests", async () => {
|
||||
const filter: TerminalCommandRunFilter = {
|
||||
projectId: "p1",
|
||||
workspaceId: "w1",
|
||||
statuses: ["running"],
|
||||
metadata: { "pi.operation": "test" },
|
||||
};
|
||||
const runs = [runningRun, succeededRun];
|
||||
const openTerminal = vi.fn();
|
||||
const api = {
|
||||
runTerminalCommand: vi.fn(),
|
||||
listCommandRuns: vi.fn(() => Promise.resolve(runs)),
|
||||
getCommandRun: vi.fn(() => Promise.resolve(succeededRun)),
|
||||
};
|
||||
const runtime = createTerminalCommandRunsRuntime("core", { api, openTerminal });
|
||||
|
||||
await expect(runtime.listCommandRuns(filter)).resolves.toEqual(runs);
|
||||
await expect(runtime.getCommandRun("run1")).resolves.toEqual(succeededRun);
|
||||
runtime.open({ terminalId: "t2" });
|
||||
|
||||
expect(api.listCommandRuns).toHaveBeenCalledWith(filter);
|
||||
expect(api.getCommandRun).toHaveBeenCalledWith("run1");
|
||||
expect(openTerminal).toHaveBeenCalledWith(undefined, { terminalId: "t2" });
|
||||
expect(api.runTerminalCommand).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("polls command-run records until completion", async () => {
|
||||
vi.useFakeTimers();
|
||||
const api = {
|
||||
@@ -73,4 +99,37 @@ describe("terminal runtime", () => {
|
||||
await expect(handle.completed).resolves.toEqual(succeededRun);
|
||||
expect(api.getCommandRun).toHaveBeenCalledWith("run1");
|
||||
});
|
||||
|
||||
it("rejects completion polling failures and clears the scheduled timer", async () => {
|
||||
const pollError = new Error("poll failed");
|
||||
const timerId = globalThis.setTimeout(() => undefined, 0);
|
||||
globalThis.clearTimeout(timerId);
|
||||
const scheduledPolls: (() => void)[] = [];
|
||||
const clearTimeout = vi.fn();
|
||||
const api = {
|
||||
runTerminalCommand: vi.fn(() => Promise.resolve(runningRun)),
|
||||
listCommandRuns: vi.fn(),
|
||||
getCommandRun: vi.fn(() => Promise.reject(pollError)),
|
||||
};
|
||||
const runtime = createTerminalCommandRunsRuntime("core", {
|
||||
api,
|
||||
openTerminal: vi.fn(),
|
||||
pollIntervalMs: 25,
|
||||
setTimeout: (handler) => {
|
||||
scheduledPolls.push(handler);
|
||||
return timerId;
|
||||
},
|
||||
clearTimeout,
|
||||
});
|
||||
|
||||
const handle = await runtime.runCommand({ workspace, title: "Build", command: "npm run build" });
|
||||
const poll = scheduledPolls[0];
|
||||
expect(poll).toBeDefined();
|
||||
poll?.();
|
||||
|
||||
await expect(handle.completed).rejects.toBe(pollError);
|
||||
expect(api.getCommandRun).toHaveBeenCalledWith("run1");
|
||||
expect(scheduledPolls).toHaveLength(1);
|
||||
expect(clearTimeout).toHaveBeenCalledWith(timerId);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,9 @@ import { chmod, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"
|
||||
import { join, resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { PiWebRuntimeResponse } from "../../shared/apiTypes.js";
|
||||
import { PI_WEB_CAPABILITIES } from "../../shared/capabilities.js";
|
||||
import type { MachineClient } from "./machineClient.js";
|
||||
import { MachineService } from "./machineService.js";
|
||||
import { MachineStore, machineStorePath } from "./machineStore.js";
|
||||
|
||||
@@ -97,6 +100,90 @@ describe("MachineService", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("fetches and caches remote runtime through the configured client", async () => {
|
||||
const body = remoteRuntimeBody();
|
||||
const requestJson = vi.fn<MachineClient["requestJson"]>(() => Promise.resolve({ statusCode: 200, headers: {}, body }));
|
||||
const factoryMachines: unknown[] = [];
|
||||
const remoteService = new MachineService(new MachineStore(storePath), {
|
||||
remoteClientFactory: (machine) => {
|
||||
factoryMachines.push(machine);
|
||||
return fakeRemoteClient({ requestJson });
|
||||
},
|
||||
now: () => new Date("2026-05-25T00:00:00.000Z"),
|
||||
runtimeCacheTtlMs: 10_000,
|
||||
});
|
||||
const machine = await remoteService.add({
|
||||
name: " Remote ",
|
||||
baseUrl: "https://remote.example.test/",
|
||||
token: "secret",
|
||||
headers: { "X-Pi-Web-Test": "yes" },
|
||||
});
|
||||
|
||||
const first = await remoteService.runtime(machine.id);
|
||||
const second = await remoteService.runtime(machine.id);
|
||||
|
||||
expect(first).toEqual({
|
||||
machineId: machine.id,
|
||||
ok: true,
|
||||
checkedAt: "2026-05-25T00:00:00.000Z",
|
||||
packageName: body.packageName,
|
||||
generatedAt: body.generatedAt,
|
||||
components: body.components,
|
||||
capabilities: body.capabilities,
|
||||
});
|
||||
expect(second).toEqual(first);
|
||||
expect(requestJson).toHaveBeenCalledTimes(1);
|
||||
expect(requestJson).toHaveBeenCalledWith("GET", "/api/pi-web/runtime", undefined, { timeoutMs: 3000 });
|
||||
expect(factoryMachines).toEqual([
|
||||
expect.objectContaining({
|
||||
id: machine.id,
|
||||
name: "Remote",
|
||||
baseUrl: "https://remote.example.test",
|
||||
token: "secret",
|
||||
headers: { "X-Pi-Web-Test": "yes" },
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("caches remote runtime errors and clears them after remote updates", async () => {
|
||||
let now = new Date("2026-05-25T00:00:00.000Z");
|
||||
const body = remoteRuntimeBody();
|
||||
const requestJson = vi.fn<MachineClient["requestJson"]>()
|
||||
.mockRejectedValueOnce(new Error("network down"))
|
||||
.mockResolvedValueOnce({ statusCode: 200, headers: {}, body });
|
||||
const remoteService = new MachineService(new MachineStore(storePath), {
|
||||
remoteClientFactory: () => fakeRemoteClient({ requestJson }),
|
||||
now: () => now,
|
||||
runtimeCacheTtlMs: 10_000,
|
||||
});
|
||||
const machine = await remoteService.add({ name: "Remote", baseUrl: "https://remote.example.test" });
|
||||
|
||||
const errorRuntime = await remoteService.runtime(machine.id);
|
||||
now = new Date("2026-05-25T00:00:01.000Z");
|
||||
const cachedErrorRuntime = await remoteService.runtime(machine.id);
|
||||
await remoteService.update(machine.id, { name: "Remote Updated" });
|
||||
now = new Date("2026-05-25T00:00:02.000Z");
|
||||
const refreshedRuntime = await remoteService.runtime(machine.id);
|
||||
|
||||
expect(errorRuntime).toEqual({
|
||||
machineId: machine.id,
|
||||
ok: false,
|
||||
checkedAt: "2026-05-25T00:00:00.000Z",
|
||||
error: "network down",
|
||||
});
|
||||
expect(cachedErrorRuntime).toEqual(errorRuntime);
|
||||
expect(refreshedRuntime).toEqual({
|
||||
machineId: machine.id,
|
||||
ok: true,
|
||||
checkedAt: "2026-05-25T00:00:02.000Z",
|
||||
packageName: body.packageName,
|
||||
generatedAt: body.generatedAt,
|
||||
components: body.components,
|
||||
capabilities: body.capabilities,
|
||||
});
|
||||
expect(requestJson).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("does not allow local machine mutation", async () => {
|
||||
await expect(service.update("local", { name: "Other" })).rejects.toThrow("Local machine cannot be changed");
|
||||
await expect(service.remove("local")).rejects.toThrow("Local machine cannot be deleted");
|
||||
@@ -112,3 +199,36 @@ async function expectOwnerOnlyMachineStore(path: string): Promise<void> {
|
||||
if (process.platform === "win32") return;
|
||||
expect((await stat(path)).mode & 0o777).toBe(0o600);
|
||||
}
|
||||
|
||||
function remoteRuntimeBody(): PiWebRuntimeResponse {
|
||||
return {
|
||||
packageName: "@jmfederico/pi-web",
|
||||
generatedAt: "2026-05-25T00:00:00.000Z",
|
||||
components: {
|
||||
web: {
|
||||
component: "web",
|
||||
label: "Remote Web",
|
||||
runtimeVersion: "1.0.0",
|
||||
available: true,
|
||||
capabilities: [PI_WEB_CAPABILITIES.sessionsDeleteArchived, PI_WEB_CAPABILITIES.piPackagesManage],
|
||||
},
|
||||
sessiond: {
|
||||
component: "sessiond",
|
||||
label: "Remote Session daemon",
|
||||
runtimeVersion: "1.0.0",
|
||||
available: true,
|
||||
capabilities: [PI_WEB_CAPABILITIES.sessionsDeleteArchived],
|
||||
},
|
||||
},
|
||||
capabilities: [PI_WEB_CAPABILITIES.sessionsDeleteArchived, PI_WEB_CAPABILITIES.piPackagesManage],
|
||||
};
|
||||
}
|
||||
|
||||
function fakeRemoteClient(overrides: Partial<MachineClient>): MachineClient {
|
||||
return {
|
||||
request: () => { throw new Error("HTTP request not configured for test"); },
|
||||
requestJson: () => { throw new Error("JSON request not configured for test"); },
|
||||
connectWebSocket: () => { throw new Error("WebSocket not configured for test"); },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -31,6 +31,49 @@ describe("createPiWebStatusCache", () => {
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("explicitly refreshes and replaces a fresh cached status", async () => {
|
||||
let now = 1_000;
|
||||
const load = vi.fn()
|
||||
.mockResolvedValueOnce(status("first"))
|
||||
.mockResolvedValueOnce(status("second"));
|
||||
const cache = createPiWebStatusCache(load, { ttlMs: 100, now: () => now });
|
||||
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "first" });
|
||||
now = 1_050;
|
||||
|
||||
await expect(cache.refresh()).resolves.toMatchObject({ generatedAt: "second" });
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "second" });
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("retains stale status and reports background refresh errors", async () => {
|
||||
let now = 1_000;
|
||||
const refreshError = new Error("refresh failed");
|
||||
const errorReported = createDeferred<unknown>();
|
||||
const onError = vi.fn((error: unknown) => {
|
||||
errorReported.resolve(error);
|
||||
});
|
||||
const load = vi.fn()
|
||||
.mockResolvedValueOnce(status("first"))
|
||||
.mockRejectedValueOnce(refreshError)
|
||||
.mockResolvedValueOnce(status("second"));
|
||||
const cache = createPiWebStatusCache(load, { ttlMs: 100, now: () => now, onError });
|
||||
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "first" });
|
||||
now = 1_101;
|
||||
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "first" });
|
||||
await expect(errorReported.promise).resolves.toBe(refreshError);
|
||||
expect(onError).toHaveBeenCalledTimes(1);
|
||||
expect(load).toHaveBeenCalledTimes(2);
|
||||
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "first" });
|
||||
await waitForMicrotasks();
|
||||
|
||||
await expect(cache.get()).resolves.toMatchObject({ generatedAt: "second" });
|
||||
expect(load).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it("deduplicates concurrent cold loads", async () => {
|
||||
const deferred = createDeferred<PiWebStatusResponse>();
|
||||
const load = vi.fn(() => deferred.promise);
|
||||
|
||||
@@ -36,6 +36,40 @@ describe("machine-scoped session proxy routes", () => {
|
||||
expect(daemon.requests).toEqual([{ method: "POST", path: "/auth/api-key", body: { providerId: "p", key: "k" } }]);
|
||||
});
|
||||
|
||||
it("forwards sessiond health and runtime aliases to daemon endpoints", async () => {
|
||||
const healthResponse = await app.inject({ method: "GET", url: "/api/machines/local/sessiond/health" });
|
||||
const runtimeResponse = await app.inject({ method: "GET", url: "/api/machines/local/sessiond/runtime" });
|
||||
|
||||
expect(healthResponse.statusCode).toBe(200);
|
||||
expect(healthResponse.json()).toEqual({ ok: true });
|
||||
expect(runtimeResponse.statusCode).toBe(200);
|
||||
expect(runtimeResponse.json()).toEqual({ ok: true });
|
||||
expect(daemon.requests).toEqual([
|
||||
{ method: "GET", path: "/health", body: undefined },
|
||||
{ method: "GET", path: "/runtime", body: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
it("forwards empty upstream responses without parsing a body", async () => {
|
||||
daemon.respondWith({ statusCode: 204, headers: {}, body: "" });
|
||||
|
||||
const response = await app.inject({ method: "DELETE", url: "/api/machines/local/sessions/session-1" });
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(response.body).toBe("");
|
||||
expect(daemon.requests).toEqual([{ method: "DELETE", path: "/sessions/session-1", body: undefined }]);
|
||||
});
|
||||
|
||||
it("returns a 502 response when the daemon request fails", async () => {
|
||||
daemon.failWith(new Error("connection refused"));
|
||||
|
||||
const response = await app.inject({ method: "GET", url: "/api/machines/local/sessions" });
|
||||
|
||||
expect(response.statusCode).toBe(502);
|
||||
expect(response.json()).toEqual({ error: "Session daemon unavailable: connection refused" });
|
||||
expect(daemon.requests).toEqual([{ method: "GET", path: "/sessions", body: undefined }]);
|
||||
});
|
||||
|
||||
it("preserves cwd query context when forwarding session event websockets", async () => {
|
||||
await app.listen({ host: "127.0.0.1", port: 0 });
|
||||
const socket = new WebSocket(`${serverUrl(app)}/api/machines/local/sessions/session-1/events?cwd=${encodeURIComponent("/repo")}`);
|
||||
@@ -49,9 +83,16 @@ describe("machine-scoped session proxy routes", () => {
|
||||
});
|
||||
});
|
||||
|
||||
interface FakeSessionDaemonResponse {
|
||||
statusCode: number;
|
||||
headers: Record<string, string>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
class FakeSessionDaemon {
|
||||
readonly requests: { method: string; path: string; body: unknown }[] = [];
|
||||
readonly websocketPaths: string[] = [];
|
||||
private readonly queuedResponses: (FakeSessionDaemonResponse | Error)[] = [];
|
||||
private readonly sockets = new Set<WebSocket>();
|
||||
|
||||
private constructor(private readonly upstream: WebSocketServer) {
|
||||
@@ -67,9 +108,19 @@ class FakeSessionDaemon {
|
||||
return new FakeSessionDaemon(upstream);
|
||||
}
|
||||
|
||||
request(method: string, path: string, body?: unknown): Promise<{ statusCode: number; headers: Record<string, string>; body: string }> {
|
||||
respondWith(response: FakeSessionDaemonResponse): void {
|
||||
this.queuedResponses.push(response);
|
||||
}
|
||||
|
||||
failWith(error: Error): void {
|
||||
this.queuedResponses.push(error);
|
||||
}
|
||||
|
||||
request(method: string, path: string, body?: unknown): Promise<FakeSessionDaemonResponse> {
|
||||
this.requests.push({ method, path, body });
|
||||
return Promise.resolve({ statusCode: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true }) });
|
||||
const queuedResponse = this.queuedResponses.shift();
|
||||
if (queuedResponse instanceof Error) return Promise.reject(queuedResponse);
|
||||
return Promise.resolve(queuedResponse ?? { statusCode: 200, headers: { "content-type": "application/json" }, body: JSON.stringify({ ok: true }) });
|
||||
}
|
||||
|
||||
connectWebSocket(path: string): WebSocket {
|
||||
|
||||
@@ -1,13 +1,21 @@
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm, symlink } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { DEFAULT_ATTACHMENT_FOLDER, saveAttachmentsToWorkspace } from "./attachmentService.js";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { formatDimensionNote, resizeImage, type ResizedImage } from "@earendil-works/pi-coding-agent";
|
||||
import { DEFAULT_ATTACHMENT_FOLDER, attachmentsToInlineImages, saveAttachmentsToWorkspace } from "./attachmentService.js";
|
||||
|
||||
vi.mock("@earendil-works/pi-coding-agent", () => ({
|
||||
formatDimensionNote: vi.fn(),
|
||||
resizeImage: vi.fn(),
|
||||
}));
|
||||
|
||||
let workspace: string;
|
||||
let externalDirectories: string[] = [];
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.mocked(formatDimensionNote).mockReset();
|
||||
vi.mocked(resizeImage).mockReset();
|
||||
workspace = await mkdtemp(join(tmpdir(), "pi-web-attachments-"));
|
||||
externalDirectories = [];
|
||||
});
|
||||
@@ -22,6 +30,63 @@ afterEach(async () => {
|
||||
const pngBytes = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
|
||||
const pngBase64 = pngBytes.toString("base64");
|
||||
|
||||
function resizedImage(overrides: Partial<ResizedImage> = {}): ResizedImage {
|
||||
return {
|
||||
data: "resized-data",
|
||||
mimeType: "image/png",
|
||||
originalWidth: 2400,
|
||||
originalHeight: 1200,
|
||||
width: 1200,
|
||||
height: 600,
|
||||
wasResized: true,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("attachmentsToInlineImages", () => {
|
||||
it("resizes images, drops unresizable images, and preserves dimension notes", async () => {
|
||||
const firstInput = Buffer.from("first image");
|
||||
const droppedInput = Buffer.from("too large");
|
||||
const thirdInput = Buffer.from("third image");
|
||||
const firstResized = resizedImage({ data: "first-resized", mimeType: "image/webp" });
|
||||
const thirdResized = resizedImage({
|
||||
data: "third-resized",
|
||||
mimeType: "image/jpeg",
|
||||
originalWidth: 640,
|
||||
originalHeight: 480,
|
||||
width: 640,
|
||||
height: 480,
|
||||
wasResized: false,
|
||||
});
|
||||
|
||||
vi.mocked(resizeImage)
|
||||
.mockResolvedValueOnce(firstResized)
|
||||
.mockResolvedValueOnce(null)
|
||||
.mockResolvedValueOnce(thirdResized);
|
||||
vi.mocked(formatDimensionNote)
|
||||
.mockReturnValueOnce("[Image dimensions changed.]")
|
||||
.mockReturnValueOnce(undefined);
|
||||
|
||||
await expect(attachmentsToInlineImages([
|
||||
{ kind: "image", mimeType: "image/png", data: firstInput.toString("base64"), name: "first.png" },
|
||||
{ kind: "image", mimeType: "image/png", data: droppedInput.toString("base64"), name: "huge.png" },
|
||||
{ kind: "image", mimeType: "image/jpeg", data: thirdInput.toString("base64"), name: "photo.jpg" },
|
||||
])).resolves.toEqual([
|
||||
{
|
||||
image: { type: "image", data: "first-resized", mimeType: "image/webp" },
|
||||
dimensionNote: "[Image dimensions changed.]",
|
||||
},
|
||||
{ image: { type: "image", data: "third-resized", mimeType: "image/jpeg" } },
|
||||
]);
|
||||
|
||||
expect(resizeImage).toHaveBeenNthCalledWith(1, firstInput, "image/png");
|
||||
expect(resizeImage).toHaveBeenNthCalledWith(2, droppedInput, "image/png");
|
||||
expect(resizeImage).toHaveBeenNthCalledWith(3, thirdInput, "image/jpeg");
|
||||
expect(formatDimensionNote).toHaveBeenNthCalledWith(1, firstResized);
|
||||
expect(formatDimensionNote).toHaveBeenNthCalledWith(2, thirdResized);
|
||||
});
|
||||
});
|
||||
|
||||
describe("saveAttachmentsToWorkspace", () => {
|
||||
it("writes attachments into the default folder and returns relative paths", async () => {
|
||||
const fixedNow = () => new Date("2026-06-13T12:05:01.123Z");
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { AuthStorage, ModelRegistry } from "@earendil-works/pi-coding-agent";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { OAuthFlowState } from "../../shared/apiTypes.js";
|
||||
import { AuthService, type AuthChange } from "./authService.js";
|
||||
import { OAuthLoginFlowService } from "./oauthLoginFlowService.js";
|
||||
|
||||
describe("AuthService", () => {
|
||||
it("saves API keys and emits a global auth change", () => {
|
||||
@@ -30,6 +32,39 @@ describe("AuthService", () => {
|
||||
expect(changes).toEqual([]);
|
||||
auth.dispose();
|
||||
});
|
||||
|
||||
it("refreshes auth state after OAuth login completes", () => {
|
||||
const authStorage = AuthStorage.inMemory();
|
||||
const modelRegistry = ModelRegistry.create(authStorage);
|
||||
const authFlows = new CapturingOAuthLoginFlowService();
|
||||
const auth = new AuthService({ modelRegistry, authFlows });
|
||||
const changes: AuthChange[] = [];
|
||||
auth.subscribe((change) => { changes.push(change); });
|
||||
const reload = vi.spyOn(authStorage, "reload");
|
||||
const refresh = vi.spyOn(modelRegistry, "refresh");
|
||||
const provider = authStorage.getOAuthProviders().find((option) => option.id === "anthropic");
|
||||
if (provider === undefined) throw new Error("Expected built-in OAuth provider");
|
||||
|
||||
expect(auth.startOAuthLogin(provider.id)).toMatchObject({ providerId: provider.id, providerName: provider.name, status: "running" });
|
||||
|
||||
const startOptions = authFlows.startCalls.at(0);
|
||||
if (startOptions === undefined) throw new Error("Expected OAuth flow to start");
|
||||
expect(startOptions.providerId).toBe(provider.id);
|
||||
expect(startOptions.providerName).toBe(provider.name);
|
||||
expect(startOptions.authStorage).toBe(authStorage);
|
||||
expect(changes).toEqual([]);
|
||||
|
||||
reload.mockClear();
|
||||
refresh.mockClear();
|
||||
if (startOptions.onComplete === undefined) throw new Error("Expected OAuth completion callback");
|
||||
startOptions.onComplete();
|
||||
|
||||
expect(reload).toHaveBeenCalledOnce();
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
expect(changes).toEqual([{}]);
|
||||
auth.dispose();
|
||||
expect(authFlows.disposed).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
function createAuthService(data: Parameters<typeof AuthStorage.inMemory>[0] = {}) {
|
||||
@@ -40,3 +75,17 @@ function createAuthService(data: Parameters<typeof AuthStorage.inMemory>[0] = {}
|
||||
auth.subscribe((change) => { changes.push(change); });
|
||||
return { auth, authStorage, changes };
|
||||
}
|
||||
|
||||
class CapturingOAuthLoginFlowService extends OAuthLoginFlowService {
|
||||
readonly startCalls: Parameters<OAuthLoginFlowService["start"]>[0][] = [];
|
||||
disposed = false;
|
||||
|
||||
override start(options: Parameters<OAuthLoginFlowService["start"]>[0]): OAuthFlowState {
|
||||
this.startCalls.push(options);
|
||||
return { flowId: "flow-1", providerId: options.providerId, providerName: options.providerName, status: "running", progress: [] };
|
||||
}
|
||||
|
||||
override dispose(): void {
|
||||
this.disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ afterEach(() => {
|
||||
describe("OAuthLoginFlowService", () => {
|
||||
it("round-trips prompt responses and completes the flow", async () => {
|
||||
let promptValue: string | undefined;
|
||||
const onComplete = vi.fn();
|
||||
const service = new OAuthLoginFlowService();
|
||||
const state = service.start({
|
||||
providerId: "test-provider",
|
||||
@@ -22,6 +23,7 @@ describe("OAuthLoginFlowService", () => {
|
||||
promptValue = await callbacks.onPrompt({ message: "Paste code", placeholder: "code" });
|
||||
callbacks.onProgress?.(`Got ${promptValue}`);
|
||||
}),
|
||||
onComplete,
|
||||
});
|
||||
|
||||
const prompt = state.prompt;
|
||||
@@ -35,6 +37,7 @@ describe("OAuthLoginFlowService", () => {
|
||||
|
||||
expect(promptValue).toBe("abc123");
|
||||
expect(service.get(state.flowId)).toMatchObject({ status: "complete", progress: ["Waiting for code", "Got abc123", "Login complete"] });
|
||||
expect(onComplete).toHaveBeenCalledOnce();
|
||||
service.dispose();
|
||||
});
|
||||
|
||||
@@ -113,6 +116,30 @@ describe("OAuthLoginFlowService", () => {
|
||||
service.dispose();
|
||||
});
|
||||
|
||||
it("rejects pending prompts when disposed", async () => {
|
||||
const promptRejected = deferred<Error>();
|
||||
const service = new OAuthLoginFlowService();
|
||||
const state = service.start({
|
||||
providerId: "test-provider",
|
||||
providerName: "Test Provider",
|
||||
authStorage: fakeAuthStorage(async (_providerId, callbacks) => {
|
||||
try {
|
||||
await callbacks.onPrompt({ message: "Paste code" });
|
||||
} catch (error) {
|
||||
promptRejected.resolve(toError(error));
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
expect(state.prompt).toBeDefined();
|
||||
|
||||
service.dispose();
|
||||
|
||||
await expect(promptRejected.promise).resolves.toMatchObject({ message: "Login cancelled" });
|
||||
expect(() => { service.get(state.flowId); }).toThrow("OAuth login flow not found");
|
||||
});
|
||||
|
||||
it("rejects stale or duplicate responses", () => {
|
||||
const service = new OAuthLoginFlowService();
|
||||
const state = service.start({
|
||||
|
||||
@@ -43,7 +43,7 @@ describe("terminal routes", () => {
|
||||
expect(terminals.events).toEqual([`close-cwd:${requestCwd}`]);
|
||||
});
|
||||
|
||||
it("routes command-run create, filter, cancel, and terminal continue requests", async () => {
|
||||
it("routes command-run create, get, filter, cancel, and terminal continue requests", async () => {
|
||||
const createResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/terminal-command-runs",
|
||||
@@ -51,7 +51,16 @@ describe("terminal routes", () => {
|
||||
});
|
||||
|
||||
expect(createResponse.statusCode).toBe(200);
|
||||
expect(createResponse.json<TerminalCommandRun>()).toMatchObject({ id: "run1", terminalId: "t-run", status: "running" });
|
||||
const createdRun = createResponse.json<TerminalCommandRun>();
|
||||
expect(createdRun).toMatchObject({ id: "run1", terminalId: "t-run", status: "running" });
|
||||
|
||||
const getResponse = await app.inject({ method: "GET", url: "/terminal-command-runs/run1" });
|
||||
expect(getResponse.statusCode).toBe(200);
|
||||
expect(getResponse.json<TerminalCommandRun>()).toEqual(createdRun);
|
||||
|
||||
const missingGetResponse = await app.inject({ method: "GET", url: "/terminal-command-runs/missing" });
|
||||
expect(missingGetResponse.statusCode).toBe(404);
|
||||
expect(missingGetResponse.json()).toEqual({ error: "Terminal command run not found" });
|
||||
|
||||
const listResponse = await app.inject({ method: "GET", url: `/terminal-command-runs?projectId=p1&statuses=running&metadata=${encodeURIComponent(JSON.stringify({ "pi.operation": "test" }))}` });
|
||||
|
||||
@@ -67,6 +76,22 @@ describe("terminal routes", () => {
|
||||
expect(continueResponse.statusCode).toBe(200);
|
||||
expect(terminals.events).toContain("continue:t-run");
|
||||
});
|
||||
|
||||
it("rejects invalid command-run filter and metadata queries", async () => {
|
||||
const invalidStatusResponse = await app.inject({ method: "GET", url: "/terminal-command-runs?statuses=running,stuck" });
|
||||
expect(invalidStatusResponse.statusCode).toBe(400);
|
||||
expect(invalidStatusResponse.json()).toEqual({ error: "Invalid command run status: stuck" });
|
||||
|
||||
const arrayMetadataResponse = await app.inject({ method: "GET", url: `/terminal-command-runs?metadata=${encodeURIComponent(JSON.stringify(["not", "an", "object"]))}` });
|
||||
expect(arrayMetadataResponse.statusCode).toBe(400);
|
||||
expect(arrayMetadataResponse.json()).toEqual({ error: "metadata filter must be an object" });
|
||||
|
||||
const nonStringMetadataResponse = await app.inject({ method: "GET", url: `/terminal-command-runs?metadata=${encodeURIComponent(JSON.stringify({ "pi.operation": 42 }))}` });
|
||||
expect(nonStringMetadataResponse.statusCode).toBe(400);
|
||||
expect(nonStringMetadataResponse.json()).toEqual({ error: "metadata filter value must be a string: pi.operation" });
|
||||
|
||||
expect(terminals.filters).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
class FakeTerminals implements TerminalRouteService {
|
||||
|
||||
@@ -380,4 +380,16 @@ describe("moveWorkspaceFile", () => {
|
||||
expect(source.content).toBe("data");
|
||||
await expect(readFile(join(outsideDir, "evil.txt"), "utf8")).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it("prevents moving a source symlink that escapes the workspace", async () => {
|
||||
const root = await tempWorkspace();
|
||||
const outsideDir = await mkdtemp(join(tmpdir(), "pi-web-move-source-outside-"));
|
||||
roots.push(outsideDir);
|
||||
await writeFile(join(outsideDir, "secret.txt"), "secret");
|
||||
await symlink(join(outsideDir, "secret.txt"), join(root, "source-link.txt"));
|
||||
|
||||
await expect(moveWorkspaceFile(root, "source-link.txt", "moved.txt")).rejects.toThrow("Path escapes workspace");
|
||||
await expect(readWorkspaceFile(root, "moved.txt")).rejects.toThrow("Path does not exist");
|
||||
await expect(readFile(join(outsideDir, "secret.txt"), "utf8")).resolves.toBe("secret");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user