Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 28 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ claude --plugin-dir ./apps/hook
**Config-only settings (`~/.plannotator/config.json`)**: Some settings have no env-var equivalent and are toggled by editing the config file directly:

- `pfmReminder` (`true` / `false`, default `false`) — when enabled, a Plannotator Flavored Markdown reminder is injected at plan-time describing the renderer's extensions (code-file links, callouts, tables, diagrams, task lists, hex swatches, wiki-links). Lets the planning agent enrich plans with PFM features without having to discover them. Composes cleanly with the compound-skill improvement hook. Supported across all three runtimes: Claude Code (`improve-context` PreToolUse hook in `apps/hook/server/index.ts`), OpenCode (`experimental.chat.system.transform` in `apps/opencode-plugin/index.ts`), and Pi (`before_agent_start` in `apps/pi-extension/index.ts`).
- `legacyTabMode` (`true` / `false`, default `false`) — when enabled, the daemon opens a new browser tab for every session regardless of whether a frontend is already connected. Sessions use the full-screen `CompletionOverlay` with auto-close instead of the inline `CompletionBanner`. Preserves the pre-frontend tab-per-session behavior for users who prefer it.

**Legacy:** `SSH_TTY` and `SSH_CONNECTION` are still detected when `PLANNOTATOR_REMOTE` is unset. Set `PLANNOTATOR_REMOTE=1` / `true` to force remote mode or `0` / `false` to force local mode.

Expand Down Expand Up @@ -234,11 +235,33 @@ The daemon is the single long-running Bun server used by normal plan/review/anno
| `/daemon/sessions/:id/cancel` | POST | Cancel a session and dispose its resources |
| `/daemon/sessions/:id` | DELETE | Delete a session record |
| `/daemon/shutdown` | POST | Ask the daemon to stop |
| `/daemon/ws` | WebSocket | Multiplex daemon lifecycle events, session-scoped external annotation events, agent job events, and correlated session actions |
| `/daemon/config` | GET | Read global config (`~/.plannotator/config.json`) |
| `/daemon/config` | POST | Write global config keys (allowlisted: `displayName`, `pfmReminder`, `legacyTabMode`, `diffOptions`, `conventionalComments`, `conventionalLabels`) |
| `/daemon/git/user` | GET | Return git user name from `git config user.name` |
| `/daemon/vaults` | GET | Detect available Obsidian vaults |
| `/daemon/obsidian/vaults` | GET | Alias for `/daemon/vaults` |
| `/daemon/hooks/status` | GET | Return PFM reminder and improvement hook status |
| `/daemon/projects` | DELETE | Remove a project by `?cwd=` (optional `?clean=1` to cancel active sessions) |
| `/daemon/projects/prs` | GET | List open PRs for a project (`?cwd=`) |
| `/daemon/projects/prs/detailed` | GET | List PRs with review metadata for dashboard (`?cwd=`) |
| `/daemon/fs/list` | GET | List directory contents (`?path=`) |
| `/daemon/ws` | WebSocket | Multiplex daemon lifecycle events, session-scoped external annotation events, agent job events, session revision events, and correlated session actions |
| `/s/:id` | GET | Serve the browser HTML for a session |
| `/s/:id/api/...` | Any | Route browser API requests to that session's plan/review/annotate handler |

Runtime live updates for daemon lifecycle events, external annotations, and agent jobs are delivered through `/daemon/ws`. Session-scoped updates subscribe by `{ family, sessionId }`. HTTP endpoints below remain for snapshots, mutations, uploads, and large payloads. AI query token streaming remains on `/api/ai/query`.
Runtime live updates for daemon lifecycle events, external annotations, agent jobs, and session revisions are delivered through `/daemon/ws`. Session-scoped updates subscribe by `{ family, sessionId }`. HTTP endpoints below remain for snapshots, mutations, uploads, and large payloads. AI query token streaming remains on `/api/ai/query`.

### Session Persistence and Resubmission

When a user denies a plan (or sends feedback on a review/annotation), the session enters `awaiting-resubmission` status instead of completing. The session's HTTP handler stays alive. When the agent replans and submits again via `POST /daemon/sessions`, the daemon matches the new submission to the existing session by a match key (`plan:project:slug` for plans, `review:project:branch` for reviews, `annotate:project:filePath` for single-file annotations). The session reactivates in place — the frontend receives a `session-revision` event via WebSocket with the updated content.

**Sessions never die.** No session type calls `store.complete()` from its decision handler. All sessions survive feedback, approve, and exit — the HTTP handler stays alive and the tab keeps working. `registerPersistentDecision` always calls `store.suspend()`. `registerReviewDecision` always calls `store.idle()`. Non-terminal sessions have no expiry timer.

**Session statuses (plan/annotate):** `active` → `awaiting-resubmission` (on any decision) → `active` (on resubmit) → `awaiting-resubmission` ... repeating.

**Session statuses (code review):** `active` → `idle` (on any decision) → `active` (on agent resubmit) → `idle` ... repeating.

**Event families:** `daemon`, `external-annotations`, `agent-jobs`, `session-revision`.

### Plan Server (`packages/server/index.ts`)

Expand Down Expand Up @@ -309,7 +332,9 @@ Runtime live updates for daemon lifecycle events, external annotations, and agen

| Endpoint | Method | Purpose |
| --------------------- | ------ | ------------------------------------------ |
| `/api/plan` | GET | Returns `{ plan, origin, mode: "annotate", filePath, sourceInfo?, gate, renderAs?, rawHtml? }` |
| `/api/plan` | GET | Returns `{ plan, origin, mode: "annotate", filePath, sourceInfo?, gate, renderAs?, rawHtml?, previousPlan, versionInfo }` |
| `/api/plan/version` | GET | Fetch specific version (`?v=N`) — single-file annotate only |
| `/api/plan/versions` | GET | List all versions — single-file annotate only |
| `/api/feedback` | POST | Submit annotations (body: feedback, annotations) |
| `/api/approve` | POST | Approve without feedback (review-gate UX, `--gate`) |
| `/api/exit` | POST | Close session without feedback |
Expand Down
1 change: 1 addition & 0 deletions apps/debug-frontend/src/daemon/events/hub-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ export class DaemonHubClient {
this.socket = undefined;
this.daemonSubscribed = false;
socket?.close();
this.scheduleReconnect();
return;
}
if (
Expand Down
2 changes: 2 additions & 0 deletions apps/frontend/.oxfmtignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist
src/routeTree.gen.ts
34 changes: 34 additions & 0 deletions apps/frontend/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# @plannotator/debug-frontend

Debug/development harness UI for the Plannotator daemon runtime. **Not production code** — this is a
testbed for exercising daemon sessions, verifying event streams, and testing session lifecycle actions.

## Shape

- `src/routes` is only TanStack Router wiring.
- `src/daemon` owns the typed daemon API client and contracts.
- `src/sessions` owns session ids, session state, the dashboard, and mode dispatch.
- `src/plan`, `src/review`, `src/annotate`, `src/archive`, and `src/setup-goal` own product views.
- `src/testing` owns contract fixtures and browser helpers.

The shell talks to session APIs through `/s/:sessionId/api`, never root `/api`.

The build is intentionally single-file HTML for daemon serving. Separate static asset
routes are deferred until the full UI migration needs code splitting or cacheable chunks.

## Commands

```bash
bun run --cwd apps/debug-frontend dev
bun run --cwd apps/debug-frontend build
bun run --cwd apps/debug-frontend check
bun run --cwd apps/debug-frontend test:browser
```

Or from the repo root:

```bash
bun run dev:debug-frontend
bun run build:debug-frontend
bun run check:debug-frontend
```
23 changes: 23 additions & 0 deletions apps/frontend/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en" class="theme-neutral">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Plannotator</title>
<script>
// Apply saved theme before React mounts to prevent flash of unstyled content.
// ThemeProvider will take over once mounted.
try {
const ct = document.cookie.match(/(?:^|; )plannotator-color-theme=([^;]*)/);
const theme = ct ? decodeURIComponent(ct[1]) : 'neutral';
const mt = document.cookie.match(/(?:^|; )plannotator-theme=([^;]*)/);
const mode = mt ? decodeURIComponent(mt[1]) : 'dark';
document.documentElement.className = 'theme-' + theme + (mode === 'light' ? ' light' : '');
} catch(e) {}
</script>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
62 changes: 62 additions & 0 deletions apps/frontend/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
{
"name": "@plannotator/frontend",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build && bun run scripts/verify-single-file-build.ts",
"typecheck": "tsc --noEmit -p tsconfig.json",
"lint": "oxlint .",
"lint:fix": "oxlint . --fix",
"fmt": "oxfmt --ignore-path .oxfmtignore --write .",
"fmt:check": "oxfmt --ignore-path .oxfmtignore --check .",
"test": "vitest run --passWithNoTests",
"check": "bun run typecheck && bun run lint && bun run fmt:check && bun run test"
},
"dependencies": {
"@fontsource-variable/geist-mono": "^5.2.7",
"@fontsource-variable/instrument-sans": "^5.2.8",
"@fontsource-variable/inter": "^5.2.8",
"@plannotator/code-review": "workspace:*",
"@plannotator/plan-review": "workspace:*",
"@plannotator/shared": "workspace:*",
"@plannotator/ui": "workspace:*",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-context-menu": "^2.2.16",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.8",
"@radix-ui/react-separator": "^1.1.8",
"@radix-ui/react-slot": "^1.2.4",
"@radix-ui/react-tabs": "^1.1.13",
"@radix-ui/react-tooltip": "^1.2.8",
"@tanstack/react-router": "^1.141.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"immer": "^10.2.0",
"lucide-react": "^1.14.0",
"react": "^19.2.3",
"react-dom": "^19.2.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.6.0",
"tailwindcss-animate": "^1.0.7",
"vaul": "^1.1.2",
"zustand": "^5.0.13"
},
"devDependencies": {
"@tailwindcss/vite": "^4.1.18",
"@tanstack/router-plugin": "^1.141.0",
"@types/node": "^22.14.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.0",
"oxfmt": "^0.17.0",
"oxlint": "^1.31.0",
"tailwindcss": "^4.1.18",
"typescript": "~5.8.2",
"vite": "^6.2.0",
"vite-plugin-singlefile": "^2.0.3",
"vitest": "^4.0.16"
}
}
56 changes: 56 additions & 0 deletions apps/frontend/scripts/verify-single-file-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { existsSync, readdirSync, readFileSync } from "fs";
import { join, relative } from "path";

const distDir = join(import.meta.dirname, "..", "dist");
const indexPath = join(distDir, "index.html");

function listFiles(dir: string): string[] {
if (!existsSync(dir)) return [];

const files: string[] = [];
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const entryPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...listFiles(entryPath));
} else if (entry.isFile()) {
files.push(entryPath);
}
}
return files;
}

if (!existsSync(indexPath)) {
throw new Error("Expected apps/debug-frontend/dist/index.html to exist after build.");
}

const html = readFileSync(indexPath, "utf-8");

const outputFiles = listFiles(distDir)
.map((file) => relative(distDir, file))
.sort();
const extraFiles = outputFiles.filter((file) => file !== "index.html");

if (extraFiles.length > 0) {
throw new Error(
`Frontend daemon shell build must be single-file; found outputs: ${extraFiles.join(", ")}`,
);
}

const htmlWithoutInlineCode = html
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, "<script></script>")
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, "<style></style>");

const externalScriptPattern = /<script\b[^>]*\bsrc=["'][^"']+["']/i;
const externalLinkPatterns = [
/<link\b[^>]*\brel=["'](?:stylesheet|modulepreload|preload)["'][^>]*\bhref=["'][^"']+["']/i,
/<link\b[^>]*\bhref=["'][^"']+["'][^>]*\brel=["'](?:stylesheet|modulepreload|preload)["']/i,
];

if (
externalScriptPattern.test(html) ||
externalLinkPatterns.some((pattern) => pattern.test(htmlWithoutInlineCode))
) {
throw new Error("Frontend daemon shell build must inline scripts and styles.");
}

console.log("Verified single-file frontend shell build.");
117 changes: 117 additions & 0 deletions apps/frontend/src/app/Layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { useCallback, useEffect } from "react";
import { Outlet, useMatchRoute } from "@tanstack/react-router";
import { Toaster } from "sonner";
import { SidebarProvider, useSidebar } from "@/components/ui/sidebar";
import { TooltipProvider } from "@/components/ui/tooltip";
import { AppSidebar } from "../components/sidebar/AppSidebar";
import { SidebarPeek } from "../components/sidebar/SidebarPeek";
import { AddProjectDialog } from "../components/landing/AddProjectDialog";
import { AppSettingsDialog } from "../components/settings/AppSettingsDialog";
import { SessionSurface } from "../components/sessions/SessionSurface";
import { appStore } from "../stores/app-store";
import { setGlobalFetchBase } from "@plannotator/ui/utils/api";
import { useDaemonEvents } from "../daemon/events/use-daemon-events";

setGlobalFetchBase("/daemon");
import { projectStore } from "../stores/project-store";
import { useAppStore } from "../stores/app-store";

function LayoutContent() {
const addProjectOpen = useAppStore((s) => s.addProjectOpen);
const setAddProjectOpen = useAppStore((s) => s.setAddProjectOpen);
const activeSessionId = useAppStore((s) => s.activeSessionId);
const visitedSessions = useAppStore((s) => s.visitedSessions);
const matchRoute = useMatchRoute();
const { open: sidebarOpen } = useSidebar();

const { reportActiveSession } = useDaemonEvents();

useEffect(() => {
void projectStore.getState().fetchProjects();
}, []);

const isOnSession = !!matchRoute({ to: "/s/$sessionId", fuzzy: true });

useEffect(() => {
reportActiveSession(isOnSession ? activeSessionId : null);
}, [reportActiveSession, isOnSession, activeSessionId]);
const showLanding = !isOnSession;

useEffect(() => {
const handler = (e: KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === ",") {
e.preventDefault();
const current = appStore.getState().settingsOpen;
appStore.getState().setSettingsOpen(!current);
}
};
window.addEventListener("keydown", handler);
return () => window.removeEventListener("keydown", handler);
}, []);

return (
<>
<AppSidebar />
<SidebarPeek />
<main className="relative flex-1 overflow-hidden">
<div
className="absolute inset-0"
style={{
visibility: showLanding ? "visible" : "hidden",
zIndex: showLanding ? 1 : 0,
}}
>
<Outlet />
</div>

{Object.values(visitedSessions).map(({ sessionId, bootstrap }) => {
const isActive = sessionId === activeSessionId && isOnSession;
return (
<div
key={sessionId}
className={`absolute inset-0 overflow-hidden ${sidebarOpen ? "rounded-tl-xl border-l border-border/50" : ""}`}
style={{
visibility: isActive ? "visible" : "hidden",
contentVisibility: isActive ? "visible" : "hidden",
containIntrinsicSize: isActive ? undefined : "auto 100vh",
zIndex: isActive ? 1 : 0,
}}
>
<SessionSurface bootstrap={bootstrap} />
</div>
);
})}
</main>
<AddProjectDialog open={addProjectOpen} onOpenChange={setAddProjectOpen} />
<AppSettingsDialog />
<Toaster
position="bottom-right"
toastOptions={{
style: {
"--normal-bg": "var(--card)",
"--normal-border": "var(--border)",
"--normal-text": "var(--foreground)",
"--normal-action-bg": "var(--primary)",
"--normal-action-text": "var(--primary-foreground)",
} as React.CSSProperties,
}}
/>
</>
);
}

export function Layout() {
const matchRoute = useMatchRoute();
const initiallyOnSession = !!matchRoute({ to: "/s/$sessionId", fuzzy: true });

return (
<TooltipProvider delayDuration={200} skipDelayDuration={100}>
<SidebarProvider
defaultOpen={!initiallyOnSession}
style={{ "--sidebar-width": "16rem" } as React.CSSProperties}
>
<LayoutContent />
</SidebarProvider>
</TooltipProvider>
);
}
25 changes: 25 additions & 0 deletions apps/frontend/src/app/router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { createRouter } from "@tanstack/react-router";
import { createDaemonApiClient, type DaemonApiClient } from "../daemon/api/client";
import { routeTree } from "../routeTree.gen";

export interface AppRouterContext {
daemonClient: DaemonApiClient;
}

export function createAppRouter(
context: AppRouterContext = { daemonClient: createDaemonApiClient() },
) {
return createRouter({
routeTree,
context,
defaultPreload: "intent",
defaultPendingMs: 0,
defaultPendingMinMs: 0,
});
}

declare module "@tanstack/react-router" {
interface Register {
router: ReturnType<typeof createAppRouter>;
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading