Skip to content
Open
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
30 changes: 29 additions & 1 deletion apps/nova-desktop/service/folders.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ test("native grants confine reads, writes and directory enumeration", async () =
await grants.write(grant.id, "nested/new.txt", "new file")
expect(await readFile(join(project, "nested/new.txt"), "utf8")).toBe("new file")
await expect(grants.write(grant.id, "/absolute.txt", "forbidden")).rejects.toThrow()
grants.clear()
await grants.clear()
await expect(grants.read(grant.id, "hello.txt")).rejects.toThrow()
})
test("symlinks do not expand a native directory grant", async () => {
Expand All @@ -33,3 +33,31 @@ test("symlinks do not expand a native directory grant", async () => {
await expect(grants.read(grant.id, "link")).rejects.toThrow("Symlinks")
expect(await grants.list(grant.id, "")).toEqual([{ name: "hello.txt", kind: "file" }])
})

test("picker grants survive service restarts and sign-out revokes them on disk", async () => {
const { root, project } = await setup()
const storage = join(root, "state", "grants.json")
const first = new FolderGrants(storage)
await first.restore()
const grant = await first.grant(project)
const restarted = new FolderGrants(storage)
await restarted.restore()
expect(await (await restarted.read(grant.id, "hello.txt")).text()).toBe("hello")
expect((await restarted.grant(project)).id).toBe(grant.id)
await restarted.clear()
const signedOut = new FolderGrants(storage)
await signedOut.restore()
await expect(signedOut.read(grant.id, "hello.txt")).rejects.toThrow()
})

test("restoring grants rejects a root replaced with a symlink", async () => {
const { root, project } = await setup()
const storage = join(root, "grants.json")
const first = new FolderGrants(storage)
const grant = await first.grant(project)
await rm(project, { recursive: true })
await symlink(root, project)
const restarted = new FolderGrants(storage)
await restarted.restore()
await expect(restarted.list(grant.id, "")).rejects.toThrow()
})
34 changes: 31 additions & 3 deletions apps/nova-desktop/service/folders.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,48 @@
import { randomUUID } from "node:crypto"
import { lstat, readdir, realpath, readFile, writeFile, mkdir } from "node:fs/promises"
import { basename, isAbsolute, join, relative, sep } from "node:path"
import { lstat, readdir, realpath, readFile, writeFile, mkdir, rename } from "node:fs/promises"
import { basename, dirname, isAbsolute, join, relative, sep } from "node:path"
import { z } from "zod"

const savedGrantsSchema = z.array(z.tuple([z.string().uuid(), z.string().min(1)]))

/** Grants originate exclusively from the native picker, never from a remote path. */
export class FolderGrants {
private roots = new Map<string, string>()
constructor(private storagePath?: string) {}
async restore() {
if (!this.storagePath) return
try {
const saved = savedGrantsSchema.parse(JSON.parse(await readFile(this.storagePath, "utf8")))
for (const [id, root] of saved) {
try {
const stat = await lstat(root)
if (isAbsolute(root) && stat.isDirectory() && !stat.isSymbolicLink() && await realpath(root) === root) this.roots.set(id, root)
} catch {
// A removed or moved folder must be selected again.
}
}
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error
}
}
private async persist() {
if (!this.storagePath) return
await mkdir(dirname(this.storagePath), { recursive: true, mode: 0o700 })
const temporary = `${this.storagePath}.${randomUUID()}.tmp`
await writeFile(temporary, JSON.stringify([...this.roots]), { mode: 0o600 })
await rename(temporary, this.storagePath)
}
async grant(path: string) {
if (!isAbsolute(path) || !(await lstat(path)).isDirectory() || (await lstat(path)).isSymbolicLink()) throw new Error("Choose a directory")
const root = await realpath(path)
const existing = [...this.roots].find(([, value]) => value === root)
const id = existing?.[0] ?? randomUUID()
this.roots.set(id, root)
await this.persist()
return { id, name: basename(root), root }
}
paths() { return [...this.roots.values()] }
clear() { this.roots.clear() }
async clear() { this.roots.clear(); await this.persist() }
private async resolve(id: string, path: string) {
const root = this.roots.get(id)
if (!root || typeof path !== "string" || path.length > 4096 || path.includes("\\") || path.includes("\0") || isAbsolute(path) || path.split("/").some(p => p === ".." || p === ".")) throw new Error("Invalid folder path")
Expand Down
7 changes: 4 additions & 3 deletions apps/nova-desktop/service/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,11 @@ lines.once("line", async line => {
const input = bootstrap.parse(JSON.parse(line))
const origin = `http://127.0.0.1:${input.port}`
const desktopComputer = new DesktopComputerAgent()
const folders = new FolderGrants()
const folders = new FolderGrants(resolve(homedir(), ".nova/desktop-folder-grants.json"))
await folders.restore()
const cursorLogin = createCursorLogin()
let localCodex: Awaited<ReturnType<typeof startCompanion>> | null = null
let engine = new NovaWorkspaceGit({ roots: [] })
let engine = new NovaWorkspaceGit({ roots: folders.paths() })
const localAgents = createDesktopAgentTurns(async id => {
if (id) return (await engine.get(id)).path
const workspace = resolve(homedir(), ".nova/local-agent-workspace")
Expand All @@ -56,7 +57,7 @@ lines.once("line", async line => {
onHarnessToken: token => desktopAuth.restore(token ? { access_token: token, expiresAt: null, source: "cli" } : null),
auth: {
status: () => desktopAuth.status(),
signOut: async () => { cursorLogin.close(); localAgents.close(); await desktopComputer.disconnect(); await localCodex?.close(); localCodex = null; folders.clear(); engine = new NovaWorkspaceGit({ roots: [] }); desktopAuth.restore(null); return { signedOut: true } },
signOut: async () => { cursorLogin.close(); localAgents.close(); await desktopComputer.disconnect(); await localCodex?.close(); localCodex = null; await folders.clear(); engine = new NovaWorkspaceGit({ roots: [] }); desktopAuth.restore(null); return { signedOut: true } },
}, folders,
startLocalCodex: async path => {
await localCodex?.close(); localCodex = null
Expand Down
1 change: 1 addition & 0 deletions apps/nova-desktop/src-tauri/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
]
},
"permissions": [
"core:window:allow-start-dragging",
"allow-choose-folder",
"allow-open-external",
"allow-capture-screen",
Expand Down
2 changes: 2 additions & 0 deletions apps/nova-desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -495,6 +495,8 @@ fn main() {
app.set_menu(menu)?;
tauri::WebviewWindowBuilder::new(app, "main", WebviewUrl::External(url))
.title("Nova")
.title_bar_style(tauri::TitleBarStyle::Overlay)
.hidden_title(true)
.inner_size(1440.0, 960.0)
.min_inner_size(900.0, 600.0)
.on_navigation(|url| {
Expand Down
40 changes: 40 additions & 0 deletions apps/nova-desktop/src/folder-handles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { expect, spyOn, test } from "bun:test"

import { directory, restoreFolderHandle, serializeFolderHandle } from "./folder-handles"

test("desktop handles persist as cloneable grant descriptors and restore working readers", async () => {
const original = directory("native-grant", "Super CLI")
expect(() => structuredClone(original)).toThrow()
const saved = structuredClone(serializeFolderHandle(original))
expect(saved).toEqual({ id: "native-grant", name: "Super CLI" })

const calls: unknown[] = []
const fetchMock = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async (_url: RequestInfo | URL, init?: RequestInit) => {
const input = JSON.parse(init?.body as string)
calls.push(input)
return input.path === "" ? Response.json([{ name: "hello.txt", kind: "file" }]) : new Response("hello")
}, { preconnect: globalThis.fetch.preconnect }))
try {
const restored = await restoreFolderHandle(saved) as {
values: () => AsyncIterable<{ name: string; getFile: () => Promise<File> }>
}
for await (const entry of restored.values()) {
expect(entry.name).toBe("hello.txt")
expect(await (await entry.getFile()).text()).toBe("hello")
}
expect(calls).toContainEqual({ id: "native-grant", path: "hello.txt" })
} finally {
fetchMock.mockRestore()
}
})

test("unknown or revoked descriptors cannot restore folder access", async () => {
expect(serializeFolderHandle({ kind: "directory", name: "ungranted" })).toBeUndefined()
expect(await restoreFolderHandle({ path: "/arbitrary/path" })).toBeNull()
const fetchMock = spyOn(globalThis, "fetch").mockImplementation(Object.assign(async () => Response.json({ error: "Invalid folder path" }, { status: 400 }), { preconnect: globalThis.fetch.preconnect }))
try {
await expect(restoreFolderHandle({ id: "revoked", name: "Super CLI" })).rejects.toThrow("Invalid folder path")
} finally {
fetchMock.mockRestore()
}
})
40 changes: 40 additions & 0 deletions apps/nova-desktop/src/folder-handles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const folderDescriptors = new WeakMap<object, { id: string; name: string }>()

async function folderRequest(op: string, id: string, path: string, content?: string) {
const response = await fetch(`/desktop/folder/${op}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id, path, content }) })
if (!response.ok) throw new Error((await response.json()).error ?? "Folder access failed")
return response
}
export function directory(id: string, name: string, path = ""): unknown {
const child = (value: string) => {
if (!value || value.includes("/") || value.includes("\\") || value === "." || value === "..") throw new Error("Invalid filename")
return path ? `${path}/${value}` : value
}
const file = (value: string) => ({
kind: "file", name: value,
getFile: async () => new File([await (await folderRequest("read", id, child(value))).blob()], value),
createWritable: async () => ({ write: async (content: string) => { await folderRequest("write", id, child(value), content) }, close: async () => {} }),
})
const handle = {
kind: "directory", name,
queryPermission: async () => "granted", requestPermission: async () => "granted",
values: async function* () {
const entries: Array<{ name: string; kind: string }> = await (await folderRequest("list", id, path)).json()
for (const entry of entries) yield entry.kind === "directory" ? directory(id, entry.name, child(entry.name)) : file(entry.name)
},
getDirectoryHandle: async (value: string, options?: { create?: boolean }) => { if (options?.create) await folderRequest("mkdir", id, child(value)); return directory(id, value, child(value)) },
getFileHandle: async (value: string) => file(value),
}
if (!path) folderDescriptors.set(handle, { id, name })
return handle
}
export function serializeFolderHandle(handle: unknown): unknown {
return typeof handle === "object" && handle !== null ? folderDescriptors.get(handle) : undefined
}

export async function restoreFolderHandle(record: unknown): Promise<unknown> {
if (!record || typeof record !== "object" || !("id" in record) || typeof record.id !== "string" || !("name" in record) || typeof record.name !== "string") return null
// Only an existing native grant can be restored; the renderer cannot grant a path.
await folderRequest("list", record.id, "")
return directory(record.id, record.name)
}
36 changes: 31 additions & 5 deletions apps/nova-desktop/src/main.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { useEffect, useState } from "react"
import { useEffect, useState, type ReactNode } from "react"
import { createRoot } from "react-dom/client"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { ThemeProvider } from "next-themes"
import { Toaster } from "sonner"
import { getCurrentWindow } from "@tauri-apps/api/window"

import { NovaApp } from "../../web/modules/nova-web/nova-app"
import { NovaLogin } from "../../web/modules/nova-web/nova-login"
Expand All @@ -14,6 +15,31 @@ import { installDesktopPlatform } from "./platform"

installDesktopPlatform()
const queryClient = new QueryClient()

function DesktopTitleBar() {
return (
<div
onMouseDown={event => {
if (event.button === 0) void getCurrentWindow().startDragging()
}}
className="h-10 shrink-0 cursor-default border-b border-white/[0.06] bg-[#0c0c0d]"
/>
)
}

function DesktopShell({ children }: { children: ReactNode }) {
return (
<div className="desktop-shell flex h-dvh flex-col bg-[#0c0c0d]">
<style>{`
.desktop-shell .h-dvh { height: calc(100dvh - 2.5rem); }
.desktop-shell .min-h-dvh { min-height: calc(100dvh - 2.5rem); }
`}</style>
<DesktopTitleBar />
<div className="min-h-0 flex-1 overflow-hidden">{children}</div>
</div>
)
}

function DesktopApp() {
const { data, isPending, error: authError } = useSession()
const [sessions, setSessions] = useState<AgentSessionSummary[] | null>(null)
Expand All @@ -25,9 +51,9 @@ function DesktopApp() {
void listSessions().then(result => { if (active) { setSessions(result.sessions); setError(null) } }).catch(cause => { if (active) setError(cause instanceof Error ? cause.message : "Could not load threads") })
return () => { active = false }
}, [data, retry])
if (error || authError) return <main className="flex min-h-dvh flex-col items-center justify-center gap-4 bg-[#0c0c0d] p-8 text-white"><p role="alert">{error ?? authError}</p><button onClick={() => { if (authError) window.location.reload(); else setRetry(n => n + 1) }}>Retry</button></main>
if (!data && !isPending) return <NovaLogin />
if (!data || !sessions) return <main className="h-dvh bg-[#0c0c0d]" role="status" aria-label="Loading Nova" />
return <NovaApp initialSessions={sessions} user={data.user} />
if (error || authError) return <DesktopShell><main className="flex h-full min-h-0 flex-col items-center justify-center gap-4 bg-[#0c0c0d] p-8 text-white"><p role="alert">{error ?? authError}</p><button onClick={() => { if (authError) window.location.reload(); else setRetry(n => n + 1) }}>Retry</button></main></DesktopShell>
if (!data && !isPending) return <DesktopShell><NovaLogin /></DesktopShell>
if (!data || !sessions) return <DesktopShell><main className="h-full bg-[#0c0c0d]" role="status" aria-label="Loading Nova" /></DesktopShell>
return <DesktopShell><NovaApp initialSessions={sessions} user={data.user} /></DesktopShell>
}
createRoot(document.getElementById("root")!).render(<QueryClientProvider client={queryClient}><ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange><DesktopApp /><Toaster /></ThemeProvider></QueryClientProvider>)
30 changes: 4 additions & 26 deletions apps/nova-desktop/src/platform.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,12 @@ import { invoke } from "@tauri-apps/api/core"
import { installNovaClientPlatform } from "@super/nova/client-platform"
import { desktopComputerSetupSchema } from "@super/nova/computer-use"

async function folderRequest(op: string, id: string, path: string, content?: string) {
const response = await fetch(`/desktop/folder/${op}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id, path, content }) })
if (!response.ok) throw new Error((await response.json()).error ?? "Folder access failed")
return response
}
function directory(id: string, name: string, path = ""): unknown {
const child = (value: string) => {
if (!value || value.includes("/") || value.includes("\\") || value === "." || value === "..") throw new Error("Invalid filename")
return path ? `${path}/${value}` : value
}
const file = (value: string) => ({
kind: "file", name: value,
getFile: async () => new File([await (await folderRequest("read", id, child(value))).blob()], value),
createWritable: async () => ({ write: async (content: string) => { await folderRequest("write", id, child(value), content) }, close: async () => {} }),
})
return {
kind: "directory", name,
queryPermission: async () => "granted", requestPermission: async () => "granted",
values: async function* () {
const entries: Array<{ name: string; kind: string }> = await (await folderRequest("list", id, path)).json()
for (const entry of entries) yield entry.kind === "directory" ? directory(id, entry.name, child(entry.name)) : file(entry.name)
},
getDirectoryHandle: async (value: string, options?: { create?: boolean }) => { if (options?.create) await folderRequest("mkdir", id, child(value)); return directory(id, value, child(value)) },
getFileHandle: async (value: string) => file(value),
}
}
import { directory, serializeFolderHandle, restoreFolderHandle } from "./folder-handles"

export function installDesktopPlatform() {
installNovaClientPlatform({ computerControl: true,
serializeFolderHandle,
restoreFolderHandle,
computerSetup: async () => {
const [response, permissions] = await Promise.all([
fetch("/desktop/computer/setup", { cache: "no-store" }),
Expand Down
Loading
Loading