Skip to content

AI-native design editor. Open-source Figma alternative.

2.7 KB
Raw Blame
import { Command } from '@tauri-apps/plugin-shell'

import { decodeTauriStderr } from '@/app/shell/ui'
import { resolvePlatformCommand } from '@/app/tauri/command'

export type TauriChild = {
  write(data: number[]): Promise<void>
  kill(): Promise<void>
}

/** A started agent: its process, and the pipes the ACP connection reads and writes. */
export interface ACPProcess {
  child: TauriChild
  input: WritableStream<Uint8Array>
  output: ReadableStream<Uint8Array>
}

type ACPProcessOptions = {
  command: string
  args: string[]
  logId: string
  destroying: () => boolean
  onUnexpectedClose: () => void
}

export async function spawnACPProcess({
  command: commandName,
  args,
  logId,
  destroying,
  onUnexpectedClose
}: ACPProcessOptions): Promise<ACPProcess> {
  const resolved = resolvePlatformCommand(commandName, args)
  const command = Command.create(resolved.command, resolved.args, {
    encoding: 'raw',
    env: {}
  })

  const stdoutChunks: Uint8Array[] = []
  let stdoutResolver: ((chunk: Uint8Array | null) => void) | null = null
  let stdoutClosed = false
  let stdoutClosedError: Error | null = null

  command.stdout.on('data', (raw: Uint8Array | number[]) => {
    const chunk = raw instanceof Uint8Array ? raw : new Uint8Array(raw)
    if (stdoutResolver) {
      const resolve = stdoutResolver
      stdoutResolver = null
      resolve(chunk)
    } else {
      stdoutChunks.push(chunk)
    }
  })

  command.stderr.on('data', (raw: Uint8Array | number[] | string) => {
    console.error(`[ACP ${logId}]`, decodeTauriStderr(raw))
  })

  command.on('close', () => {
    stdoutClosed = true
    stdoutClosedError = destroying() ? null : new Error('Agent process exited unexpectedly.')
    if (stdoutResolver) {
      const resolve = stdoutResolver
      stdoutResolver = null
      resolve(null)
    }
    if (!destroying()) {
      onUnexpectedClose()
    }
  })

  const child = await command.spawn()

  const output = new ReadableStream<Uint8Array>({
    async pull(controller) {
      const buffered = stdoutChunks.shift()
      if (buffered) {
        controller.enqueue(buffered)
        return
      }
      if (stdoutClosed) {
        if (stdoutClosedError) controller.error(stdoutClosedError)
        else controller.close()
        return
      }
      const chunk = await new Promise<Uint8Array | null>((resolve) => {
        stdoutResolver = resolve
      })
      if (chunk) {
        controller.enqueue(chunk)
        return
      }
      if (stdoutClosedError) controller.error(stdoutClosedError)
      else controller.close()
    }
  })

  const input = new WritableStream<Uint8Array>({
    async write(chunk) {
      await child.write(Array.from(chunk))
    }
  })

  return { child, input, output }
}