Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

test(e2e): cover chat, asks, conversations, recovery, and access key in the browser

Alan Buscagliadc425c0db48d
diff --git a/e2e/serve.ts b/e2e/serve.ts
new file mode 100644
index 0000000..c11351d
--- /dev/null
+++ b/e2e/serve.ts
@@ -0,0 +1,19 @@
+// Starts the daemon for Playwright with the fake agent, a fresh data dir, and a known token.
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { E2E_TOKEN } from "./token.ts";
+
+const dataDir = join(tmpdir(), "gentle-dot-e2e");
+rmSync(dataDir, { recursive: true, force: true });
+mkdirSync(dataDir, { recursive: true });
+writeFileSync(join(dataDir, "token"), `${E2E_TOKEN}\n`, { mode: 0o600 });
+
+process.env.GENTLE_DOT_DATA_DIR = dataDir;
+process.env.GENTLE_DOT_WORKSPACE = dataDir;
+process.env.GENTLE_DOT_AGENT_BIN = process.execPath;
+process.env.GENTLE_DOT_AGENT_ARGS = JSON.stringify([
+ fileURLToPath(new URL("../packages/daemon/test/fixtures/fake-agent.ts", import.meta.url)),
+]);
+await import("../packages/daemon/src/cli.ts");
diff --git a/e2e/token.ts b/e2e/token.ts
new file mode 100644
index 0000000..5eed954
--- /dev/null
+++ b/e2e/token.ts
@@ -0,0 +1 @@
+export const E2E_TOKEN = "e2e-token-0123456789abcdefghijklmnopqrstuv";
diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json
new file mode 100644
index 0000000..1fb003d
--- /dev/null
+++ b/e2e/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../tsconfig.base.json",
+ "compilerOptions": {
+ "composite": true,
+ "emitDeclarationOnly": true,
+ "noEmit": false,
+ "outDir": "../node_modules/.e2e-types",
+ "lib": ["ES2023", "DOM"]
+ },
+ "include": ["."]
+}
diff --git a/e2e/web.spec.ts b/e2e/web.spec.ts
new file mode 100644
index 0000000..0f19243
--- /dev/null
+++ b/e2e/web.spec.ts
@@ -0,0 +1,75 @@
+import { expect, type Page, test } from "@playwright/test";
+import { E2E_TOKEN } from "./token.ts";
+
+async function open(page: Page) {
+ await page.goto(`/#token=${E2E_TOKEN}`);
+ await expect(page.getByRole("textbox", { name: "Message" })).toBeEnabled();
+}
+
+async function say(page: Page, text: string) {
+ const box = page.getByRole("textbox", { name: "Message" });
+ await box.fill(text);
+ await box.press("Enter");
+}
+
+test("chats and streams the answer, and removes the token from the address bar", async ({ page }) => {
+ await open(page);
+ expect(page.url()).not.toContain("token");
+ await say(page, "hello there");
+ await expect(page.locator(".message-user").last()).toHaveText("hello there");
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: hello there");
+});
+
+test("answers a question card", async ({ page }) => {
+ await open(page);
+ await say(page, "ask:select");
+ const card = page.getByRole("region", { name: "The assistant needs your answer" });
+ await expect(card).toContainText("Pick a color");
+ await card.getByRole("button", { name: "Blue" }).click();
+ await expect(card).toBeHidden();
+ await expect(page.locator(".message-assistant").last()).toHaveText("You chose Blue");
+});
+
+test("starts a new conversation and reopens the previous one", async ({ page }) => {
+ await open(page);
+ await page.getByRole("button", { name: "New conversation" }).click();
+ await expect(page.getByText("Hi! What can I do for you?")).toBeVisible();
+ await say(page, "plan my trip");
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: plan my trip");
+ await page.getByRole("button", { name: "New conversation" }).click();
+ await expect(page.getByText("Hi! What can I do for you?")).toBeVisible();
+ await page.getByRole("button", { name: "Conversations" }).click();
+ await page
+ .getByRole("navigation", { name: "Earlier conversations" })
+ .getByRole("button", { name: /plan my trip/ })
+ .click();
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: plan my trip");
+ await expect(page.getByRole("heading", { level: 1 })).toHaveText("plan my trip");
+});
+
+test("offers to continue after the assistant was interrupted", async ({ page }) => {
+ await open(page);
+ await say(page, "crash");
+ await expect(page.getByText("I was interrupted. Continue?")).toBeVisible({ timeout: 15_000 });
+ await page.getByRole("button", { name: "Continue" }).click();
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: Continue where you left off.");
+ await expect(page.getByText("I was interrupted. Continue?")).toBeHidden();
+});
+
+test("keeps the conversation after a page reload", async ({ page }) => {
+ await open(page);
+ await say(page, "remember this");
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: remember this");
+ await page.reload();
+ await expect(page.locator(".message-assistant").last()).toHaveText("Echo: remember this");
+});
+
+test("explains a rejected access key", async ({ page }) => {
+ await page.goto("/#token=wrong-token");
+ await expect(page.getByRole("status")).toContainText("This link is not valid anymore");
+});
+
+test("asks for the printed link when there is no access key", async ({ page }) => {
+ await page.goto("/");
+ await expect(page.getByRole("status")).toContainText("Open the link the assistant printed");
+});
diff --git a/packages/daemon/src/bridge.d.ts b/packages/daemon/src/bridge.d.ts
new file mode 100644
index 0000000..f6a8ef1
--- /dev/null
+++ b/packages/daemon/src/bridge.d.ts
@@ -0,0 +1,51 @@
+import type { AgentState, ClientMessage, ServerPayload } from "@gentle-dot/protocol";
+import type { AgentSupervisor } from "./supervisor.ts";
+export interface BridgeClient {
+ send(payload: ServerPayload): void;
+}
+export interface BridgeOptions {
+ dataDir: string;
+ log?: (line: string) => void;
+}
+/**
+ * Translates between protocol v1 clients and the supervised agent: it keeps
+ * the derived agent state, the pending asks, and the streaming message ids,
+ * and broadcasts every agent event to all connected clients.
+ */
+export declare class DotBridge {
+ private readonly clients;
+ private readonly asks;
+ private readonly runningTools;
+ private readonly seenRequestIds;
+ private readonly sessionDir;
+ private readonly supervisor;
+ private readonly options;
+ private state;
+ private interrupted;
+ private nextMessage;
+ private assistantId;
+ constructor(supervisor: AgentSupervisor, options: BridgeOptions);
+ get agentState(): AgentState;
+ attach(client: BridgeClient): () => void;
+ handle(client: BridgeClient, message: ClientMessage): Promise<void>;
+ private dispatch;
+ private afterConversationChange;
+ private loadHistory;
+ private conversationsPayload;
+ private conversationRef;
+ private activeRef;
+ private onAgentEvent;
+ private onMessageStart;
+ private onMessageUpdate;
+ private onMessageEnd;
+ private onTool;
+ private onUiRequest;
+ private resolveAsk;
+ private clearRun;
+ private deriveState;
+ private refreshState;
+ private alreadySeen;
+ private broadcast;
+ private deliver;
+ private log;
+}
diff --git a/packages/daemon/src/cli.d.ts b/packages/daemon/src/cli.d.ts
new file mode 100644
index 0000000..b798801
--- /dev/null
+++ b/packages/daemon/src/cli.d.ts
@@ -0,0 +1,2 @@
+#!/usr/bin/env node
+export {};
diff --git a/packages/daemon/src/config.d.ts b/packages/daemon/src/config.d.ts
new file mode 100644
index 0000000..daeb60d
--- /dev/null
+++ b/packages/daemon/src/config.d.ts
@@ -0,0 +1,12 @@
+export interface DotConfig {
+ port: number;
+ host: string;
+ dataDir: string;
+ workspace: string;
+ uiDir: string;
+ agentCommand: string;
+ agentArgs: string[];
+ allowedOrigins: string[];
+}
+/** Resolves configuration from environment variables, then `~/.gentle-dot/config.json`, then defaults. */
+export declare function loadConfig(env?: NodeJS.ProcessEnv): DotConfig;
diff --git a/packages/daemon/src/conversations.d.ts b/packages/daemon/src/conversations.d.ts
new file mode 100644
index 0000000..60ad2a6
--- /dev/null
+++ b/packages/daemon/src/conversations.d.ts
@@ -0,0 +1,8 @@
+import type { ConversationSummary, HistoryMessage } from "@gentle-dot/protocol";
+/** Session files under `sessionDir` (and one level of subfolders), newest first. */
+export declare function listConversations(sessionDir: string): ConversationSummary[];
+export declare function conversationIdOf(sessionDir: string, sessionFile: string): string;
+/** Resolves a client-supplied id to a session file inside `sessionDir`, or undefined. */
+export declare function resolveConversation(sessionDir: string, id: string): string | undefined;
+/** Converts Pi `get_messages` output into display messages; consecutive assistant messages form one turn. */
+export declare function historyFromMessages(messages: unknown[]): HistoryMessage[];
diff --git a/packages/daemon/src/daemon.d.ts b/packages/daemon/src/daemon.d.ts
new file mode 100644
index 0000000..d0984db
--- /dev/null
+++ b/packages/daemon/src/daemon.d.ts
@@ -0,0 +1,29 @@
+import { DotBridge } from "./bridge.ts";
+import { AgentSupervisor } from "./supervisor.ts";
+export interface DaemonOptions {
+ port: number;
+ host: string;
+ dataDir: string;
+ workspace: string;
+ /** Directory with the built web UI (`index.html`). */
+ uiDir: string;
+ agentCommand: string;
+ agentArgs?: string[];
+ agentExtraArgs?: string[];
+ agentEnv?: NodeJS.ProcessEnv;
+ /** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */
+ allowedOrigins?: string[];
+ backoffMs?: number[];
+ log?: (line: string) => void;
+}
+export interface DotDaemon {
+ port: number;
+ token: string;
+ url: string;
+ bridge: DotBridge;
+ supervisor: AgentSupervisor;
+ close(): Promise<void>;
+}
+/** Reads the access token from `<dataDir>/token`, creating a random one (mode 0600) when absent. */
+export declare function ensureToken(dataDir: string): string;
+export declare function startDaemon(options: DaemonOptions): Promise<DotDaemon>;
diff --git a/packages/daemon/src/jsonl.d.ts b/packages/daemon/src/jsonl.d.ts
new file mode 100644
index 0000000..c4d5085
--- /dev/null
+++ b/packages/daemon/src/jsonl.d.ts
@@ -0,0 +1,14 @@
+/**
+ * Strict JSONL framing for the Pi RPC protocol: records are split on LF bytes
+ * only. Node's `readline` is deliberately avoided because it also splits on
+ * U+2028 and U+2029, which are valid inside JSON strings.
+ */
+export declare class JsonlDecoder {
+ private pending;
+ private readonly onRecord;
+ private readonly onMalformed;
+ constructor(onRecord: (record: unknown) => void, onMalformed?: (line: string) => void);
+ push(chunk: Buffer): void;
+ private emit;
+}
+export declare function encodeRecord(record: unknown): string;
diff --git a/packages/daemon/src/presentation.d.ts b/packages/daemon/src/presentation.d.ts
new file mode 100644
index 0000000..f1bb989
--- /dev/null
+++ b/packages/daemon/src/presentation.d.ts
@@ -0,0 +1,11 @@
+import type { ActivityKind } from "@gentle-dot/protocol";
+/**
+ * Turns an internal tool call into a neutral activity. Tool names never reach
+ * the user; only the kind and a short human title do.
+ */
+export declare function describeTool(toolName: string, args: unknown): {
+ kind: ActivityKind;
+ title: string;
+};
+/** Plain text of a user or assistant message whose content is a string or content blocks. */
+export declare function textOf(message: unknown): string;
diff --git a/packages/daemon/src/supervisor.d.ts b/packages/daemon/src/supervisor.d.ts
new file mode 100644
index 0000000..397eda8
--- /dev/null
+++ b/packages/daemon/src/supervisor.d.ts
@@ -0,0 +1,91 @@
+/** A record the agent wrote to stdout that is not a command response. */
+export type AgentRecord = {
+ type: string;
+ [key: string]: unknown;
+};
+export type RpcResponse = {
+ type: "response";
+ id?: string;
+ command: string;
+ success: boolean;
+ data?: unknown;
+ error?: string;
+};
+export type SupervisorState = "stopped" | "starting" | "ready" | "restarting";
+export type SupervisorEvent = AgentRecord | {
+ type: "supervisor_state";
+ state: SupervisorState;
+} | {
+ type: "interrupted";
+};
+export interface SupervisorOptions {
+ /** Executable to run, for example `gentle-shell`. */
+ command: string;
+ /** Arguments placed before the RPC arguments (used to run a script with node). */
+ args?: string[];
+ /** Arguments placed after the RPC arguments. */
+ extraArgs?: string[];
+ cwd: string;
+ /** Directory for `sessions/` and `state.json`. */
+ dataDir: string;
+ env?: NodeJS.ProcessEnv;
+ /** Respawn delays; the last value repeats. Default 1s, 2s, 4s, 8s, 16s, 30s. */
+ backoffMs?: number[];
+ /** Uptime after which the backoff starts over. Default 30s. */
+ stableMs?: number;
+ /** Deadline for one command response. Default 5 minutes. */
+ requestTimeoutMs?: number;
+ /** Deadline for the agent to answer its first `get_state`. Default 60s. */
+ startTimeoutMs?: number;
+ /** Grace period after closing stdin before SIGTERM. Default 5s. */
+ stopTimeoutMs?: number;
+ log?: (line: string) => void;
+}
+/**
+ * Runs the agent (`gentle-shell --mode rpc`) as a child process, correlates
+ * commands with responses, forwards session events, and respawns the agent
+ * after an unexpected exit, reopening the same conversation.
+ */
+export declare class AgentSupervisor {
+ state: SupervisorState;
+ busy: boolean;
+ sessionFile: string | undefined;
+ sessionId: string | undefined;
+ model: string | undefined;
+ private child;
+ private readonly pending;
+ private readonly listeners;
+ private nextId;
+ private attempts;
+ private spawnedAt;
+ private stopping;
+ private interrupted;
+ private restartTimer;
+ private closeWaiters;
+ private readonly sessionDir;
+ private readonly stateFile;
+ private readonly options;
+ constructor(options: SupervisorOptions);
+ get pid(): number | undefined;
+ onEvent(listener: (event: SupervisorEvent) => void): () => void;
+ /** Spawns the agent and resolves once it answered `get_state`. */
+ start(): Promise<void>;
+ /** Sends a command and resolves with its successful response. */
+ request(command: AgentRecord): Promise<RpcResponse>;
+ /** Writes a record that has no response, such as `extension_ui_response`. */
+ send(record: AgentRecord): void;
+ stop(): Promise<void>;
+ private spawnAndInitialize;
+ private spawnChild;
+ private rawRequest;
+ private handleRecord;
+ private handleClose;
+ private scheduleRestart;
+ private refreshSession;
+ private applyState;
+ private readPersistedSession;
+ private persistSession;
+ private setState;
+ private emit;
+ private log;
+}
diff --git a/packages/daemon/src/white-label.d.ts b/packages/daemon/src/white-label.d.ts
new file mode 100644
index 0000000..3c9d98c
--- /dev/null
+++ b/packages/daemon/src/white-label.d.ts
@@ -0,0 +1,10 @@
+/** Internal names that must never reach the user (docs/design.md §5). */
+export declare const HIDDEN_NAMES: RegExp[];
+/** Rewrites internal names in harness-generated text shown to the user. */
+export declare function presentText(text: string): string;
+/** Informational notifications are harness chatter; warnings and errors still reach the user. */
+export declare function shouldShowToast(level: "info" | "warning" | "error"): boolean;
+/** Internal slash commands are not part of the product. */
+export declare function isBlockedInput(text: string): boolean;
+/** Writes the identity prompt to `<dataDir>/identity.md` and returns the agent arguments that load it. */
+export declare function identityArgs(dataDir: string): string[];
diff --git a/playwright.config.ts b/playwright.config.ts
new file mode 100644
index 0000000..d297073
--- /dev/null
+++ b/playwright.config.ts
@@ -0,0 +1,23 @@
+import { defineConfig, devices } from "@playwright/test";
+
+const PORT = 4391;
+
+export default defineConfig({
+ testDir: "e2e",
+ fullyParallel: false,
+ workers: 1,
+ timeout: 30_000,
+ reporter: [["list"]],
+ use: {
+ baseURL: `http://127.0.0.1:${PORT}`,
+ trace: "retain-on-failure",
+ },
+ projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }],
+ webServer: {
+ command: "pnpm build && node e2e/serve.ts",
+ url: `http://127.0.0.1:${PORT}/health`,
+ env: { GENTLE_DOT_PORT: String(PORT) },
+ reuseExistingServer: false,
+ timeout: 60_000,
+ },
+});
diff --git a/tsconfig.json b/tsconfig.json
index 17b1ddd..ffc1c0c 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -9,6 +9,9 @@
},
{
"path": "packages/ui"
+ },
+ {
+ "path": "e2e"
}
]
}