diff --git a/apps/desktop/e2e/app.spec.ts b/apps/desktop/e2e/app.spec.ts index 7f3f01e1..97667fc9 100644 --- a/apps/desktop/e2e/app.spec.ts +++ b/apps/desktop/e2e/app.spec.ts @@ -395,17 +395,17 @@ test("primitives: the model Menu is keyboard-driven, and icon buttons are named, await expect(more).toHaveAccessibleName("Project actions"); // Row actions are hidden until hover, but a keyboard user reaching one sees it, with its tooltip and shortcut. await expect(more).toHaveCSS("opacity", "0"); - await newThread.focus(); - await page.keyboard.press("Tab"); // → worktree + // The row's actions run worktree chat, ⋯, new chat. + await tid(project, "project-new-worktree-thread").focus(); await page.keyboard.press("Tab"); // → ⋯ await expect(more).toBeFocused(); await expect(more).toHaveCSS("opacity", "1"); const tip = page.getByRole("tooltip", { name: "Project actions" }); await expect(tip).toHaveText("Project actions"); await expect(more).toHaveAttribute("aria-describedby", (await tip.getAttribute("id"))!); - // The ⋯ opens a Menu: focus lands on its first item (Open notes), Escape hands focus back. + // The ⋯ opens a Menu: focus lands on its first item (reveal the folder), Escape hands focus back. await page.keyboard.press("Enter"); - await expect(tid(project, "project-notes")).toBeFocused(); + await expect(tid(project, "project-reveal")).toBeFocused(); await expect(tid(project, "project-remove")).toHaveRole("menuitem"); await page.keyboard.press("Escape"); await expect(tid(project, "project-remove")).toHaveCount(0); diff --git a/apps/desktop/e2e/browser.spec.ts b/apps/desktop/e2e/browser.spec.ts index 8e6ee0a0..8e0e6f64 100644 --- a/apps/desktop/e2e/browser.spec.ts +++ b/apps/desktop/e2e/browser.spec.ts @@ -34,8 +34,15 @@ test("browser without preload: add folder, approve a turn, inspect changes, term await page.setViewportSize({ width: 1400, height: 1000 }); await tid(page, "empty-open-project").focus(); await expect(tid(page, "empty-open-project")).toBeFocused(); - page.once("dialog", (dialog) => dialog.accept(repo)); + // A project is made in the Create project dialog; a browser tab has no folder picker, so the path is typed. await page.keyboard.press("Enter"); + await expect(tid(page, "create-project")).toBeVisible(); + await expect(tid(page, "create-project-submit")).toBeDisabled(); + await tid(page, "create-project-path").fill(repo); + await page.keyboard.press("Enter"); + await expect(tid(page, "create-project-folder")).toContainText(path.basename(repo)); + await tid(page, "create-project-submit").click(); + await expect(tid(page, "create-project")).toHaveCount(0); await expect(tid(page, "draft-view")).toBeVisible(); await expect(tid(page, "model-picker")).toContainText("Scripted mock"); await tid(page, "composer-input").fill("Add a contributing guide"); diff --git a/apps/desktop/e2e/routines.spec.ts b/apps/desktop/e2e/routines.spec.ts index cdeb8bef..3d5cf2a6 100644 --- a/apps/desktop/e2e/routines.spec.ts +++ b/apps/desktop/e2e/routines.spec.ts @@ -23,6 +23,17 @@ async function openRoutines(page: Page) { await expect(tid(page, "routines-view")).toBeVisible(); } +/** Selects the first task and shows its details and runs. A task that has run opens as its conversation first. */ +async function openTaskDetails(page: Page) { + await tid(page, "routine-row").first().click(); + await expect(tid(page, "routine-detail").or(tid(page, "sched-chat-title"))).toBeVisible(); + if (await tid(page, "sched-chat-title").count()) { + await tid(page, "sched-chat-title").click(); + await tid(page, "sched-details").click(); + } + await expect(tid(page, "routine-detail")).toBeVisible(); +} + test("with the window closed, a routine still runs, and reopening shows it in Activity", async () => { test.skip(process.platform !== "darwin", "macOS keeps Modex running after its last window closes"); const { home } = seedHome(); @@ -42,6 +53,7 @@ test("with the window closed, a routine still runs, and reopening shows it in Ac page = await nextWindow; await waitForWindowReady(app, page); await openRoutines(page); + await openTaskDetails(page); const row = tid(page, "activity-row"); await expect(row).toHaveCount(1); await expect(row).toHaveAttribute("data-status", "completed"); @@ -80,6 +92,7 @@ test("killing Modex mid-run leaves the run interrupted on restart, with no page fs.writeFileSync(path.join(home, "app", "state.json"), JSON.stringify(restarted)); ({ app, page } = await launch(home)); await openRoutines(page); + await openTaskDetails(page); const interrupted = tid(page, "activity-row"); await expect(interrupted).toHaveCount(1, { timeout: 10_000 }); await expect(interrupted).toHaveAttribute("data-status", "interrupted"); @@ -93,7 +106,7 @@ test("killing Modex mid-run leaves the run interrupted on restart, with no page await expect(tid(page, "activity-row")).toHaveCount(2); }); -test("a routine made in the editor runs read-only: its edit is refused with a receipt and the checkout is untouched", async () => { +test("a task made from a message runs read-only: its edit is refused with a receipt and the checkout is untouched", async () => { const { home, repo } = seedHome(); const state = JSON.parse(fs.readFileSync(path.join(home, "app", "state.json"), "utf8")); state.settings.mock_script = script(home, "edit", [ @@ -104,21 +117,39 @@ test("a routine made in the editor runs read-only: its edit is refused with a re let page: Page; ({ app, page } = await launch(home)); await openRoutines(page); + // A task is made by describing it in a message, never in a form: the schedule is read from the message. await tid(page, "routine-new").click(); - await tid(page, "routine-name").fill("Weekly summary"); - await tid(page, "routine-instructions").fill("Write a short summary of the week."); - await tid(page, "routine-mode-plan").check(); - await tid(page, "routine-save").click(); + await expect(tid(page, "routine-name")).toHaveCount(0); + await tid(page, "sched-compose-text").fill("Every week, write a short summary of the week."); + await expect(tid(page, "sched-reading")).toContainText("s at 8:00 AM · first run now"); + await tid(page, "sched-compose-send").click(); const row = tid(page, "routine-row"); - await expect(row).toContainText("Weekly summary"); - await expect(row).toContainText("Plan (read-only)"); - await expect(tid(row, "routine-next")).toContainText("Next run"); + await expect(row).toContainText("Write a short summary of the week"); - await tid(row, "routine-run-now").click(); + // Its first run starts at once and opens as the task's conversation; the runs are one menu away. + await expect(tid(page, "sched-chat-title")).toContainText("Write a short summary of the week", { timeout: 30_000 }); + await tid(page, "sched-chat-title").click(); + await tid(page, "sched-details").click(); + await expect(tid(page, "routine-detail")).toContainText("Chat (read-only)"); const activity = tid(page, "activity-row").first(); await expect(activity).toHaveAttribute("data-status", "completed", { timeout: 30_000 }); await expect(activity).toContainText("Run now"); - await expect(tid(activity, "activity-page")).toHaveText("Weekly summary · revision 1"); + await expect(tid(activity, "activity-page")).toHaveText("Write a short summary of the week · revision 1"); + await expect(tid(page, "routine-next")).toContainText("Next run"); + + // What the run wrote opens beside its conversation, from the outputs list; the row's menu holds its actions. + await tid(page, "routine-row").first().click(); + await tid(page, "sched-info").click(); + await tid(page, "sched-output-open").click(); + await expect(tid(page, "sched-output-page")).toContainText("I could not edit files, so here is the summary instead."); + await page.getByRole("button", { name: "Close output" }).click(); + await expect(tid(page, "sched-output")).toHaveCount(0); + await tid(page, "routine-row").first().hover(); + await tid(page, "routine-row-menu").first().click(); + await expect(page.getByRole("menuitem", { name: "Pause" })).toBeVisible(); + await page.keyboard.press("Escape"); + await tid(page, "sched-chat-title").click(); + await tid(page, "sched-details").click(); await tid(activity, "activity-thread").click(); // A finished turn folds its work; the refused approval is part of it. await tid(page, "turn-label").last().click(); diff --git a/apps/desktop/e2e/task-to-notes.spec.ts b/apps/desktop/e2e/task-to-notes.spec.ts index fc6b4c83..780b8a43 100644 --- a/apps/desktop/e2e/task-to-notes.spec.ts +++ b/apps/desktop/e2e/task-to-notes.spec.ts @@ -64,7 +64,7 @@ test("Save to Notes writes the turn's record into the project's notes, and savin expect(saved[0]!.markdown).toContain("Fixed the import."); expect(saved[0]!.markdown).toContain(`From modex thread ${threadId}.`); expect(saved[0]!.markdown).not.toContain(repo); - await expect(save).toHaveText("Update note"); + await expect(save).toHaveAccessibleName("Update note"); await save.click(); await expect(tid(page, "task-note-saved").first()).toContainText("Updated in Notes · Task:"); expect((await pages()).filter((p) => p.title.startsWith("Task:"))).toHaveLength(1); diff --git a/apps/desktop/e2e/workspace.spec.ts b/apps/desktop/e2e/workspace.spec.ts index 1b7e13f5..9f479e80 100644 --- a/apps/desktop/e2e/workspace.spec.ts +++ b/apps/desktop/e2e/workspace.spec.ts @@ -92,8 +92,15 @@ test("new-tab menu, launcher, full view and Files replace the old panel", async await tid(page, "workspace-full").click(); await expect(tid(page, "main")).toBeHidden(); await page.getByRole("button", { name: "Files ⌘P", exact: true }).click(); - await page.getByRole("button", { name: "Open README.md", exact: true }).click(); + await page.getByRole("treeitem", { name: "Open README.md", exact: true }).click(); + // Markdown opens rendered; View source shows the file's own text. The crumb opens the folder tree. + await expect(tid(page, "workspace-file-content").getByRole("heading", { name: "e2e" })).toBeVisible(); + await tid(page, "file-view-source").click(); await expect(tid(page, "workspace-file-content")).toContainText("# e2e"); + await page.getByRole("navigation", { name: "File path" }).getByRole("button").first().click(); + await expect(tid(page, "file-crumb-pop").getByRole("treeitem", { name: "Open README.md" })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(tid(page, "file-crumb-pop")).toHaveCount(0); await tid(page, "workspace-full").click(); await expect(tid(page, "main")).toBeVisible(); await page.keyboard.press("Meta+Shift+f"); diff --git a/apps/desktop/src/main/browser-dev.ts b/apps/desktop/src/main/browser-dev.ts index e18faec0..76cc1107 100644 --- a/apps/desktop/src/main/browser-dev.ts +++ b/apps/desktop/src/main/browser-dev.ts @@ -14,6 +14,7 @@ import { hydratePath } from "./engine/shell-env.js"; import { LIMITS } from "../shared/attachments.js"; import { revealAttachment } from "./reveal-attachment.js"; import { openTerminal } from "./engine/open-terminal.js"; +import { RoutinePages, RoutineScheduler, validateRoutine } from "./engine/routines.js"; /** Local development transport only; never included in the packaged renderer. */ export function createBrowserDev(home: string) { @@ -42,6 +43,22 @@ export function createBrowserDev(home: string) { return store.thread(id)!.cwd; }, (event) => broadcast("terminal", event), undefined, process.env, process.env.MODEX_E2E ? { file: "/bin/bash", args: ["--noprofile", "--norc"] } : undefined); + // Scheduled tasks in browser development: they can be made, edited and run by hand. The timer is never + // started here, so nothing runs unattended from a dev server. + const routines = new RoutineScheduler(home, { + project: (id) => store.project(id), + createThread: async (projectId, routine) => { await pathReady; return runner.createRoutineThread(projectId, routine); }, + sendUnattended: (id, text) => runner.sendUnattended(id, text), + stop: (id) => runner.stop(id), + items: (id) => runner.items(id), + status: (id) => runner.status(id), + addNotice: (id, level, text) => runner.addNotice(id, level, text), + pages: new RoutinePages(store.space), + }); + handlers.set("routines:list", (() => routines.list()) as (payload: never) => unknown); + handlers.set("routines:save", ((draft: unknown) => routines.save(validateRoutine(draft, (id) => Boolean(store.project(id))))) as (payload: never) => unknown); + handlers.set("routines:delete", (({ id }: { id: string }) => routines.remove(id)) as (payload: never) => unknown); + handlers.set("routines:run", (({ id }: { id: string }) => routines.runNow(id)) as (payload: never) => unknown); registerCommands((channel, handler) => handlers.set(channel, handler as (payload: never) => unknown), { store, runner, terminals, emit, pickDirectory: async () => { throw new Error("Enter the local project folder's absolute path."); }, @@ -171,6 +188,7 @@ export function createBrowserDev(home: string) { for (const upload of uploads) upload.destroy(); for (const client of clients) client.end(); clients.clear(); + try { routines.dispose(); } catch { /* Nothing was scheduled. */ } const results = await Promise.allSettled([terminals.dispose(), runner.dispose()]); const failure = results.find((result) => result.status === "rejected"); if (failure?.status === "rejected") throw failure.reason; diff --git a/apps/desktop/src/main/commands.ts b/apps/desktop/src/main/commands.ts index bbc5c9c9..7b00f26b 100644 --- a/apps/desktop/src/main/commands.ts +++ b/apps/desktop/src/main/commands.ts @@ -90,8 +90,9 @@ export function registerCommands(handle: RegisterCommand, { dir = await pickDirectory() ?? undefined; if (!dir) return null; } - return store.addProject(dir); + return store.addProject(dir, req?.name); }); + handle("project:pick-folder", async () => await pickDirectory() ?? null); handle("project:remove", async ({ projectId }) => { await runner.removeProject(projectId); return store.snapshot(); @@ -109,6 +110,7 @@ export function registerCommands(handle: RegisterCommand, { handle("thread:answer-question", ({ threadId, itemId, answers }) => runner.answerQuestion(threadId, itemId, answers)); handle("thread:update", ({ threadId, patch }) => runner.updateThread(threadId, patch)); handle("thread:archive", ({ threadId, archived }) => runner.setArchived(threadId, archived)); + handle("thread:vote", ({ threadId, itemId, vote }) => runner.setVote(threadId, itemId, vote)); handle("thread:delete", async ({ threadId, removeWorktree }) => { await runner.deleteThread(threadId, removeWorktree); return store.snapshot(); diff --git a/apps/desktop/src/main/engine/runner.ts b/apps/desktop/src/main/engine/runner.ts index f7ee6507..a8556d07 100644 --- a/apps/desktop/src/main/engine/runner.ts +++ b/apps/desktop/src/main/engine/runner.ts @@ -1281,6 +1281,16 @@ export class ThreadRunner { * phone; the transcript stays. A thread that is working cannot be archived, so nothing hidden ever * waits for an answer. */ + /** Records the person's rating of a reply with the thread. It is never sent to a CLI, a provider or any service. */ + setVote(threadId: string, itemId: string, vote: "up" | "down" | null): void { + if (vote !== "up" && vote !== "down" && vote !== null) throw new Error("Choose up, down or no rating."); + if (!this.o.store.thread(threadId)) throw new Error(`unknown thread ${threadId}`); + const item = this.slot(threadId).items.find((i) => i.id === itemId); + if (!item || item.kind !== "assistant") throw new Error("Only a reply can be rated."); + if ((item.vote ?? null) === vote) return; + this.patchItem(threadId, itemId, { vote }); + } + setArchived(threadId: string, archived: boolean): Thread { this.assertNotRestarting(); if (typeof archived !== "boolean") throw new Error("Choose Archive or Unarchive."); diff --git a/apps/desktop/src/main/engine/store.ts b/apps/desktop/src/main/engine/store.ts index 86ff0421..9fc4af3f 100644 --- a/apps/desktop/src/main/engine/store.ts +++ b/apps/desktop/src/main/engine/store.ts @@ -280,11 +280,11 @@ export class Store { return this.settings; } - addProject(dir: string): Project { + addProject(dir: string, name?: string): Project { const abs = path.resolve(dir); const existing = this.state.projects.find((p) => p.path === abs); if (existing) return existing; - const project: Project = { id: newId(), name: path.basename(abs), path: abs, addedAt: new Date().toISOString() }; + const project: Project = { id: newId(), name: (typeof name === "string" && name.trim().slice(0, 80)) || path.basename(abs), path: abs, addedAt: new Date().toISOString() }; this.state.projects.push(project); this.write(); // Notes never stand in the way of a project: a failure leaves it to be linked the next time notes open. diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.ts index 9cefbb0b..d699de22 100644 --- a/apps/desktop/src/main/index.ts +++ b/apps/desktop/src/main/index.ts @@ -803,7 +803,11 @@ handle("project:add", async (req) => { if (r.canceled || !r.filePaths[0]) return null; dir = r.filePaths[0]; } - return store.addProject(dir); + return store.addProject(dir, req?.name); +}); +handle("project:pick-folder", async () => { + const r = await dialog.showOpenDialog(win!, { properties: ["openDirectory", "createDirectory"], title: "Choose a project folder" }); + return r.canceled || !r.filePaths[0] ? null : r.filePaths[0]; }); handle("project:remove", async ({ projectId }) => { await runner.removeProject(projectId); @@ -857,6 +861,7 @@ handle("thread:answer", ({ threadId, itemId, answer }, event) => runner.answer(t handle("thread:answer-question", ({ threadId, itemId, answers }, event) => runner.answerQuestion(threadId, itemId, answers, answeredFrom(event))); handle("thread:update", ({ threadId, patch }, event) => runner.updateThread(threadId, patch, { by: answeredFrom(event) })); handle("thread:archive", ({ threadId, archived }) => runner.setArchived(threadId, archived)); +handle("thread:vote", ({ threadId, itemId, vote }) => runner.setVote(threadId, itemId, vote)); handle("thread:delete", async ({ threadId, removeWorktree }) => { await runner.deleteThread(threadId, removeWorktree); return store.snapshot(); diff --git a/apps/desktop/src/renderer/App.tsx b/apps/desktop/src/renderer/App.tsx index 04e4259c..fc132cb5 100644 --- a/apps/desktop/src/renderer/App.tsx +++ b/apps/desktop/src/renderer/App.tsx @@ -23,6 +23,7 @@ import { bridge } from "./bridge"; import { Sidebar } from "./components/Sidebar"; import { ThreadView } from "./components/ThreadView"; import { Workspace } from "./components/Workspace"; +import { subagentsOf } from "./components/SubagentsPanel"; import { SettingsDialog } from "./components/SettingsDialog"; import type { LocalMenu } from "./components/ModelMenu"; import { discoverAll, useLocalModels } from "./local-models"; @@ -30,6 +31,7 @@ import type { LocalModelRef } from "../shared/local-models"; import { CompanionDialog } from "./components/CompanionDialog"; import { EmptyState } from "./components/EmptyState"; import { DraftView, type Draft } from "./components/DraftView"; +import { CreateProjectDialog } from "./components/CreateProjectDialog"; import { TitleBar } from "./components/TitleBar"; import { Rail } from "./components/Rail"; import { AnalyticsView } from "./components/AnalyticsView"; @@ -50,6 +52,12 @@ const isTerminalToggle = (e: KeyboardEvent) => e.ctrlKey && !e.metaKey && !e.alt const TerminalPanel = lazy(() => import("./components/TerminalPanel").then((m) => ({ default: m.TerminalPanel }))); const ImagesView = lazy(() => import("./images/ImagesView").then(m => ({ default: m.ImagesView }))); const RoutinesView = lazy(() => import("./routines/RoutinesView").then(m => ({ default: m.RoutinesView }))); +const PluginsCatalog = lazy(() => import("./plugins/PluginsCatalog").then(m => ({ default: m.PluginsCatalog }))); +/** + * The browser versions: a tab on the development server (no bridge is injected), and the demo workspace at + * app.modex.codes. Neither has a plugin host, so Plugins is a preview with every action unavailable. + */ +const WEB = !window.modex || window.modex.platform === "demo"; const PluginSurface = lazy(() => import("./plugins/PluginSurface").then(m => ({ default: m.PluginSurface }))); const SpaceView = lazy(() => import("./space/SpaceView").then(m => ({ default: m.SpaceView }))); const CodeReviewView = lazy(() => import("./code-review/CodeReviewView")); @@ -197,6 +205,9 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE const changesRequest = useRef(0); // Which threads have their terminal panel showing. Hiding a panel leaves its shell running. const [terminals, setTerminals] = useState>({}); + const [subagentsSignal, setSubagentsSignal] = useState(0); + /** The thread of the scheduled task being read on the Scheduled page, shown there beside the task list. */ + const [scheduledThread, setScheduledThread] = useState(null); // A command line for a thread's shell (a failure card's sign-in fix); the panel types it once per nonce. const [terminalCommands, setTerminalCommands] = useState>({}); const commandNonce = useRef(0); @@ -216,8 +227,39 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE }, []); const knowledgeFocused = surface === "space" && knowledgeReady; const sidebarOpen = knowledgeFocused ? knowledgeSidebarOpen : layout.sidebar; + // On the web a hidden sidebar opens over the page while the pointer is on the rail, its toggle or the + // sidebar itself, and closes when the pointer leaves. Clicking the toggle keeps it open as usual. + const [sidebarPeek, setSidebarPeek] = useState(false); + const railQuiet = useRef(false); + // Heard on every page, peeking or not: the click that changes page is what must keep the sidebar away. + useEffect(() => { + if (!WEB) return; + const picked = (event: MouseEvent) => { if (event.target instanceof Element && event.target.closest(".rail")) { railQuiet.current = true; setSidebarPeek(false); } }; + document.addEventListener("click", picked, true); + return () => document.removeEventListener("click", picked, true); + }, []); + useEffect(() => { + // On Chat with the sidebar already showing there is nothing to peek; every other page hides it. + if (!WEB || (sidebarOpen && surface === "chat")) { setSidebarPeek(false); return; } + let timer: ReturnType | undefined; + const over = (event: PointerEvent) => { + if (event.pointerType !== "mouse") return; + const target = event.target instanceof Element ? event.target : null; + const inside = Boolean(target?.closest('.rail, [data-testid="sidebar-toggle"], .sidebar, .menu, .thread-details')); + // A click on the rail went somewhere: the sidebar stays away until the pointer has left the rail. + if (railQuiet.current && target && !target.closest('.rail, [role="tooltip"]')) railQuiet.current = false; + clearTimeout(timer); + if (inside && !railQuiet.current) setSidebarPeek(true); else if (!inside) timer = setTimeout(() => setSidebarPeek(false), 220); + }; + + const gone = () => { clearTimeout(timer); timer = setTimeout(() => setSidebarPeek(false), 220); }; + document.addEventListener("pointerover", over); + document.documentElement.addEventListener("pointerleave", gone); + return () => { clearTimeout(timer); document.removeEventListener("pointerover", over); document.documentElement.removeEventListener("pointerleave", gone); }; + }, [sidebarOpen, surface]); const streamerMode = layout.streamerMode; - const showAnalytics = analyticsEnabled && layout.analytics; + // The browser version has no Analytics page: its rail entry and the page itself are desktop only. + const showAnalytics = !WEB && analyticsEnabled && layout.analytics; // Hiding Analytics in Settings while it is open returns to Chat rather than leaving an unreachable surface. useEffect(() => { if (!showAnalytics && surface === "analytics") setSurface("chat"); }, [showAnalytics, surface]); const reviewEnabled = codeReviewEnabled && layout.codeReview; @@ -515,6 +557,12 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE setDraft(null); setSelected(id); }, []); + /** Shows a scheduled task's thread on the Scheduled page itself: the same transcript and composer as Chat. */ + const showScheduledThread = useCallback((id: string | null) => { + setScheduledThread(id); + if (!id || nativeHoldRef.current) return; + void (stateRef.current?.threads.some(t => t.id === id) ? Promise.resolve() : refresh()).then(() => { setDraft(null); setSelected(id); }).catch((err: Error) => setError({ message: err.message })); + }, []); /** Shows a thread in chat, refreshing first when this window has not heard of it yet. */ const openThread = (id: string) => { void (state?.threads.some(t => t.id === id) ? Promise.resolve() : refresh()).then(() => { selectThread(id); setSurface("chat"); }).catch((err: Error) => setError({ message: err.message })); }; const history = useSelectionHistory(selected, selectThread, (id) => Boolean(state?.threads.some((t) => t.id === id))); @@ -615,12 +663,14 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE return next; }); - const addProject = () => act(async () => { - const folder = bridge.platform === "web" ? window.prompt("Local project folder (absolute path)")?.trim() : undefined; - if (bridge.platform === "web" && !folder) return; - const p = await bridge.invoke("project:add", folder ? { path: folder } : undefined); + /** Projects are made in the Create project dialog: a name and the folder it works in. */ + const [creatingProject, setCreatingProject] = useState(false); + // The demo workspace has no folders on this computer: it adds its own sample project, with no dialog. + const addProject = () => { if (bridge.platform === "demo") void act(async () => { if (await bridge.invoke("project:add", undefined)) await refresh(); }); else setCreatingProject(true); }; + const createProject = async (folder: string, name: string) => { + const p = await bridge.invoke("project:add", { path: folder, ...(name ? { name } : {}) }); if (p) await refresh(); - }); + }; const resumeNativeSend = async (initial: PendingSendView): Promise => { const capability = nativeRef.current; if (!capability || pendingRuns.current.has(initial.id) || nativeHoldRef.current || nativeRecoveryError) return; @@ -974,6 +1024,8 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE const activeAgents = activeThreads.flatMap(t => (items[t.id] ?? []).flatMap(item => item.kind === "tool" && item.agent && (item.agent.state === "running" || item.agent.state === "waiting") ? [{ threadId: t.id, threadTitle: t.title, agent: item.agent }] : [])); + const scheduledChat = surface === "routines" && Boolean(scheduledThread) && thread?.id === scheduledThread; + const threadAgents = thread ? subagentsOf(items[thread.id] ?? []) : []; const activeWork = { count: activeThreads.length, agents: activeAgents.length, waiting: activeThreads.filter((candidate) => candidate.status === "waiting").length }; const openActiveWork = () => { const next = activeThreads[0]; @@ -1004,6 +1056,8 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE onToggleSidebar={() => setSidebarOpen((v) => !v)} showChanges={showChanges} onToggleChanges={() => setShowChanges((v) => !v)} + subagents={threadAgents.length ? { active: threadAgents.filter((item) => item.agent.state === "running" || item.agent.state === "waiting").length, total: threadAgents.length } : undefined} + onOpenSubagents={() => { setLayout({ changes: true }); setSubagentsSignal((n) => n + 1); }} showTerminal={Boolean(thread && showChanges && terminals[thread.id])} onToggleTerminal={() => thread && toggleTerminal(thread.id)} changedCount={changes?.files.length ?? 0} @@ -1013,8 +1067,9 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE onArchive={archiveThread} platform={bridge.platform} /> - setSurface("routines")} onOpenAnalytics={showAnalytics ? () => setSurface("analytics") : undefined} onOpenImages={mediaFeatures.images ? openImages : undefined} onOpenPlugins={mediaFeatures.plugins ? () => setSurface("plugins") : undefined} onOpenCodeReview={reviewEnabled ? () => { setReviewOpened(true); setSurface("code-review"); } : undefined} onOpenChat={() => setSurface("chat")} onOpenSpace={spaceEnabled ? () => { setSpaceOpened(true); setSurface("space"); } : undefined} activeWork={activeWork} onOpenActiveWork={openActiveWork} onOpenSettings={() => setShowSettings(true)} onOpenCompanion={() => setShowCompanion(true)} streamerMode={streamerMode} onEnableStreamerMode={() => setLayout({ streamerMode: !streamerMode })} /> -
+ setSurface("routines")} onOpenAnalytics={showAnalytics ? () => setSurface("analytics") : undefined} onOpenImages={mediaFeatures.images ? openImages : undefined} onOpenPlugins={mediaFeatures.plugins || WEB ? () => setSurface("plugins") : undefined} onOpenCodeReview={reviewEnabled ? () => { setReviewOpened(true); setSurface("code-review"); } : undefined} onOpenChat={() => setSurface("chat")} onOpenSpace={spaceEnabled ? () => { setSpaceOpened(true); setSurface("space"); } : undefined} activeWork={activeWork} onOpenActiveWork={openActiveWork} onOpenSettings={() => setShowSettings(true)} onOpenCompanion={() => setShowCompanion(true)} streamerMode={streamerMode} onEnableStreamerMode={() => setLayout({ streamerMode: !streamerMode })} /> + {creatingProject && setCreatingProject(false)} />} +
{(surface === "chat" || surface === "space" || surface === "code-review") && sidebarOpen && setLayout({ sidebarWidth })} onReset={() => setLayout({ sidebarWidth: panels.sidebarDefault })} />} {surface === "chat" && thread && showChanges && } - {surface === "plugins" && Opening Plugins…
}>} - {surface === "routines" && Opening Routines…
}>Opening Plugins…}>{mediaFeatures.plugins ? : }} + {surface === "routines" && Opening Scheduled…}> { setOpenPage({ id }); setSpaceOpened(true); setSurface("space"); } : undefined} />} {spaceOpened && Opening Space… : null}>} - {sidebarOpen && ( + {(sidebarOpen || sidebarPeek) && ( )} -
+
+ {scheduledChat &&
} {surface === "space" && spaceChatOpen &&
{ setSpaceChatOpen(false); requestAnimationFrame(() => document.querySelector(".space-chat-launcher input")?.focus()); }} />{thread?.title ?? "New chat"} setSurface("chat")} />
} {surface === "chat" && } {pendingSends.map(record =>
@@ -1116,6 +1172,7 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE ) : null}
{thread && loadChanges(thread.id)} onRevert={revert} + items={items[thread.id] ?? []} subagentsSignal={subagentsSignal} visible={surface === "chat" && showChanges} onShow={() => setLayout({ changes: true })} onHide={() => setLayout({ changes: false })} suspended={suspended || surface !== "chat" || showSettings || showCompanion} onOpenTerminal={() => { setLayout({ changes: true }); setTerminals((m) => ({ ...m, [thread.id]: true })); }} @@ -1138,7 +1195,7 @@ export function App({ persistPreferences = true, spaceEnabled = true, analyticsE )} - {showSettings && { setShowSettings(false); setSettingsSection(undefined); }} initialSection={settingsSection} {...(analyticsEnabled ? { analyticsInRail: layout.analytics, onAnalyticsInRail: (shown: boolean) => setLayout({ analytics: shown }) } : {})} {...(codeReviewEnabled ? { codeReviewInRail: layout.codeReview, onCodeReviewInRail: (codeReview: boolean) => setLayout({ codeReview }) } : {})} />} + {showSettings && { setShowSettings(false); setSettingsSection(undefined); }} initialSection={settingsSection} {...(analyticsEnabled && !WEB ? { analyticsInRail: layout.analytics, onAnalyticsInRail: (shown: boolean) => setLayout({ analytics: shown }) } : {})} {...(codeReviewEnabled ? { codeReviewInRail: layout.codeReview, onCodeReviewInRail: (codeReview: boolean) => setLayout({ codeReview }) } : {})} />} {showCompanion && setShowCompanion(false)} />} ) : {error?.message ?? "Loading…"}; diff --git a/apps/desktop/src/renderer/browser-bridge.ts b/apps/desktop/src/renderer/browser-bridge.ts index 85d649a7..82863858 100644 --- a/apps/desktop/src/renderer/browser-bridge.ts +++ b/apps/desktop/src/renderer/browser-bridge.ts @@ -3,6 +3,17 @@ import { IMAGE_TYPES, LIMITS } from "../shared/attachments"; import type { BridgeCommands, ModexBridge, ThreadEvent, TerminalEvent } from "../shared/types"; /** Same-origin dev transport. The Electron preload continues to take precedence. */ +/** True when the page is being reloaded for a stale token. At most once a minute, so a real refusal still shows. */ +function staleTokenReload(): boolean { + try { + const last = Number(sessionStorage.getItem("modex.bridge.reloaded") ?? 0); + if (Date.now() - last < 60_000) return false; + sessionStorage.setItem("modex.bridge.reloaded", String(Date.now())); + } catch { return false; } + location.reload(); + return true; +} + export function createBrowserBridge(): ModexBridge { const token = document.querySelector('meta[name="modex-browser-token"]')?.content ?? ""; const threads = new Set<(event: ThreadEvent) => void>(); @@ -63,6 +74,8 @@ export function createBrowserBridge(): ModexBridge { body: JSON.stringify(staging ? payload : { channel, payload }), }); const result = await response.json(); + // The dev server was restarted: this page holds the old server's token. Load the page again, once. + if (!response.ok && result.error === "Untrusted browser bridge request." && staleTokenReload()) return new Promise(() => {}); if (!response.ok) throw new Error(result.error ?? `Browser bridge failed (${response.status}).`); return result.value; }, diff --git a/apps/desktop/src/renderer/components/Composer.tsx b/apps/desktop/src/renderer/components/Composer.tsx index e31f1077..8fc854ee 100644 --- a/apps/desktop/src/renderer/components/Composer.tsx +++ b/apps/desktop/src/renderer/components/Composer.tsx @@ -153,7 +153,7 @@ export function Composer({ text, onText: setText, attachments, attachmentActions {canSuggest && ( )} ; onClose(): void }) { + const web = bridge.platform === "web"; + const [name, setName] = useState(""); + const [folder, setFolder] = useState(""); + const [typed, setTyped] = useState(""); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const nameRef = useRef(null); + useEffect(() => { nameRef.current?.focus(); }, []); + useEffect(() => { + const key = (event: KeyboardEvent) => { if (event.key === "Escape") { event.stopPropagation(); onClose(); } }; + document.addEventListener("keydown", key, true); + return () => document.removeEventListener("keydown", key, true); + }, [onClose]); + const base = (path: string) => path.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || path; + const pick = async () => { + setError(null); + try { const path = await bridge.invoke("project:pick-folder", undefined); if (path) setFolder(path); } + catch (failure) { setError((failure as Error).message); } + }; + const create = async () => { + if (!folder || busy) return; + setBusy(true); setError(null); + try { await onCreate(folder, name.trim()); onClose(); } + catch (failure) { setError((failure as Error).message); setBusy(false); } + }; + return ( +
{ if (event.target === event.currentTarget) onClose(); }}> +
{ event.preventDefault(); void create(); }}> + +

Create project

+ +
Source folders{folder && This computer}
+
+ {folder ? ( +
{base(folder)}
+ ) : ( +
+

Add a folder on this computer

+ {web ? ( + setTyped(event.target.value)} onKeyDown={(event) => { if (event.key === "Enter" && typed.trim()) { event.preventDefault(); setFolder(typed.trim()); } }} /> + + ) : } +
+ )} +
+ {error &&

{error}

} +
+ + +
+
+
+ ); +} diff --git a/apps/desktop/src/renderer/components/Rail.tsx b/apps/desktop/src/renderer/components/Rail.tsx index ac3dc9a4..2154f400 100644 --- a/apps/desktop/src/renderer/components/Rail.tsx +++ b/apps/desktop/src/renderer/components/Rail.tsx @@ -19,13 +19,13 @@ export function Rail({ surface = "chat", onOpenChat, onOpenSpace, onOpenAnalytic const workLabel = activeWork && activeWork.count > 0 ? activeWorkLabel(activeWork) : ""; return (