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
4 changes: 2 additions & 2 deletions pkg/app/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@hanzo/app",
"version": "0.3.111",
"version": "0.3.112",
"description": "Hanzo's app: the shell and its apps (Home, Chat, Inbox, Contacts, Meet, Calendar, Drive, Board, Work, Bots), once, for every Hanzo surface.",
"type": "module",
"main": "./dist/index.js",
Expand Down Expand Up @@ -59,7 +59,7 @@
"peerDependencies": {
"@hanzo/ai": ">=0.7.0",
"@hanzo/appearance": ">=0.2.15",
"@hanzo/build": ">=0.2.135",
"@hanzo/build": ">=0.2.136",
"@hanzo/composer": ">=0.2.0",
"@hanzo/design": ">=0.5.39",
"@hanzo/event": ">=0.3.63",
Expand Down
95 changes: 89 additions & 6 deletions pkg/app/src/lib/local-fs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,17 +37,100 @@ describe('This computer for Dev (hanzo-inc/app issues 309 and 310)', () => {
])
})

it('runs the dev agent in the folder and reads the desktop’s own answer', async () => {
const invoke = vi.fn(async () => ({ session_id: 'local_1', output: 'Edited README.md', success: true }))
it('runs the dev agent in the folder and reads the desktop’s own answer: what it said, and what it did', async () => {
const invoke = vi.fn(async (cmd: string) =>
cmd === 'local_workspace_run_dev' ? { session_id: 'local_1', output: 'Edited README.md', process: "exec bash -lc 'ls ~'", success: true } : null,
)
desktop(invoke)
await expect(desktopLocal()!.run('/Users/me/api', 'Fix the typo')).resolves.toEqual({ ok: true, output: 'Edited README.md' })
await expect(desktopLocal()!.run('/Users/me/api', 'Fix the typo')).resolves.toEqual({ ok: true, output: 'Edited README.md', process: "exec bash -lc 'ls ~'" })
expect(invoke).toHaveBeenCalledWith('local_workspace_run_dev', { workspacePath: '/Users/me/api', prompt: 'Fix the typo' })
await expect(runLocalDev('/Users/me/api', 'x')).resolves.toMatchObject({ sessionId: 'local_1', ok: true })
await expect(runLocalDev('/Users/me/api', 'x')).resolves.toMatchObject({ sessionId: 'local_1', ok: true, process: "exec bash -lc 'ls ~'" })
})

it('says a run the agent failed is not ok, with what it printed', async () => {
desktop(async () => ({ session_id: 'local_2', output: 'error: not signed in', success: false }))
await expect(desktopLocal()!.run('/Users/me/api', 'x')).resolves.toEqual({ ok: false, output: 'error: not signed in' })
desktop(async (cmd) => (cmd === 'local_workspace_run_dev' ? { session_id: 'local_2', output: 'error: not signed in', success: false } : null))
await expect(desktopLocal()!.run('/Users/me/api', 'x')).resolves.toEqual({ ok: false, output: 'error: not signed in', process: '' })
})

it('hears the desktop fetch the agent while a run waits, and stops listening once it is done', async () => {
let heard: ((e: { payload: { percent: number } }) => void) | null = null
const calls: string[] = []
const invoke = vi.fn(async (cmd: string) => {
calls.push(cmd)
if (cmd === 'plugin:event|listen') return 7
if (cmd === 'local_workspace_run_dev') {
heard?.({ payload: { percent: 40 } })
heard?.({ payload: { percent: 100 } })
return { session_id: 'local_3', output: 'Done.', success: true }
}
return null
})
desktop(invoke)
const internals = (globalThis as unknown as { window: { __TAURI_INTERNALS__: Record<string, unknown> } }).window.__TAURI_INTERNALS__
internals.transformCallback = (cb: (e: { payload: { percent: number } }) => void) => {
heard = cb
return 1
}
const percents: number[] = []
await desktopLocal()!.run('/Users/me/api', 'x', (p) => percents.push(p))
expect(percents).toEqual([40, 100])
expect(invoke).toHaveBeenCalledWith('plugin:event|listen', expect.objectContaining({ event: 'local-dev-setup' }))
expect(invoke).toHaveBeenCalledWith('plugin:event|unlisten', { event: 'local-dev-setup', eventId: 7 })
expect(calls.indexOf('plugin:event|listen')).toBeLessThan(calls.indexOf('local_workspace_run_dev'))
})

it('runs without listening in a window that has no event plugin', async () => {
const invoke = vi.fn(async (cmd: string) => (cmd === 'local_workspace_run_dev' ? { session_id: 'local_4', output: 'Done.', success: true } : null))
desktop(invoke)
await expect(desktopLocal()!.run('/Users/me/api', 'x', () => {})).resolves.toMatchObject({ ok: true })
expect(invoke).not.toHaveBeenCalledWith('plugin:event|listen', expect.anything())
})

it('adds the project folders the desktop finds, after the ones opened, and says when they arrive', async () => {
desktop(
async (cmd) =>
cmd === 'local_workspace_discover'
? [
{ name: 'shop', path: '/Users/me/work/shop', modified: 900 },
{ name: 'site', path: '/Users/me/site', modified: 800 },
{ name: 'blog', path: '/Users/me/blog', modified: 700 },
]
: null,
{ 'hanzo.local_workspaces': two },
)
const here = desktopLocal()!
// Before the answer: only the ones opened.
expect(here.folders().map((f) => f.name)).toEqual(['site', 'api'])
const arrived = vi.fn()
const stop = here.changed!(arrived)
await vi.waitFor(() => expect(arrived).toHaveBeenCalled())
// A folder found that was also opened is listed once, as opened; the rest follow in the order found.
expect(here.folders()).toEqual([
{ path: '/Users/me/site', name: 'site', used: 100 },
{ path: '/Users/me/api', name: 'api', used: 300 },
{ path: '/Users/me/work/shop', name: 'shop' },
{ path: '/Users/me/blog', name: 'blog' },
])
stop()
})

it('opens a folder that was only found, so the next run there is the one used last', async () => {
desktop(async (cmd) => (cmd === 'local_workspace_discover' ? [{ name: 'shop', path: '/Users/me/work/shop', modified: 900 }] : null), { 'hanzo.local_workspaces': two })
const here = desktopLocal()!
await vi.waitFor(() => expect(here.folders().map((f) => f.name)).toContain('shop'))
here.use('/Users/me/work/shop')
expect(getLocalWorkspaces().map((w) => w.path)).toContain('/Users/me/work/shop')
expect(here.folders().find((f) => f.name === 'shop')!.used).toBeGreaterThan(300)
})

it('offers only the folders it opened when the desktop cannot look', async () => {
desktop(async (cmd) => {
if (cmd === 'local_workspace_discover') throw new Error('Command not found')
return null
}, { 'hanzo.local_workspaces': two })
const here = desktopLocal()!
await Promise.resolve()
expect(here.folders().map((f) => f.name)).toEqual(['site', 'api'])
})

it('takes a folder from the window’s own dialog, keeps it, and makes it the one used last', async () => {
Expand Down
85 changes: 70 additions & 15 deletions pkg/app/src/lib/local-fs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
* 5. Run local coding tasks against the workspace with `hanzoai/dev`.
*
* Dev's This computer is `desktopLocal()` (hanzo-inc/app issues 309 and 310): on Hanzo Desktop it hands @hanzo/build
* the folders opened here, the window's folder dialog and the `dev` runner, so a run works in a folder with no
* repository. Auto there is the folder used most recently (`lastOpenedAt`). A browser page has no folder of its own,
* and gets none.
* the folders opened here and the project folders the desktop finds on the computer, the window's folder dialog and
* the `dev` runner, so a run works in a folder with no repository. Auto there is the folder the ask is about, else
* the one used most recently (`lastOpenedAt`), as @hanzo/build's `route` reads them. A browser page has no folder of
* its own, and gets none.
*/
import type { Folder, Local } from '@hanzo/build'

Expand Down Expand Up @@ -280,32 +281,81 @@ export async function deleteLocalPath(path: string): Promise<void> {
}

/**
* Run local coding task with `dev` CLI. Hanzo Desktop answers `{session_id, output, success}` (its Rust struct's own
* names); `ok` is false only when it said the agent failed.
* Run local coding task with `dev` CLI. Hanzo Desktop answers `{session_id, output, process, success}` (its Rust struct's own
* names): `output` is the agent's final message, `process` what it did on the way. `ok` is false only when it said the agent
* failed. The desktop fetches the agent itself when the computer has none.
*/
export async function runLocalDev(workspacePath: string, prompt: string): Promise<{ sessionId: string; output?: string; ok: boolean }> {
export async function runLocalDev(workspacePath: string, prompt: string): Promise<{ sessionId: string; output?: string; process?: string; ok: boolean }> {
if (isTauri()) {
const r = await tauriInvoke<{ sessionId?: string; session_id?: string; output?: string; success?: boolean }>('local_workspace_run_dev', {
const r = await tauriInvoke<{ sessionId?: string; session_id?: string; output?: string; process?: string; success?: boolean }>('local_workspace_run_dev', {
workspacePath,
prompt,
})
return { sessionId: r?.sessionId ?? r?.session_id ?? '', output: r?.output, ok: r?.success !== false }
return { sessionId: r?.sessionId ?? r?.session_id ?? '', output: r?.output, process: r?.process, ok: r?.success !== false }
}
throw new Error('Local Dev agent execution requires Hanzo Desktop')
}

/** A project folder the desktop found on the computer, as `local_workspace_discover` answers it. */
interface Found {
name: string
path: string
modified: number
}

/**
* Listen to an event Hanzo Desktop emits, through the window's own IPC (what `@tauri-apps/api/event`'s `listen` does,
* without the package). Answers how to stop listening; a window without the event plugin hears nothing.
*/
async function tauriListen<T>(event: string, handler: (payload: T) => void): Promise<() => void> {
const win = window as unknown as {
__TAURI_INTERNALS__?: { transformCallback?: (cb: (e: { payload: T }) => void) => number; invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown> }
__TAURI_EVENT_PLUGIN_INTERNALS__?: { unregisterListener?: (event: string, id: number) => void }
}
const internals = win.__TAURI_INTERNALS__
if (!internals?.transformCallback) return () => {}
const id = (await internals.invoke('plugin:event|listen', {
event,
target: { kind: 'Any' },
handler: internals.transformCallback((e) => handler(e.payload)),
})) as number
return () => {
win.__TAURI_EVENT_PLUGIN_INTERNALS__?.unregisterListener?.(event, id)
void internals.invoke('plugin:event|unlisten', { event, eventId: id }).catch(() => {})
}
}

/** The event the desktop emits while it fetches Hanzo Dev for a computer that has none: `{ percent }`, 0 to 100. */
const SETUP_EVENT = 'local-dev-setup'

/** A workspace as Dev's Folder pill reads it. */
const folderOf = (w: LocalWorkspace): Folder => ({ path: w.path, name: w.name, used: w.lastOpenedAt || w.addedAt || 0 })

/**
* This computer, as @hanzo/build's Dev takes it (`Host.local`): the folders Hanzo Desktop opened, its folder dialog,
* and a run of the `dev` agent in one folder (`dev exec -C <folder>`, its workspace-write sandbox). Null outside the
* desktop window, so a browser page offers the cloud workspace and the org's machines only.
* This computer, as @hanzo/build's Dev takes it (`Host.local`): the folders Hanzo Desktop opened and the project folders it
* finds on the computer (asked once, when this is made, and announced through `changed` when they arrive), its folder
* dialog, and a run of the `dev` agent in one folder (`dev exec -C <folder>`, its workspace-write sandbox). Null outside
* the desktop window, so a browser page offers the cloud workspace and the org's machines only.
*/
export function desktopLocal(): Local | null {
if (!isTauri()) return null
let found: Folder[] = []
tauriInvoke<Found[] | null>('local_workspace_discover').then(
(list) => {
found = (Array.isArray(list) ? list : []).filter((f) => f && typeof f.path === 'string' && f.path).map((f) => ({ path: f.path, name: f.name || f.path.split(/[/\\]/).filter(Boolean).pop() || f.path }))
if (found.length) notify()
},
() => {
// A desktop that cannot look offers the folders it opened, as before.
},
)
return {
folders: () => getLocalWorkspaces().map(folderOf),
folders: () => {
const opened = getLocalWorkspaces().map(folderOf)
const known = new Set(opened.map((f) => f.path))
return [...opened, ...found.filter((f) => !known.has(f.path))]
},
changed: subscribeLocalFs,
pick: async () => {
const ws = await pickLocalFolder({ browser: false })
return ws ? folderOf(ws) : null
Expand All @@ -315,9 +365,14 @@ export function desktopLocal(): Local | null {
if (ws) setActiveWorkspace(ws)
else addLocalWorkspace(path)
},
run: async (folder, prompt) => {
const r = await runLocalDev(folder, prompt)
return { ok: r.ok, output: r.output ?? '' }
run: async (folder, prompt, setup) => {
const stop = setup ? await tauriListen<{ percent: number }>(SETUP_EVENT, (p) => setup(p.percent)).catch(() => () => {}) : () => {}
try {
const r = await runLocalDev(folder, prompt)
return { ok: r.ok, output: r.output ?? '', process: r.process ?? '' }
} finally {
stop()
}
},
}
}
18 changes: 9 additions & 9 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ minimumReleaseAge: 0
catalog:
'@hanzo/ai': 0.7.0
'@hanzo/appearance': 0.2.15
'@hanzo/build': 0.2.135
'@hanzo/build': 0.2.136
'@hanzo/composer': 0.2.0
'@hanzo/design': 0.5.39
'@hanzo/event': 0.3.67
Expand Down
Loading