Skip to content

An open-source, faster Devin alternative

TypeScript

feat(web): add repository agent deployment flow

Igor Zalutskid5dfee324969
diff --git a/web/src/App.tsx b/web/src/App.tsx
index ceb8d996..190abb70 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -8,7 +8,9 @@ import AppShell from './components/app-shell'
// deps (xterm, in Terminal/LogsPanel) only load on SandboxDetail when opened.
const Dashboard = lazy(() => import('./pages/Dashboard'))
const Agents = lazy(() => import('./pages/Agents'))
+const AgentNew = lazy(() => import('./pages/AgentNew'))
const AgentDetail = lazy(() => import('./pages/AgentDetail'))
+const AgentDeployment = lazy(() => import('./pages/AgentDeployment'))
const Credentials = lazy(() => import('./pages/Credentials'))
const Sessions = lazy(() => import('./pages/Sessions'))
const SessionDetail = lazy(() => import('./pages/SessionDetail'))
@@ -36,6 +38,11 @@ export default function App() {
<Route path="getting-started" element={<Dashboard />} />
{/* Agent plane */}
<Route path="agents" element={<Agents />} />
+ <Route path="agents/new" element={<AgentNew />} />
+ <Route
+ path="agents/:agentId/deployments/:deploymentId"
+ element={<AgentDeployment />}
+ />
<Route path="agents/:agentId" element={<AgentDetail />} />
<Route path="agents/:agentId/:tab" element={<AgentDetail />} />
<Route path="credentials" element={<Credentials />} />
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index a4586af3..22f970df 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -32,6 +32,9 @@ export type {
AgentSkills,
SkillItem,
AgentDeploy,
+ AgentDeployment,
+ AgentDeploymentLog,
+ FlueSourceInspection,
Session,
AgentSnapshot,
SessionEvent,
@@ -606,6 +609,40 @@ export const deleteAgentSkills = (agentId: string) =>
// The OC GitHub App (deploy) install-state + pickable repos — org-scoped admin read.
export const getDeployApp = () => apiFetch('/v3/github/deploy-app', {}, S.DeployAppSchema)
+export const inspectFlueRepository = (body: {
+ repo: string
+ path: string
+ production_ref: string
+}) =>
+ apiFetch(
+ '/v3/github/deploy-app/inspect',
+ { method: 'POST', body: JSON.stringify(body) },
+ S.FlueSourceInspectionSchema,
+ )
+
+export const importAgentFromGithub = (
+ body: {
+ name: string
+ source: {
+ type: 'github'
+ repo: string
+ path: string
+ production_ref: string
+ }
+ credential: 'managed'
+ },
+ idempotencyKey: string,
+) =>
+ apiFetch(
+ '/v3/agents/import',
+ {
+ method: 'POST',
+ body: JSON.stringify(body),
+ headers: { 'Idempotency-Key': idempotencyKey },
+ },
+ S.ImportAgentResponseSchema,
+ )
+
// Deployment source — link an agent to a repo dir for push-to-deploy (deploy-from-github).
export const getDeploymentSource = (agentId: string) =>
apiFetch(`/v3/agents/${agentId}/deployment-source`, {}, S.DeploymentSourceResponseSchema)
@@ -631,6 +668,29 @@ export const deployFromGithub = (agentId: string) =>
{ method: 'POST', body: JSON.stringify({ input: { type: 'github' } }) },
)
+export const getAgentDeployment = (agentId: string, deploymentId: string) =>
+ apiFetch(
+ `/v3/agents/${encodeURIComponent(agentId)}/deployments/${encodeURIComponent(deploymentId)}`,
+ {},
+ S.AgentDeploymentSchema,
+ )
+
+export const getAgentDeploymentLogs = (
+ agentId: string,
+ deploymentId: string,
+ options: { after?: string; limit?: number } = {},
+) => {
+ const query = new URLSearchParams()
+ if (options.after) query.set('after', options.after)
+ if (options.limit) query.set('limit', String(options.limit))
+ const qs = query.toString()
+ return apiFetch(
+ `/v3/agents/${encodeURIComponent(agentId)}/deployments/${encodeURIComponent(deploymentId)}/logs${qs ? `?${qs}` : ''}`,
+ {},
+ S.AgentDeploymentLogsSchema,
+ )
+}
+
// Slack — an agent's BYO Slack app (1 app ⟷ 1 agent ⟷ 1 workspace). Two-step
// connect: START (manifest) returns the app manifest + guided steps; COMPLETE
// posts the three pasted values back. No secrets are ever returned.
diff --git a/web/src/api/deployment-schemas.test.ts b/web/src/api/deployment-schemas.test.ts
new file mode 100644
index 00000000..a443b199
--- /dev/null
+++ b/web/src/api/deployment-schemas.test.ts
@@ -0,0 +1,134 @@
+import { describe, expect, it } from 'vitest'
+import {
+ AgentDeploymentLogsSchema,
+ AgentDeploymentSchema,
+ DeployAppSchema,
+} from './schemas'
+
+const deployment = {
+ id: 'dep_0123456789abcdef01234567',
+ state: 'building',
+ phase: 'build',
+ terminal: false,
+ result: null,
+ input_type: 'github',
+ revision_id: null,
+ revision: null,
+ source: {
+ via: 'repo',
+ repo_id: 'repo_0123456789abcdef01234567',
+ path: '',
+ git_sha: 'a'.repeat(40),
+ },
+ source_relation: {
+ repo: {
+ id: 'repo_0123456789abcdef01234567',
+ full_name: 'example/flue-agent',
+ },
+ path: '',
+ production_ref: 'main',
+ status: 'active',
+ ref: 'main',
+ sha: 'a'.repeat(40),
+ commit_url: `https://github.com/example/flue-agent/commit/${'a'.repeat(40)}`,
+ },
+ actor: { kind: 'human', id: 'user_123' },
+ ref: 'main',
+ sha: 'a'.repeat(40),
+ error_class: null,
+ error: null,
+ build: {
+ schema_version: 1,
+ attempts: 1,
+ root: '',
+ node: '22.19.0',
+ source_bytes: 42,
+ source_files: 3,
+ },
+ configuration: {
+ entrypoint: 'support-triage',
+ model: 'anthropic/claude-haiku-4-5',
+ runtime: { family: 'flue', type: 'default' },
+ variable_names: ['REGION'],
+ },
+ log_bytes: 86,
+ log_truncated: false,
+ live_touched: false,
+ agent_live: null,
+ restore_eligibility: 'none',
+ redeploy_of: null,
+ allowed_actions: ['view_commit'],
+ active: false,
+ timing: {
+ accepted_at: '2026-07-14T20:00:00.000Z',
+ started_at: '2026-07-14T20:00:01.000Z',
+ finished_at: null,
+ cancel_requested_at: null,
+ queue_ms: 1_000,
+ run_ms: null,
+ total_ms: null,
+ },
+ created_at: '2026-07-14T20:00:00.000Z',
+ updated_at: '2026-07-14T20:00:02.000Z',
+ started_at: '2026-07-14T20:00:01.000Z',
+ finished_at: null,
+}
+
+describe('repository deployment API schemas', () => {
+ it('accepts the frozen deployment read model and ignores additive fields', () => {
+ const parsed = AgentDeploymentSchema.parse({
+ ...deployment,
+ future_server_field: { safe: true },
+ })
+
+ expect(parsed.state).toBe('building')
+ expect(parsed.source_relation?.repo?.full_name).toBe('example/flue-agent')
+ expect('future_server_field' in parsed).toBe(false)
+ })
+
+ it('keeps deployment-log sequence identity as an opaque string', () => {
+ const seq = '900719925474099312345'
+ const parsed = AgentDeploymentLogsSchema.parse({
+ data: [
+ {
+ seq,
+ cursor: 'opaque-cursor',
+ recorded_at: '2026-07-14T20:00:02.000Z',
+ phase: 'build',
+ stream: 'stdout',
+ chunk: 'building',
+ },
+ ],
+ next_cursor: 'opaque-cursor',
+ has_more: false,
+ })
+
+ expect(parsed.data[0]?.seq).toBe(seq)
+ })
+
+ it('filters repositories without a registered import coordinate safely', () => {
+ const parsed = DeployAppSchema.parse({
+ installed: true,
+ install_url: null,
+ configure_url: null,
+ account: 'example',
+ repository_selection: 'selected',
+ repositories: [
+ {
+ id: null,
+ full_name: 'example/pending-registration',
+ default_branch: 'main',
+ private: true,
+ },
+ ],
+ })
+
+ expect(parsed.repositories[0]?.id).toBeNull()
+ })
+
+ it('fails closed when deployment identity or canonical state is absent', () => {
+ const withoutState = { ...deployment } as Partial<typeof deployment>
+ delete withoutState.state
+ expect(() => AgentDeploymentSchema.parse(withoutState)).toThrow()
+ })
+})
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 31173625..2ba4409e 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -495,9 +495,24 @@ const deployAppInstalled = {
account: 'acme',
repository_selection: 'selected' as const,
repositories: [
- { full_name: 'acme/agents', default_branch: 'main', private: true },
- { full_name: 'acme/support-bot', default_branch: 'main', private: false },
- { full_name: 'acme/infra', default_branch: 'production', private: true },
+ {
+ id: 'repo_01k0acmeagents000000000',
+ full_name: 'acme/agents',
+ default_branch: 'main',
+ private: true,
+ },
+ {
+ id: 'repo_01k0supportbot00000000',
+ full_name: 'acme/support-bot',
+ default_branch: 'main',
+ private: false,
+ },
+ {
+ id: 'repo_01k0acmeinfra000000000',
+ full_name: 'acme/infra',
+ default_branch: 'production',
+ private: true,
+ },
],
}
const deployAppNotInstalled = {
@@ -525,6 +540,191 @@ const deploymentSource = {
full_name: 'acme/agents',
}
+const flueInspection = {
+ repository: {
+ id: 'repo_01k0supportbot00000000',
+ full_name: 'acme/support-bot',
+ default_branch: 'main',
+ },
+ root: '',
+ production_ref: 'main',
+ sha: 'cbb8766d972199b01d03389d2680970dc29d1d34',
+ manifest: {
+ schema_version: 1 as const,
+ entrypoint: 'support-triage',
+ model: 'anthropic/claude-haiku-4-5',
+ runtime: { family: 'flue' as const, type: 'default' },
+ vars: { SUPPORT_QUEUE: 'priority' },
+ },
+ package: {
+ name: 'oc-flue-starter',
+ node_engine: '>=22.19 <23',
+ flue_cli: '0.1.0',
+ },
+ lockfile: { version: 3 },
+ builder: { node: '22.19.0' },
+ source: { files: 28, bytes: 164_208 },
+ variable_names: ['SUPPORT_QUEUE'],
+ warnings: [],
+}
+
+const importedAgent = {
+ id: 'agt_flue_import',
+ name: 'Support triage',
+ prompt: null,
+ prompt_hash: null,
+ model: 'anthropic/claude-haiku-4-5',
+ runtime: 'flue',
+ credential_id: 'managed',
+ revision: 0,
+ active_revision_id: null,
+ active_revision: null,
+ deployment_status: {
+ deployment_id: 'dep_flue_building',
+ state: 'building',
+ result: null,
+ error_class: null,
+ live_touched: false,
+ live_status: null,
+ updated_at: at(0, 0),
+ },
+ flue: { agent_name: 'support-triage', live: null },
+ created_at: at(0, 1),
+}
+
+const importedSource = {
+ agent_id: importedAgent.id,
+ repo_id: flueInspection.repository.id,
+ path: '',
+ production_ref: 'main',
+ status: 'active',
+ latest_seen_sha: flueInspection.sha,
+ active_deployed_sha: null,
+ full_name: flueInspection.repository.full_name,
+}
+
+const flueDeployment = {
+ id: 'dep_flue_building',
+ state: 'building',
+ phase: 'build',
+ terminal: false,
+ result: null,
+ input_type: 'github',
+ revision_id: null,
+ revision: null,
+ source: {
+ via: 'repo',
+ repo_id: flueInspection.repository.id,
+ path: '',
+ git_sha: flueInspection.sha,
+ },
+ source_relation: {
+ repo: {
+ id: flueInspection.repository.id,
+ full_name: flueInspection.repository.full_name,
+ },
+ path: '',
+ production_ref: 'main',
+ status: 'active',
+ ref: 'main',
+ sha: flueInspection.sha,
+ commit_url: `https://github.com/${flueInspection.repository.full_name}/commit/${flueInspection.sha}`,
+ },
+ actor: { kind: 'human', id: 'user_2abc' },
+ ref: 'main',
+ sha: flueInspection.sha,
+ error: null,
+ error_class: null,
+ build: {
+ schema_version: 1,
+ root: '',
+ node: '22.19.0',
+ npm: '10.9.3',
+ lockfile_version: 3,
+ builder: 'oc@dev',
+ attempts: 1,
+ source_files: 28,
+ source_bytes: 164_208,
+ },
+ configuration: {
+ entrypoint: 'support-triage',
+ model: 'anthropic/claude-haiku-4-5',
+ runtime: { family: 'flue', type: 'default' },
+ variable_names: ['SUPPORT_QUEUE'],
+ },
+ log_bytes: 862,
+ log_truncated: false,
+ live_touched: false,
+ agent_live: null,
+ restore_eligibility: 'none',
+ redeploy_of: null,
+ allowed_actions: ['view_commit'],
+ active: false,
+ timing: {
+ accepted_at: at(0, 1),
+ started_at: at(0, 1),
+ finished_at: null,
+ cancel_requested_at: null,
+ queue_ms: 420,
+ run_ms: null,
+ total_ms: null,
+ },
+ created_at: at(0, 1),
+ updated_at: at(0, 0),
+ started_at: at(0, 1),
+ finished_at: null,
+}
+
+const failedFlueDeployment = {
+ ...flueDeployment,
+ id: 'dep_flue_failed',
+ state: 'failed',
+ phase: 'failed',
+ terminal: true,
+ result: 'failed',
+ error: {
+ class: 'install_failed',
+ phase: 'install',
+ message: 'npm ci failed because package-lock.json is out of date.',
+ retryable: false,
+ },
+ error_class: 'install_failed',
+ finished_at: at(0, 0),
+ timing: {
+ ...flueDeployment.timing,
+ finished_at: at(0, 0),
+ run_ms: 12_000,
+ total_ms: 12_420,
+ },
+}
+
+const flueDeploymentLogs = [
+ {
+ seq: '101',
+ cursor: 'deployment-log-101',
+ recorded_at: at(0, 1),
+ phase: 'source',
+ stream: 'system',
+ chunk: 'Materialized acme/support-bot at cbb8766',
+ },
+ {
+ seq: '102',
+ cursor: 'deployment-log-102',
+ recorded_at: at(0, 1),
+ phase: 'install',
+ stream: 'stdout',
+ chunk: 'added 214 packages in 4s\n',
+ },
+ {
+ seq: '103',
+ cursor: 'deployment-log-103',
+ recorded_at: at(0, 0),
+ phase: 'build',
+ stream: 'system',
+ chunk: 'Running offline Flue artifact builder',
+ },
+]
+
// Revisions / deploys / skills for the agent Overview + Deployments tab.
const agentRevisions = [
{
@@ -924,6 +1124,19 @@ const ROUTES: Array<[RegExp, Handler]> = [
// Durable Agent Sessions — lists return the { data: [...] } envelope.
[/^\/v3\/agents\/[^/]+\/slack$/, () => slackConnection],
[/^\/v3\/github\/deploy-app$/, () => deployApp],
+ [
+ /^\/v3\/agents\/[^/]+\/deployments\/[^/]+\/logs(?:\?.*)?$/,
+ () => ({
+ data: flueDeploymentLogs,
+ next_cursor: 'deployment-log-103',
+ has_more: false,
+ }),
+ ],
+ [
+ /^\/v3\/agents\/[^/]+\/deployments\/dep_flue_failed$/,
+ () => failedFlueDeployment,
+ ],
+ [/^\/v3\/agents\/[^/]+\/deployments\/[^/]+$/, () => flueDeployment],
[
/^\/v3\/agents\/[^/]+\/deployment-source$/,
() =>
@@ -932,6 +1145,7 @@ const ROUTES: Array<[RegExp, Handler]> = [
[/^\/v3\/agents\/[^/]+\/deploys$/, () => ({ data: agentDeploys })],
[/^\/v3\/agents\/[^/]+\/revisions$/, () => ({ data: agentRevisions })],
[/^\/v3\/agents\/[^/]+\/skills$/, () => agentSkills],
+ [/^\/v3\/agents\/agt_flue_import$/, () => importedAgent],
[/^\/v3\/agents\/[^/]+$/, () => agents[0]],
[/^\/v3\/agents$/, () => ({ data: agents })],
[/^\/v3\/credentials$/, () => ({ data: credentials })],
@@ -959,6 +1173,16 @@ const ROUTES: Array<[RegExp, Handler]> = [
// Mutations the preview needs to echo something parseable (e.g. the Slack
// wizard's POST …/slack/manifest → manifest+steps). Everything else 204-ish.
const POST_ROUTES: [RegExp, () => unknown][] = [
+ [/^\/v3\/github\/deploy-app\/inspect$/, () => flueInspection],
+ [
+ /^\/v3\/agents\/import$/,
+ () => ({
+ agent: importedAgent,
+ source: importedSource,
+ deployment: flueDeployment,
+ }),
+ ],
+ [/^\/v3\/agents$/, () => agents[0]],
[/^\/v3\/agents\/[^/]+\/slack\/manifest$/, () => slackManifest],
[
/^\/v3\/agents\/[^/]+\/slack$/,
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index 16469e98..1ece4c33 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -337,6 +337,32 @@ export const AgentSchema = z.object({
.object({ id: z.string(), number: z.number(), digest: z.string() })
.nullish(),
limits: record.nullish(),
+ deployment_status: z
+ .object({
+ deployment_id: z.string().nullish(),
+ state: z.string(),
+ result: z.string().nullish(),
+ error_class: z.string().nullish(),
+ live_touched: z.boolean(),
+ live_status: z.string().nullish(),
+ updated_at: z.string().nullish(),
+ })
+ .optional(),
+ flue: z
+ .object({
+ agent_name: z.string().nullish(),
+ live: z
+ .object({
+ deployment_id: z.string().nullish(),
+ worker_version_id: z.string().nullish(),
+ status: z.string().nullish(),
+ guarded_at: z.string().nullish(),
+ deadline_at: z.string().nullish(),
+ updated_at: z.string().nullish(),
+ })
+ .nullish(),
+ })
+ .nullish(),
created_at: z.string(),
})
// List endpoints wrap rows in { data: [...], next_cursor? }.
@@ -372,6 +398,143 @@ export const AgentDeploySchema = z.object({
export const AgentDeployListSchema = z.object({
data: z.array(AgentDeploySchema),
})
+
+// Managed repository deployments (work 025). The identity and canonical state
+// are required; phase detail is additive so an older dashboard can keep
+// rendering when the control plane gains new metadata.
+export const AgentDeploymentErrorSchema = z
+ .object({
+ class: z.string(),
+ phase: z.string().optional(),
+ message: z.string().optional(),
+ retryable: z.boolean().optional(),
+ exit_code: z.number().optional(),
+ })
+ .nullish()
+
+export const AgentDeploymentBuildSchema = z
+ .object({
+ schema_version: z.number().optional(),
+ attempts: z.number().optional(),
+ lockfile_version: z.number().optional(),
+ source_bytes: z.number().optional(),
+ source_files: z.number().optional(),
+ artifact_bytes: z.number().optional(),
+ root: z.string().optional(),
+ node: z.string().optional(),
+ npm: z.string().optional(),
+ builder: z.string().optional(),
+ snapshot: z.string().optional(),
+ artifact_digest: z.string().optional(),
+ })
+ .nullish()
+
+export const AgentDeploymentSourceRelationSchema = z
+ .object({
+ repo: z
+ .object({
+ id: z.string(),
+ full_name: z.string().nullish(),
+ })
+ .nullish(),
+ path: z.string().nullish(),
+ production_ref: z.string().nullish(),
+ status: z.string().nullish(),
+ ref: z.string().nullish(),
+ sha: z.string().nullish(),
+ commit_url: z.string().nullish(),
+ })
+ .nullish()
+
+export const AgentDeploymentLiveSchema = z
+ .object({
+ deployment_id: z.string().optional(),
+ worker_version_id: z.string().optional(),
+ status: z.string().optional(),
+ guarded_at: z.string().optional(),
+ deadline_at: z.string().optional(),
+ updated_at: z.string().optional(),
+ })
+ .nullish()
+
+export const AgentDeploymentSchema = z.object({
+ id: z.string(),
+ state: z.string(),
+ phase: z.string(),
+ terminal: z.boolean(),
+ result: z.string().nullish(),
+ input_type: z.string(),
+ revision_id: z.string().nullish(),
+ revision: z
+ .object({
+ id: z.string(),
+ number: z.number().nullish(),
+ digest: z.string().nullish(),
+ created_at: z.string().nullish(),
+ })
+ .nullish(),
+ source: record.nullish(),
+ source_relation: AgentDeploymentSourceRelationSchema,
+ actor: z
+ .object({
+ kind: z.string().optional(),
+ id: z.string().optional(),
+ login: z.string().optional(),
+ })
+ .nullish(),
+ ref: z.string().nullish(),
+ sha: z.string().nullish(),
+ error: AgentDeploymentErrorSchema,
+ error_class: z.string().nullish(),
+ build: AgentDeploymentBuildSchema,
+ configuration: z
+ .object({
+ entrypoint: z.string().optional(),
+ model: z.string().optional(),
+ runtime: z.object({ family: z.string(), type: z.string() }).optional(),
+ variable_names: z.array(z.string()).default([]),
+ })
+ .nullish(),
+ log_bytes: z.number(),
+ log_truncated: z.boolean(),
+ live_touched: z.boolean(),
+ agent_live: AgentDeploymentLiveSchema,
+ restore_eligibility: z.string(),
+ redeploy_of: z.unknown().nullish(),
+ allowed_actions: z.array(z.string()).default([]),
+ active: z.boolean(),
+ timing: z.object({
+ accepted_at: z.string().nullish(),
+ started_at: z.string().nullish(),
+ finished_at: z.string().nullish(),
+ cancel_requested_at: z.string().nullish(),
+ queue_ms: z.number().nullish(),
+ run_ms: z.number().nullish(),
+ total_ms: z.number().nullish(),
+ }),
+ created_at: z.string(),
+ updated_at: z.string(),
+ started_at: z.string().nullish(),
+ finished_at: z.string().nullish(),
+})
+
+export const AgentDeploymentLogSchema = z.object({
+ // Postgres bigint serializers may return a decimal string. Treat this as an
+ // opaque cursor/identity in the dashboard rather than narrowing it to JS's
+ // potentially lossy number range.
+ seq: z.string(),
+ cursor: z.string(),
+ recorded_at: z.string(),
+ phase: z.string(),
+ stream: z.string(),
+ chunk: z.string(),
+})
+
+export const AgentDeploymentLogsSchema = z.object({
+ data: z.array(AgentDeploymentLogSchema).default([]),
+ next_cursor: z.string().nullish(),
+ has_more: z.boolean(),
+})
// The pointer-move response from POST …/revisions/:rev/activate.
export const ActivateRevisionSchema = z.object({
active_revision_id: z.string(),
@@ -428,6 +591,10 @@ export const DeploymentSourceResponseSchema = z.object({
// The OC GitHub App (deploy) install-state + pickable repos — admin/operator surface.
export const DeployAppRepoSchema = z.object({
+ // Older installations can briefly lack their registered repo_ coordinate
+ // during rollout. The import picker filters those rows until registration
+ // reconciliation completes.
+ id: z.string().nullish(),
full_name: z.string(),
default_branch: z.string().nullish(),
private: z.boolean().nullish(),
@@ -446,6 +613,45 @@ export const LinkResultSchema = z.object({
deploy_error: z.object({ type: z.string(), message: z.string() }).nullish(),
})
+export const FlueSourceInspectionSchema = z.object({
+ repository: z.object({
+ id: z.string(),
+ full_name: z.string(),
+ default_branch: z.string().nullish(),
+ }),
+ root: z.string(),
+ production_ref: z.string(),
+ sha: z.string(),
+ manifest: z.object({
+ schema_version: z.literal(1),
+ entrypoint: z.string(),
+ model: z.string(),
+ runtime: z.object({
+ family: z.literal('flue'),
+ type: z.string(),
+ }),
+ vars: z.record(z.string(), z.string()),
+ }),
+ package: z.object({
+ name: z.string().nullish(),
+ node_engine: z.string(),
+ flue_cli: z.string(),
+ }),
+ lockfile: z.object({ version: z.number() }),
+ builder: z.object({ node: z.string() }),
+ source: z.object({ files: z.number(), bytes: z.number() }),
+ variable_names: z.array(z.string()).default([]),
+ warnings: z
+ .array(z.object({ code: z.string(), message: z.string() }))
+ .default([]),
+})
+
+export const ImportAgentResponseSchema = z.object({
+ agent: AgentSchema,
+ source: DeploymentSourceSchema,
+ deployment: AgentDeploymentSchema,
+})
+
// Credentials — the reusable model-provider keys an agent/session resolves. The
// raw key is write-only; the API returns only metadata (last4 for display).
export const CredentialSchema = z.object({
@@ -609,6 +815,9 @@ export type AgentRevision = z.infer<typeof AgentRevisionSchema>
export type AgentSkills = z.infer<typeof AgentSkillsSchema>
export type SkillItem = z.infer<typeof SkillItemSchema>
export type AgentDeploy = z.infer<typeof AgentDeploySchema>
+export type AgentDeployment = z.infer<typeof AgentDeploymentSchema>
+export type AgentDeploymentLog = z.infer<typeof AgentDeploymentLogSchema>
+export type FlueSourceInspection = z.infer<typeof FlueSourceInspectionSchema>
export type Credential = z.infer<typeof CredentialSchema>
export type SlackConnection = z.infer<typeof SlackConnectionSchema>
export type SlackManifestResponse = z.infer<typeof SlackManifestResponseSchema>
diff --git a/web/src/components/manual-agent-form.tsx b/web/src/components/manual-agent-form.tsx
new file mode 100644
index 00000000..c48740dd
--- /dev/null
+++ b/web/src/components/manual-agent-form.tsx
@@ -0,0 +1,290 @@
+import { useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useNavigate } from 'react-router-dom'
+import { createAgent, createCredential, getCredentials } from '@/api/client'
+import { Field, Input, Select, Textarea } from '@/components/form'
+import { Button } from '@/components/ui/button'
+import { notifyError } from '@/lib/errors'
+import {
+ DEFAULT_RUNTIME,
+ defaultModelFor,
+ getRuntime,
+ keyFieldFor,
+ providerForModel,
+ runtimeOptions,
+ withModelGroups,
+} from '@/lib/runtimes'
+
+const NEW_CRED = '__new__'
+const MANAGED = 'managed'
+
+const NAME_ADJECTIVES = [
+ 'swift',
+ 'calm',
+ 'bright',
+ 'clever',
+ 'bold',
+ 'quiet',
+ 'keen',
+ 'brave',
+ 'nimble',
+ 'sunny',
+ 'lucid',
+ 'witty',
+ 'deft',
+ 'mellow',
+ 'crisp',
+ 'vivid',
+]
+const NAME_NOUNS = [
+ 'otter',
+ 'harbor',
+ 'falcon',
+ 'cedar',
+ 'comet',
+ 'delta',
+ 'ember',
+ 'fjord',
+ 'grove',
+ 'heron',
+ 'lynx',
+ 'maple',
+ 'nova',
+ 'quartz',
+ 'sparrow',
+ 'willow',
+]
+
+function randomAgentName(): string {
+ const pick = (items: readonly string[]) =>
+ items[Math.floor(Math.random() * items.length)]
+ return `${pick(NAME_ADJECTIVES)}-${pick(NAME_NOUNS)}`
+}
+
+const DEFAULT_PROMPT =
+ 'You are a helpful AI assistant working in a sandboxed computer. Complete tasks end to end, use the tools available to you, and keep your answers clear and concise. When something is ambiguous, make a sensible assumption and say so.'
+
+export function ManualAgentForm({ onCancel }: { onCancel: () => void }) {
+ const queryClient = useQueryClient()
+ const navigate = useNavigate()
+ const { data: credentials } = useQuery({
+ queryKey: ['credentials'],
+ queryFn: getCredentials,
+ })
+ const [name, setName] = useState(randomAgentName)
+ const [prompt, setPrompt] = useState(DEFAULT_PROMPT)
+ const [runtime, setRuntime] = useState(DEFAULT_RUNTIME)
+ const [model, setModel] = useState(defaultModelFor(DEFAULT_RUNTIME))
+ const [credChoice, setCredChoice] = useState('')
+ const [newCredName, setNewCredName] = useState('')
+ const [newCredKey, setNewCredKey] = useState('')
+
+ const rt = getRuntime(runtime)
+ const provider = providerForModel(model) || rt.provider
+ const keyField = keyFieldFor(provider)
+ const providerCreds = (credentials ?? []).filter(
+ (credential) => credential.provider === provider,
+ )
+ const hasDefault = providerCreds.some((credential) => credential.is_default)
+
+ const defaultCredFor = (available: typeof providerCreds) =>
+ available.find((credential) => credential.is_default)?.id ?? MANAGED
+ const selectedCredChoice = credChoice || defaultCredFor(providerCreds)
+
+ const onRuntimeChange = (value: string) => {
+ setRuntime(value)
+ const nextModel = defaultModelFor(value)
+ setModel(nextModel)
+ setCredChoice(
+ defaultCredFor(
+ (credentials ?? []).filter(
+ (credential) => credential.provider === providerForModel(nextModel),
+ ),
+ ),
+ )
+ setNewCredName('')
+ setNewCredKey('')
+ }
+
+ const onModelChange = (value: string) => {
+ setModel(value)
+ const nextProvider = providerForModel(value)
+ if (nextProvider !== provider) {
+ setCredChoice(
+ defaultCredFor(
+ (credentials ?? []).filter(
+ (credential) => credential.provider === nextProvider,
+ ),
+ ),
+ )
+ setNewCredName('')
+ setNewCredKey('')
+ }
+ }
+
+ const credOptions = [
+ { value: MANAGED, label: 'Managed · no key needed' },
+ ...providerCreds.map((credential) => ({
+ value: credential.id,
+ label: `${credential.name || 'Unnamed'}${
+ credential.last4 ? ` ·· ${credential.last4}` : ''
+ }${credential.is_default ? ' (default)' : ''}`,
+ })),
+ { value: NEW_CRED, label: '+ New credential…' },
+ ]
+
+ const createMutation = useMutation({
+ mutationFn: async () => {
+ let credentialId: string | undefined
+ if (selectedCredChoice === MANAGED) {
+ credentialId = MANAGED
+ } else if (selectedCredChoice === NEW_CRED) {
+ const credential = await createCredential({
+ key: newCredKey.trim(),
+ provider,
+ name: newCredName.trim() || undefined,
+ is_default: !hasDefault,
+ })
+ credentialId = credential.id
+ } else if (selectedCredChoice) {
+ credentialId = selectedCredChoice
+ }
+ return createAgent({
+ name: name.trim(),
+ prompt: prompt.trim(),
+ model,
+ runtime,
+ credential: credentialId,
+ })
+ },
+ onSuccess: (agent) => {
+ void queryClient.invalidateQueries({ queryKey: ['agents'] })
+ void queryClient.invalidateQueries({ queryKey: ['credentials'] })
+ setNewCredKey('')
+ void navigate(`/agents/${agent.id}`)
+ },
+ onError: (error) => notifyError("Couldn't create the agent.", error),
+ })
+
+ const canCreate =
+ name.trim().length > 0 &&
+ prompt.trim().length > 0 &&
+ (selectedCredChoice !== NEW_CRED || newCredKey.trim().length > 0)
+
+ return (
+ <form
+ className="space-y-4"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (canCreate) createMutation.mutate()
+ }}
+ >
+ <Field label="Name" htmlFor="agent-name">
+ <Input
+ id="agent-name"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="e.g. PR Reviewer"
+ />
+ </Field>
+ <Field
+ label="Prompt"
+ htmlFor="agent-prompt"
+ description="The system prompt that defines how the agent behaves."
+ >
+ <Textarea
+ id="agent-prompt"
+ value={prompt}
+ onChange={(event) => setPrompt(event.target.value)}
+ placeholder="You are a meticulous code reviewer…"
+ className="min-h-28"
+ />
+ </Field>
+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
+ <Field
+ label="Runtime"
+ htmlFor="agent-runtime"
+ description="The engine, fixed once created."
+ >
+ <Select
+ id="agent-runtime"
+ value={runtime}
+ onValueChange={onRuntimeChange}
+ options={runtimeOptions}
+ />
+ </Field>
+ <Field
+ label="Model"
+ htmlFor="agent-model"
+ description={`Models for the ${rt.label} runtime.`}
+ >
+ <Select
+ key={runtime}
+ id="agent-model"
+ value={model}
+ onValueChange={onModelChange}
+ options={withModelGroups(rt.models)}
+ />
+ </Field>
+ </div>
+ <Field
+ label="Credential"
+ htmlFor="agent-cred"
+ description={
+ selectedCredChoice === MANAGED
+ ? 'Run via OpenComputer, billed to your credits. No key needed.'
+ : `The ${provider} key this agent runs on (matches the model). Reuse one from Credentials, or add a new one here.`
+ }
+ >
+ <Select
+ key={provider}
+ id="agent-cred"
+ value={selectedCredChoice}
+ onValueChange={setCredChoice}
+ options={credOptions}
+ placeholder="Choose a credential"
+ />
+ </Field>
+ {selectedCredChoice === NEW_CRED ? (
+ <div className="border-border bg-panel-2 grid grid-cols-1 gap-4 rounded-md border p-3 sm:grid-cols-2">
+ <Field label="Credential name" htmlFor="new-cred-name">
+ <Input
+ id="new-cred-name"
+ value={newCredName}
+ onChange={(event) => setNewCredName(event.target.value)}
+ placeholder="e.g. Production"
+ />
+ </Field>
+ <Field
+ label={keyField.keyLabel}
+ htmlFor="new-cred-key"
+ description="Encrypted in a dedicated secret store."
+ >
+ <Input
+ id="new-cred-key"
+ type="password"
+ value={newCredKey}
+ onChange={(event) => setNewCredKey(event.target.value)}
+ placeholder={keyField.keyPlaceholder}
+ />
+ </Field>
+ </div>
+ ) : null}
+ <div className="flex flex-col-reverse justify-end gap-2 pt-2 sm:flex-row">
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => {
+ setNewCredKey('')
+ onCancel()
+ }}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" disabled={createMutation.isPending || !canCreate}>
+ {createMutation.isPending ? 'Creating…' : 'Create agent'}
+ </Button>
+ </div>
+ </form>
+ )
+}
diff --git a/web/src/components/status-badge.tsx b/web/src/components/status-badge.tsx
index 35da2945..cb6fce7d 100644
--- a/web/src/components/status-badge.tsx
+++ b/web/src/components/status-badge.tsx
@@ -38,7 +38,39 @@ const STATUS: Record<string, Meta> = {
awaiting_input: { tone: 'pending', label: 'Awaiting input', icon: Clock },
pending: { tone: 'pending', label: 'Pending', icon: Clock },
queued: { tone: 'pending', label: 'Queued', icon: Clock },
+ accepted: { tone: 'pending', label: 'Queued', icon: Clock },
+ fetching: { tone: 'pending', label: 'Fetching', icon: Loader2, spin: true },
+ validating: {
+ tone: 'pending',
+ label: 'Validating',
+ icon: Loader2,
+ spin: true,
+ },
+ installing: {
+ tone: 'pending',
+ label: 'Installing',
+ icon: Loader2,
+ spin: true,
+ },
building: { tone: 'pending', label: 'Building', icon: Loader2, spin: true },
+ uploading: {
+ tone: 'pending',
+ label: 'Publishing artifact',
+ icon: Loader2,
+ spin: true,
+ },
+ deploying: {
+ tone: 'pending',
+ label: 'Deploying',
+ icon: Loader2,
+ spin: true,
+ },
+ verifying: {
+ tone: 'pending',
+ label: 'Verifying',
+ icon: Loader2,
+ spin: true,
+ },
processing: {
tone: 'pending',
label: 'Processing',
@@ -50,6 +82,8 @@ const STATUS: Record<string, Meta> = {
deleting: { tone: 'pending', label: 'Deleting', icon: Loader2, spin: true },
error: { tone: 'error', label: 'Error', icon: CircleAlert },
failed: { tone: 'error', label: 'Failed', icon: CircleAlert },
+ superseded: { tone: 'stopped', label: 'Superseded', icon: CircleSlash },
+ skipped: { tone: 'stopped', label: 'Skipped', icon: CircleSlash },
degraded: { tone: 'error', label: 'Degraded', icon: CircleAlert },
// Webhook delivery statuses
delivered: { tone: 'running', label: 'Delivered', icon: CircleCheck },
@@ -91,7 +125,10 @@ export function StatusBadge({
)}
>
<Icon
- className={cn('size-3.5', meta.spin && 'animate-spin')}
+ className={cn(
+ 'size-3.5',
+ meta.spin && 'animate-spin motion-reduce:animate-none',
+ )}
aria-hidden
/>
{label ?? meta.label}
diff --git a/web/src/pages/AgentDeployment.tsx b/web/src/pages/AgentDeployment.tsx
new file mode 100644
index 00000000..4029e067
--- /dev/null
+++ b/web/src/pages/AgentDeployment.tsx
@@ -0,0 +1,646 @@
+import { Fragment, useEffect } from 'react'
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { Link, useParams } from 'react-router-dom'
+import {
+ ArrowLeft,
+ ArrowRight,
+ Check,
+ Circle,
+ CircleAlert,
+ Clock,
+ ExternalLink,
+ GitCommitHorizontal,
+ Loader2,
+} from 'lucide-react'
+import {
+ getAgent,
+ getAgentDeployment,
+ getAgentDeploymentLogs,
+ type AgentDeployment,
+ type AgentDeploymentLog,
+} from '@/api/client'
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
+import { Button } from '@/components/ui/button'
+import { Skeleton } from '@/components/ui/skeleton'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { StatusBadge } from '@/components/status-badge'
+import { cn } from '@/lib/utils'
+
+const PHASES = [
+ { label: 'Source', states: ['fetching', 'validating'] },
+ { label: 'Install', states: ['installing'] },
+ { label: 'Build', states: ['building'] },
+ { label: 'Artifact', states: ['uploading'] },
+ { label: 'Deploy', states: ['deploying'] },
+ { label: 'Verify', states: ['verifying'] },
+] as const
+
+function errorMessage(deployment: AgentDeployment): string | undefined {
+ if (deployment.error?.message) return deployment.error.message
+ return undefined
+}
+
+function failedPhase(deployment: AgentDeployment): string | undefined {
+ const phase = deployment.error?.phase?.toLowerCase()
+ if (phase) return phase
+ const errorClass = deployment.error_class?.toLowerCase() ?? ''
+ return PHASES.find(({ states, label }) =>
+ [...states, label.toLowerCase()].some((state) =>
+ errorClass.includes(state),
+ ),
+ )?.label.toLowerCase()
+}
+
+function phaseIndex(deployment: AgentDeployment): number {
+ if (deployment.state === 'ready') return PHASES.length
+ const state =
+ deployment.state === 'failed'
+ ? failedPhase(deployment)
+ : deployment.phase.toLowerCase()
+ return PHASES.findIndex(
+ ({ label, states }) =>
+ label.toLowerCase() === state || states.some((item) => item === state),
+ )
+}
+
+function DeploymentPhases({ deployment }: { deployment: AgentDeployment }) {
+ const current = phaseIndex(deployment)
+ const failed = deployment.state === 'failed'
+ const queued =
+ deployment.state === 'accepted' || deployment.state === 'queued'
+ const terminalWithoutPhase = failed && current < 0
+ const allDone = deployment.state === 'ready'
+
+ return (
+ <div>
+ {queued ? (
+ <p className="text-status-pending mb-4 flex items-center gap-1.5 text-sm font-medium">
+ <Clock className="size-4" aria-hidden />
+ Queued
+ <span className="text-muted-foreground font-normal">
+ Waiting for the build worker.
+ </span>
+ </p>
+ ) : null}
+ <ol
+ className="grid grid-cols-3 gap-y-4 sm:grid-cols-6"
+ aria-label="Deployment phases"
+ >
+ {PHASES.map((phase, index) => {
+ const done = allDone || (current >= 0 && index < current)
+ const active = !allDone && index === current
+ const phaseFailed = active && failed
+ const Icon = phaseFailed
+ ? CircleAlert
+ : done
+ ? Check
+ : active
+ ? Loader2
+ : Circle
+ return (
+ <li
+ key={phase.label}
+ className={cn(
+ 'relative flex flex-col items-center gap-2 text-center',
+ index > 0 &&
+ "before:bg-border before:absolute before:top-3.5 before:right-1/2 before:h-px before:w-full before:-translate-x-3.5 before:content-['']",
+ index === 3 && 'before:hidden sm:before:block',
+ )}
+ >
+ <span
+ className={cn(
+ 'bg-panel relative z-10 flex size-7 items-center justify-center rounded-full border',
+ phaseFailed
+ ? 'border-status-error text-status-error'
+ : done || active
+ ? 'border-status-running text-status-running'
+ : 'text-muted-foreground border-border',
+ )}
+ >
+ <Icon
+ className={cn(
+ 'size-3.5',
+ active &&
+ !failed &&
+ 'animate-spin motion-reduce:animate-none',
+ )}
+ aria-hidden
+ />
+ </span>
+ <span
+ className={cn(
+ 'text-xs',
+ active || done ? 'text-foreground' : 'text-muted-foreground',
+ )}
+ >
+ {phase.label}
+ {active ? (
+ <span className="sr-only">
+ {phaseFailed ? ', failed' : ', in progress'}
+ </span>
+ ) : done ? (
+ <span className="sr-only">, complete</span>
+ ) : (
+ <span className="sr-only">, pending</span>
+ )}
+ </span>
+ </li>
+ )
+ })}
+ </ol>
+ {terminalWithoutPhase ? (
+ <p className="text-status-error mt-4 flex items-center gap-1.5 text-xs">
+ <CircleAlert className="size-3.5" aria-hidden />
+ The deployment failed before a phase was recorded.
+ </p>
+ ) : null}
+ </div>
+ )
+}
+
+function formatDate(value: string | null | undefined): string {
+ if (!value) return 'Not recorded'
+ const date = new Date(value)
+ return Number.isNaN(date.getTime()) ? value : date.toLocaleString()
+}
+
+function formatDuration(deployment: AgentDeployment): string {
+ if (deployment.timing.total_ms != null) {
+ return formatMilliseconds(deployment.timing.total_ms)
+ }
+ const start = new Date(
+ deployment.started_at ?? deployment.created_at,
+ ).getTime()
+ const end = deployment.finished_at
+ ? new Date(deployment.finished_at).getTime()
+ : deployment.terminal
+ ? new Date(deployment.updated_at).getTime()
+ : Date.now()
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end < start)
+ return 'Not available'
+ return formatMilliseconds(end - start)
+}
+
+function formatMilliseconds(milliseconds: number): string {
+ const seconds = Math.max(0, Math.round(milliseconds / 1000))
+ if (seconds < 60) return `${seconds}s`
+ const minutes = Math.floor(seconds / 60)
+ return `${minutes}m ${seconds % 60}s`
+}
+
+function formatBytes(value: number | undefined): string {
+ if (value === undefined) return 'Not available'
+ if (value < 1024) return `${value} B`
+ if (value < 1024 * 1024) return `${(value / 1024).toFixed(1)} KiB`
+ return `${(value / 1024 / 1024).toFixed(1)} MiB`
+}
+
+function Outcome({ deployment }: { deployment: AgentDeployment }) {
+ if (deployment.state === 'ready') {
+ return (
+ <Alert className="bg-status-running-bg text-status-running border-status-running/25">
+ <Check className="size-4" />
+ <AlertTitle>Deployment ready</AlertTitle>
+ <AlertDescription className="text-status-running">
+ {deployment.revision?.number
+ ? `Revision #${deployment.revision.number} is ready to run.`
+ : 'The agent passed verification and is ready to run.'}
+ </AlertDescription>
+ </Alert>
+ )
+ }
+
+ if (deployment.state === 'failed') {
+ return (
+ <Alert variant="destructive">
+ <CircleAlert className="size-4" />
+ <AlertTitle>
+ {deployment.live_touched
+ ? 'Live deployment could not be verified'
+ : 'Deployment failed'}
+ </AlertTitle>
+ <AlertDescription>
+ {errorMessage(deployment) ??
+ (deployment.live_touched
+ ? 'The live Worker may have changed. Check the persisted log before starting new work.'
+ : 'The live agent was not changed. Check the persisted log and fix the repository before deploying again.')}
+ </AlertDescription>
+ </Alert>
+ )
+ }
+
+ if (
+ deployment.state === 'canceled' ||
+ deployment.state === 'superseded' ||
+ deployment.state === 'skipped'
+ ) {
+ return (
+ <Alert>
+ <AlertTitle>
+ {deployment.state === 'skipped'
+ ? 'No changes to deploy'
+ : deployment.state === 'canceled'
+ ? 'Deployment canceled'
+ : 'Deployment superseded'}
+ </AlertTitle>
+ <AlertDescription>
+ {deployment.state === 'skipped'
+ ? 'The built result matches the active revision, so the live agent was left unchanged.'
+ : 'This attempt ended without producing a new revision.'}
+ </AlertDescription>
+ </Alert>
+ )
+ }
+
+ return (
+ <Alert>
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ <AlertTitle>Deployment in progress</AlertTitle>
+ <AlertDescription>
+ This page polls the durable deployment record and build log.
+ </AlertDescription>
+ </Alert>
+ )
+}
+
+function DeploymentLog({
+ logs,
+ terminal,
+}: {
+ logs: AgentDeploymentLog[]
+ terminal: boolean
+}) {
+ if (!logs.length) {
+ return (
+ <div className="text-code-muted bg-code flex min-h-52 items-center justify-center rounded-md px-4 py-8 font-mono text-xs">
+ {terminal
+ ? 'No build output was recorded.'
+ : 'Waiting for build output…'}
+ </div>
+ )
+ }
+
+ return (
+ <div
+ className="bg-code text-code-foreground max-h-[32rem] overflow-auto rounded-md py-3 font-mono text-xs"
+ aria-label="Build and deploy log"
+ >
+ {logs.map((entry, index) => {
+ const phaseChanged =
+ index === 0 || entry.phase !== logs[index - 1]?.phase
+ return (
+ <Fragment key={entry.seq}>
+ {phaseChanged ? (
+ <div className="text-code-muted border-code-border mt-2 border-y px-4 py-1.5 first:mt-0">
+ {entry.phase}
+ </div>
+ ) : null}
+ <div className="grid grid-cols-[3rem_4.5rem_minmax(0,1fr)] gap-2 px-4 py-0.5">
+ <span className="text-code-muted text-right select-none">
+ {entry.seq}
+ </span>
+ <span
+ className={cn(
+ 'select-none',
+ entry.stream === 'stderr'
+ ? 'text-red-300'
+ : 'text-code-muted',
+ )}
+ >
+ {entry.stream}
+ </span>
+ <span className="min-w-0 break-words whitespace-pre-wrap">
+ {entry.chunk}
+ </span>
+ </div>
+ </Fragment>
+ )
+ })}
+ </div>
+ )
+}
+
+function Metadata({ deployment }: { deployment: AgentDeployment }) {
+ const build = deployment.build
+ const items = [
+ [
+ 'Root',
+ build?.root ?? deployment.source_relation?.path ?? 'Repository root',
+ ],
+ ['Node', build?.node ?? 'Not recorded'],
+ ['npm', build?.npm ?? 'Not recorded'],
+ [
+ 'Lockfile',
+ build?.lockfile_version !== undefined
+ ? `version ${build.lockfile_version}`
+ : 'Not recorded',
+ ],
+ ['Builder', build?.builder ?? 'Not recorded'],
+ ['Snapshot', build?.snapshot ?? 'Not recorded'],
+ ['Artifact', build?.artifact_digest ?? 'Not available'],
+ ['Artifact size', formatBytes(build?.artifact_bytes)],
+ [
+ 'Source',
+ build?.source_files !== undefined && build.source_bytes !== undefined
+ ? `${build.source_files.toLocaleString()} files · ${formatBytes(build.source_bytes)}`
+ : 'Not recorded',
+ ],
+ ['Infrastructure attempts', String(build?.attempts ?? 1)],
+ ['Flue entrypoint', deployment.configuration?.entrypoint ?? 'Not recorded'],
+ ['Model', deployment.configuration?.model ?? 'Not recorded'],
+ ]
+ return (
+ <dl className="grid gap-x-8 gap-y-4 sm:grid-cols-2">
+ {items.map(([label, value]) => (
+ <div key={label} className="min-w-0">
+ <dt className="text-muted-foreground text-xs">{label}</dt>
+ <dd className="mt-1 truncate font-mono text-sm" title={value}>
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ )
+}
+
+export default function AgentDeployment() {
+ const { agentId = '', deploymentId = '' } = useParams()
+ const queryClient = useQueryClient()
+ const deploymentQuery = useQuery({
+ queryKey: ['agent-deployment', agentId, deploymentId],
+ queryFn: () => getAgentDeployment(agentId, deploymentId),
+ enabled: !!agentId && !!deploymentId,
+ refetchInterval: (query) => (query.state.data?.terminal ? false : 1500),
+ })
+ const { data: agent } = useQuery({
+ queryKey: ['agent', agentId],
+ queryFn: () => getAgent(agentId),
+ enabled: !!agentId,
+ })
+ const logQueryKey = ['agent-deployment-logs', agentId, deploymentId] as const
+ const logsQuery = useQuery({
+ queryKey: logQueryKey,
+ queryFn: async () => {
+ const previous = queryClient.getQueryData<{
+ data: AgentDeploymentLog[]
+ cursor: string | null
+ }>(logQueryKey)
+ const data = previous?.data ? [...previous.data] : []
+ const seen = new Set(data.map((entry) => entry.cursor))
+ let cursor = previous?.cursor ?? null
+ let hasMore = false
+ do {
+ const page = await getAgentDeploymentLogs(agentId, deploymentId, {
+ after: cursor ?? undefined,
+ limit: 500,
+ })
+ for (const entry of page.data) {
+ if (!seen.has(entry.cursor)) {
+ seen.add(entry.cursor)
+ data.push(entry)
+ }
+ }
+ const nextCursor = page.next_cursor
+ hasMore = page.has_more && !!nextCursor && nextCursor !== cursor
+ if (nextCursor) cursor = nextCursor
+ } while (hasMore)
+ return { data, cursor }
+ },
+ enabled: !!agentId && !!deploymentId,
+ refetchInterval: deploymentQuery.data?.terminal ? false : 1500,
+ })
+
+ const terminal = deploymentQuery.data?.terminal ?? false
+ const refetchLogs = logsQuery.refetch
+ useEffect(() => {
+ if (terminal) void refetchLogs()
+ // One final durable read when the deployment terminalizes.
+ }, [terminal, refetchLogs])
+
+ if (deploymentQuery.isLoading) {
+ return (
+ <div className="space-y-5">
+ <Skeleton className="h-5 w-40" />
+ <Skeleton className="h-20 w-full" />
+ <Skeleton className="h-44 w-full" />
+ </div>
+ )
+ }
+
+ if (deploymentQuery.isError || !deploymentQuery.data) {
+ return (
+ <div className="space-y-5">
+ <Button variant="ghost" size="sm" asChild>
+ <Link to={`/agents/${agentId}`}>
+ <ArrowLeft className="size-4" />
+ Back to agent
+ </Link>
+ </Button>
+ <Alert variant="destructive">
+ <AlertTitle>Deployment could not be loaded</AlertTitle>
+ <AlertDescription>
+ {deploymentQuery.error instanceof Error
+ ? deploymentQuery.error.message
+ : 'Check that the deployment exists and belongs to this agent.'}
+ </AlertDescription>
+ </Alert>
+ </div>
+ )
+ }
+
+ const deployment = deploymentQuery.data
+ const repo = deployment.source_relation?.repo?.full_name ?? undefined
+ const root = deployment.source_relation?.path ?? undefined
+ const ref =
+ deployment.source_relation?.ref ??
+ deployment.source_relation?.production_ref ??
+ deployment.ref ??
+ undefined
+ const sha = deployment.source_relation?.sha ?? deployment.sha ?? undefined
+ const commitUrl = deployment.source_relation?.commit_url ?? undefined
+ const trigger =
+ deployment.actor?.kind === 'ci'
+ ? 'GitHub push'
+ : deployment.actor?.kind === 'agent'
+ ? 'Agent'
+ : deployment.input_type === 'github'
+ ? 'Dashboard import'
+ : 'Dashboard'
+ const canViewCommit =
+ deployment.allowed_actions.includes('view_commit') && !!commitUrl
+ const canOpenAgent = deployment.allowed_actions.includes('open_agent')
+ const canStartSession = deployment.allowed_actions.includes('start_session')
+
+ return (
+ <div className="space-y-5">
+ <div>
+ <Link
+ to={`/agents/${agentId}`}
+ className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"
+ >
+ <ArrowLeft className="size-4" />
+ {agent?.name ? `Back to ${agent.name}` : 'Back to agent'}
+ </Link>
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
+ <div>
+ <div className="flex flex-wrap items-center gap-2">
+ <h1 className="text-xl font-semibold tracking-tight">
+ Deployment
+ </h1>
+ <StatusBadge status={deployment.state} />
+ </div>
+ <p className="text-muted-foreground mt-1 font-mono text-xs">
+ {deployment.id}
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ {canViewCommit ? (
+ <Button variant="outline" size="sm" asChild>
+ <a href={commitUrl} target="_blank" rel="noreferrer">
+ <GitCommitHorizontal className="size-4" />
+ View commit
+ <ExternalLink className="size-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ {canOpenAgent ? (
+ <Button variant="outline" size="sm" asChild>
+ <Link to={`/agents/${agentId}`}>Open agent</Link>
+ </Button>
+ ) : null}
+ {canStartSession ? (
+ <Button size="sm" asChild>
+ <Link to={`/agents/${agentId}/sessions`}>
+ Start session
+ <ArrowRight className="size-4" />
+ </Link>
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ </div>
+
+ <Outcome deployment={deployment} />
+
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Progress</PanelTitle>
+ <PanelDescription className="mt-1" aria-live="polite">
+ Current state: {deployment.state.replace(/_/g, ' ')}
+ </PanelDescription>
+ </div>
+ {!terminal ? (
+ <span className="text-muted-foreground flex items-center gap-1.5 text-xs">
+ <Clock className="size-3.5" />
+ {formatDuration(deployment)}
+ </span>
+ ) : null}
+ </PanelHeader>
+ <PanelContent>
+ <DeploymentPhases deployment={deployment} />
+ </PanelContent>
+ </Panel>
+
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Build and deploy log</PanelTitle>
+ <PanelDescription className="mt-1">
+ Persisted output from source, install, build, and deployment.
+ </PanelDescription>
+ </div>
+ {deployment.log_truncated ? (
+ <span className="text-status-pending text-xs">
+ Output truncated
+ </span>
+ ) : null}
+ </PanelHeader>
+ <PanelContent>
+ {logsQuery.isError ? (
+ <Alert variant="destructive">
+ <AlertTitle>Log could not be loaded</AlertTitle>
+ <AlertDescription>
+ The deployment record is still available. Retry this durable log
+ read.
+ </AlertDescription>
+ <div className="mt-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void logsQuery.refetch()}
+ >
+ Retry log
+ </Button>
+ </div>
+ </Alert>
+ ) : logsQuery.isLoading ? (
+ <Skeleton className="h-52 w-full" />
+ ) : (
+ <DeploymentLog
+ logs={logsQuery.data?.data ?? []}
+ terminal={deployment.terminal}
+ />
+ )}
+ </PanelContent>
+ </Panel>
+
+ <div className="grid gap-5 lg:grid-cols-2">
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>Build metadata</PanelTitle>
+ </PanelHeader>
+ <PanelContent>
+ <Metadata deployment={deployment} />
+ </PanelContent>
+ </Panel>
+
+ <Panel>
+ <PanelHeader>
+ <PanelTitle>Source and result</PanelTitle>
+ </PanelHeader>
+ <PanelContent>
+ <dl className="grid gap-y-4">
+ {[
+ ['Repository', repo ?? 'Not recorded'],
+ ['Root', root || 'Repository root'],
+ ['Branch', ref ?? 'Not recorded'],
+ ['Commit', sha ?? 'Not recorded'],
+ ['Trigger', trigger],
+ ['Accepted', formatDate(deployment.created_at)],
+ ['Started', formatDate(deployment.started_at)],
+ ['Finished', formatDate(deployment.finished_at)],
+ ['Duration', formatDuration(deployment)],
+ [
+ 'Revision',
+ deployment.revision?.number
+ ? `#${deployment.revision.number}${deployment.active ? ' · Active' : ''}`
+ : 'None',
+ ],
+ ].map(([label, value]) => (
+ <div
+ key={label}
+ className="grid gap-1 sm:grid-cols-[7rem_minmax(0,1fr)] sm:gap-3"
+ >
+ <dt className="text-muted-foreground text-xs">{label}</dt>
+ <dd
+ className="truncate font-mono text-xs sm:text-right"
+ title={value}
+ >
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </PanelContent>
+ </Panel>
+ </div>
+ </div>
+ )
+}
diff --git a/web/src/pages/AgentNew.tsx b/web/src/pages/AgentNew.tsx
new file mode 100644
index 00000000..c0fcf324
--- /dev/null
+++ b/web/src/pages/AgentNew.tsx
@@ -0,0 +1,699 @@
+import { useMemo, useRef, useState } from 'react'
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { Link, useNavigate, useSearchParams } from 'react-router-dom'
+import {
+ ArrowLeft,
+ ArrowRight,
+ Bot,
+ ExternalLink,
+ GitBranch,
+ KeyRound,
+ Loader2,
+ Search,
+} from 'lucide-react'
+import {
+ getDeployApp,
+ importAgentFromGithub,
+ inspectFlueRepository,
+ type FlueSourceInspection,
+} from '@/api/client'
+import { Field, FieldError, Input } from '@/components/form'
+import { GithubMark } from '@/components/github-mark'
+import { ManualAgentForm } from '@/components/manual-agent-form'
+import {
+ Panel,
+ PanelContent,
+ PanelDescription,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
+import { Badge } from '@/components/ui/badge'
+import { Skeleton } from '@/components/ui/skeleton'
+import { cn } from '@/lib/utils'
+
+const STARTER_URL = 'https://github.com/diggerhq/oc-flue-starter'
+const STARTER_FORK_URL = `${STARTER_URL}/fork`
+const IMPORT_COMMAND_STORAGE = 'oc.flue-import-command.v1'
+
+type ImportBody = Parameters<typeof importAgentFromGithub>[0]
+type ImportCommand = { fingerprint: string; key: string }
+
+function isValidRoot(root: string): boolean {
+ if (root.includes('\0') || root.includes('\\') || root.startsWith('/'))
+ return false
+ return !root
+ .split('/')
+ .filter(Boolean)
+ .some((part) => part === '.' || part === '..')
+}
+
+function newCommandKey(): string {
+ return (
+ globalThis.crypto?.randomUUID?.() ??
+ `import-${Date.now()}-${Math.random().toString(36).slice(2)}`
+ )
+}
+
+function stableCommandKey(
+ fingerprint: string,
+ memory: { current: ImportCommand | null },
+): string {
+ if (memory.current?.fingerprint === fingerprint) return memory.current.key
+
+ try {
+ const stored = window.sessionStorage.getItem(IMPORT_COMMAND_STORAGE)
+ if (stored) {
+ const parsed = JSON.parse(stored) as Partial<ImportCommand>
+ if (parsed.fingerprint === fingerprint && parsed.key) {
+ memory.current = { fingerprint, key: parsed.key }
+ return parsed.key
+ }
+ }
+ } catch {
+ // Storage can be unavailable in privacy-restricted browser contexts.
+ }
+
+ const key = newCommandKey()
+ memory.current = { fingerprint, key }
+ try {
+ window.sessionStorage.setItem(
+ IMPORT_COMMAND_STORAGE,
+ JSON.stringify({ fingerprint, key }),
+ )
+ } catch {
+ // The in-memory key still makes repeated submits stable for this page load.
+ }
+ return key
+}
+
+function shortSha(sha: string): string {
+ return sha.slice(0, 7)
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KiB`
+ return `${(bytes / 1024 / 1024).toFixed(1)} MiB`
+}
+
+function ModeButton({
+ active,
+ onClick,
+ icon: Icon,
+ title,
+ description,
+}: {
+ active: boolean
+ onClick: () => void
+ icon: typeof GithubMark | typeof Bot
+ title: string
+ description: string
+}) {
+ return (
+ <button
+ type="button"
+ aria-pressed={active}
+ onClick={onClick}
+ className={cn(
+ 'focus-visible:ring-ring/50 flex min-w-0 flex-1 items-start gap-3 rounded-md px-3 py-2.5 text-left transition-colors outline-none focus-visible:ring-3',
+ active ? 'bg-foreground text-background' : 'hover:bg-muted',
+ )}
+ >
+ <Icon className="mt-0.5 size-4 shrink-0" aria-hidden />
+ <span className="min-w-0">
+ <span className="block text-sm font-medium">{title}</span>
+ <span
+ className={cn(
+ 'mt-0.5 block text-xs',
+ active ? 'text-background/80' : 'text-muted-foreground',
+ )}
+ >
+ {description}
+ </span>
+ </span>
+ </button>
+ )
+}
+
+function DetectedAgent({ inspection }: { inspection: FlueSourceInspection }) {
+ const rows = [
+ ['Flue entrypoint', inspection.manifest.entrypoint],
+ [
+ 'Runtime',
+ `${inspection.manifest.runtime.family}/${inspection.manifest.runtime.type}`,
+ ],
+ ['Model', inspection.manifest.model],
+ ['Commit', shortSha(inspection.sha)],
+ [
+ 'Node',
+ `${inspection.package.node_engine} (builder ${inspection.builder.node})`,
+ ],
+ ['npm lockfile', `lockfileVersion ${inspection.lockfile.version}`],
+ ]
+
+ return (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Detected Flue agent</PanelTitle>
+ <PanelDescription className="mt-1">
+ Read from the exact commit without running repository code.
+ </PanelDescription>
+ </div>
+ <Badge variant="outline">{shortSha(inspection.sha)}</Badge>
+ </PanelHeader>
+ <PanelContent className="space-y-4">
+ <dl className="grid gap-x-8 gap-y-3 sm:grid-cols-2">
+ {rows.map(([label, value]) => (
+ <div key={label} className="min-w-0">
+ <dt className="text-muted-foreground text-xs">{label}</dt>
+ <dd className="mt-0.5 truncate font-mono text-sm" title={value}>
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ <div className="border-t pt-4">
+ <p className="text-muted-foreground text-xs">Source</p>
+ <p className="mt-1 text-sm">
+ {inspection.source.files.toLocaleString()} tracked files,{' '}
+ {formatBytes(inspection.source.bytes)}
+ </p>
+ </div>
+ <div className="border-t pt-4">
+ <p className="text-muted-foreground text-xs">
+ Variables from agent.toml
+ </p>
+ {inspection.variable_names.length ? (
+ <div className="mt-2 flex flex-wrap gap-1.5">
+ {inspection.variable_names.map((name) => (
+ <Badge key={name} variant="secondary" className="font-mono">
+ {name}
+ </Badge>
+ ))}
+ </div>
+ ) : (
+ <p className="mt-1 text-sm">No variables declared.</p>
+ )}
+ <p className="text-muted-foreground mt-2 text-xs">
+ Values stay in source and are not shown here.
+ </p>
+ </div>
+ </PanelContent>
+ </Panel>
+ )
+}
+
+function GithubImport() {
+ const navigate = useNavigate()
+ const queryClient = useQueryClient()
+ const importCommand = useRef<ImportCommand | null>(null)
+ const [repoSearch, setRepoSearch] = useState('')
+ const [repoId, setRepoId] = useState('')
+ const [productionRef, setProductionRef] = useState('')
+ const [root, setRoot] = useState('')
+ const [name, setName] = useState('')
+
+ const {
+ data: app,
+ isLoading,
+ isError,
+ refetch,
+ } = useQuery({
+ queryKey: ['deploy-app'],
+ queryFn: getDeployApp,
+ refetchOnWindowFocus: 'always',
+ })
+
+ const repositories = useMemo(() => {
+ const needle = repoSearch.trim().toLowerCase()
+ return (app?.repositories ?? [])
+ .filter(
+ (repo): repo is typeof repo & { id: string } =>
+ typeof repo.id === 'string' && repo.id.length > 0,
+ )
+ .filter(
+ (repo) => !needle || repo.full_name.toLowerCase().includes(needle),
+ )
+ }, [app?.repositories, repoSearch])
+
+ const selectedRepo = app?.repositories.find((repo) => repo.id === repoId)
+ const rootValid = isValidRoot(root.trim())
+
+ const inspectMutation = useMutation({
+ mutationFn: () =>
+ inspectFlueRepository({
+ repo: repoId,
+ path: root.trim(),
+ production_ref: productionRef.trim(),
+ }),
+ onSuccess: (inspection) => setName(inspection.manifest.entrypoint),
+ })
+
+ const importMutation = useMutation({
+ mutationFn: (body: ImportBody) =>
+ importAgentFromGithub(
+ body,
+ stableCommandKey(JSON.stringify(body), importCommand),
+ ),
+ onSuccess: ({ agent, deployment }) => {
+ try {
+ window.sessionStorage.removeItem(IMPORT_COMMAND_STORAGE)
+ } catch {
+ // Storage can be unavailable in privacy-restricted browser contexts.
+ }
+ void queryClient.invalidateQueries({ queryKey: ['agents'] })
+ void navigate(`/agents/${agent.id}/deployments/${deployment.id}`)
+ },
+ })
+
+ const clearInspection = () => {
+ inspectMutation.reset()
+ importMutation.reset()
+ }
+
+ const selectRepo = (id: string) => {
+ const repo = app?.repositories.find((candidate) => candidate.id === id)
+ setRepoId(id)
+ setProductionRef(repo?.default_branch || 'main')
+ setRoot('')
+ setName('')
+ clearInspection()
+ }
+
+ const inspection = inspectMutation.data
+ const canInspect =
+ !!selectedRepo &&
+ !!productionRef.trim() &&
+ rootValid &&
+ !inspectMutation.isPending
+ const canImport =
+ !!inspection &&
+ !!name.trim() &&
+ !importMutation.isPending &&
+ !inspectMutation.isPending
+
+ const deployAgent = () => {
+ if (!inspection || !canImport) return
+ importMutation.mutate({
+ name: name.trim(),
+ source: {
+ type: 'github',
+ repo: inspection.repository.id,
+ path: inspection.root,
+ production_ref: inspection.production_ref,
+ },
+ credential: 'managed',
+ })
+ }
+
+ if (isLoading) {
+ return (
+ <Panel>
+ <PanelContent className="space-y-3 py-6">
+ <Skeleton className="h-4 w-40" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-3/4" />
+ </PanelContent>
+ </Panel>
+ )
+ }
+
+ if (isError || !app) {
+ return (
+ <Alert variant="destructive">
+ <AlertTitle>GitHub connection could not be loaded</AlertTitle>
+ <AlertDescription>
+ Retry the request. No repository or agent was changed.
+ </AlertDescription>
+ <div className="mt-2">
+ <Button size="sm" variant="outline" onClick={() => void refetch()}>
+ Retry
+ </Button>
+ </div>
+ </Alert>
+ )
+ }
+
+ if (!app.installed) {
+ return (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Connect GitHub</PanelTitle>
+ <PanelDescription className="mt-1">
+ Install the OpenComputer App and choose the repositories it may
+ deploy.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <PanelContent className="space-y-3">
+ {app.install_url ? (
+ <Button asChild>
+ <a href={app.install_url} target="_blank" rel="noreferrer">
+ <GithubMark className="size-4" />
+ Install GitHub App
+ <ExternalLink className="size-3.5" />
+ </a>
+ </Button>
+ ) : (
+ <Button disabled>
+ <GithubMark className="size-4" />
+ Install GitHub App
+ </Button>
+ )}
+ <p className="text-muted-foreground max-w-xl text-sm">
+ {app.install_url
+ ? 'GitHub opens in a new tab. Return here after installation; this page refreshes the repository list when it regains focus.'
+ : 'The installation link is unavailable. Refresh this page or contact support.'}
+ </p>
+ </PanelContent>
+ </Panel>
+ )
+ }
+
+ return (
+ <div className="space-y-5">
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Choose repository</PanelTitle>
+ <PanelDescription className="mt-1">
+ {app.account
+ ? `Repositories available to the OpenComputer App for ${app.account}.`
+ : 'Repositories available to the OpenComputer App.'}
+ </PanelDescription>
+ </div>
+ {app.configure_url ? (
+ <Button variant="ghost" size="sm" asChild>
+ <a href={app.configure_url} target="_blank" rel="noreferrer">
+ Add repositories
+ <ExternalLink className="size-3.5" />
+ </a>
+ </Button>
+ ) : null}
+ </PanelHeader>
+ <PanelContent className="space-y-4">
+ <div className="relative">
+ <Search
+ className="text-muted-foreground pointer-events-none absolute top-2 left-2.5 size-4"
+ aria-hidden
+ />
+ <Input
+ value={repoSearch}
+ onChange={(event) => setRepoSearch(event.target.value)}
+ placeholder="Search repositories"
+ aria-label="Search repositories"
+ className="pl-8"
+ />
+ </div>
+ <div
+ role="group"
+ aria-label="Repository"
+ className="max-h-60 overflow-y-auto rounded-md border"
+ >
+ {repositories.length ? (
+ repositories.map((repo, index) => (
+ <button
+ key={repo.id}
+ type="button"
+ aria-pressed={repo.id === repoId}
+ onClick={() => selectRepo(repo.id)}
+ className={cn(
+ 'focus-visible:ring-ring/50 flex w-full items-center gap-3 px-3 py-2.5 text-left outline-none focus-visible:ring-3 focus-visible:ring-inset',
+ index > 0 && 'border-t',
+ repo.id === repoId
+ ? 'bg-row-selected'
+ : 'hover:bg-row-hover',
+ )}
+ >
+ <GithubMark className="size-4 shrink-0" />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">
+ {repo.full_name}
+ </span>
+ <span className="text-muted-foreground flex shrink-0 items-center gap-2 text-xs">
+ {repo.private == null
+ ? null
+ : repo.private
+ ? 'Private'
+ : 'Public'}
+ {repo.default_branch ? (
+ <span className="hidden items-center gap-1 sm:flex">
+ <GitBranch className="size-3" />
+ {repo.default_branch}
+ </span>
+ ) : null}
+ </span>
+ </button>
+ ))
+ ) : (
+ <p className="text-muted-foreground px-4 py-8 text-center text-sm">
+ {app.repositories.length === 0
+ ? 'No repositories are available to this installation.'
+ : app.repositories.some((repo) => repo.id)
+ ? 'No repositories match this search.'
+ : 'Repository registration is still syncing. Return to this page in a moment.'}
+ </p>
+ )}
+ </div>
+
+ {selectedRepo ? (
+ <div className="grid gap-4 border-t pt-4 sm:grid-cols-2">
+ <Field
+ label="Production branch"
+ htmlFor="import-branch"
+ description="The branch to resolve for this deployment."
+ >
+ <Input
+ id="import-branch"
+ value={productionRef}
+ onChange={(event) => {
+ setProductionRef(event.target.value)
+ clearInspection()
+ }}
+ placeholder="main"
+ />
+ </Field>
+ <Field
+ label="Root directory"
+ htmlFor="import-root"
+ error={
+ rootValid
+ ? undefined
+ : 'Use a repository-relative path without . or .. segments.'
+ }
+ description="Leave empty when agent.toml is at repository root."
+ >
+ <Input
+ id="import-root"
+ value={root}
+ onChange={(event) => {
+ setRoot(event.target.value)
+ clearInspection()
+ }}
+ placeholder="agents/support"
+ aria-invalid={!rootValid}
+ />
+ </Field>
+ </div>
+ ) : null}
+
+ {inspectMutation.isError ? (
+ <FieldError>
+ {inspectMutation.error instanceof Error
+ ? inspectMutation.error.message
+ : 'Repository inspection failed.'}
+ </FieldError>
+ ) : null}
+
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={!canInspect}
+ onClick={() => inspectMutation.mutate()}
+ >
+ {inspectMutation.isPending ? (
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ ) : null}
+ {inspectMutation.isPending
+ ? 'Inspecting repository…'
+ : inspection
+ ? 'Inspect again'
+ : 'Inspect repository'}
+ </Button>
+ </div>
+ </PanelContent>
+ </Panel>
+
+ {inspection ? <DetectedAgent inspection={inspection} /> : null}
+
+ {inspection?.warnings.map((warning) => (
+ <Alert key={`${warning.code}:${warning.message}`}>
+ <AlertTitle>Compatibility warning</AlertTitle>
+ <AlertDescription>{warning.message}</AlertDescription>
+ </Alert>
+ ))}
+
+ {inspection ? (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Name and deploy</PanelTitle>
+ <PanelDescription className="mt-1">
+ The OpenComputer name can differ from the Flue entrypoint.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <PanelContent className="space-y-5">
+ <Field
+ label="Agent name"
+ htmlFor="import-agent-name"
+ description={`Flue entrypoint: ${inspection.manifest.entrypoint}`}
+ >
+ <Input
+ id="import-agent-name"
+ value={name}
+ onChange={(event) => {
+ setName(event.target.value)
+ importMutation.reset()
+ }}
+ placeholder="Support triage"
+ />
+ </Field>
+ <div className="bg-panel-2 flex items-start gap-3 rounded-md p-3">
+ <KeyRound
+ className="text-muted-foreground mt-0.5 size-4 shrink-0"
+ aria-hidden
+ />
+ <div>
+ <p className="text-sm font-medium">Managed credential</p>
+ <p className="text-muted-foreground mt-0.5 text-xs">
+ OpenComputer provides model access for{' '}
+ <code className="font-mono">{inspection.manifest.model}</code>
+ . No provider key is added to the build environment.
+ </p>
+ </div>
+ </div>
+ {importMutation.isError ? (
+ <Alert variant="destructive">
+ <AlertTitle>Agent could not be created</AlertTitle>
+ <AlertDescription>
+ {importMutation.error instanceof Error
+ ? importMutation.error.message
+ : 'The import request failed. You can retry without creating a duplicate.'}
+ </AlertDescription>
+ </Alert>
+ ) : null}
+ <div className="flex justify-end">
+ <Button disabled={!canImport} onClick={deployAgent}>
+ {importMutation.isPending ? (
+ <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
+ ) : (
+ <ArrowRight className="size-4" />
+ )}
+ {importMutation.isPending
+ ? 'Creating deployment…'
+ : 'Deploy agent'}
+ </Button>
+ </div>
+ </PanelContent>
+ </Panel>
+ ) : null}
+ </div>
+ )
+}
+
+export default function AgentNew() {
+ const [searchParams, setSearchParams] = useSearchParams()
+ const mode = searchParams.get('mode') === 'manual' ? 'manual' : 'github'
+ const setMode = (next: 'github' | 'manual') =>
+ setSearchParams(next === 'github' ? {} : { mode: 'manual' }, {
+ replace: true,
+ })
+
+ return (
+ <div className="mx-auto max-w-4xl">
+ <Link
+ to="/agents"
+ className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"
+ >
+ <ArrowLeft className="size-4" />
+ Back to agents
+ </Link>
+
+ <div className="mb-6">
+ <h1 className="text-xl font-semibold tracking-tight">Create agent</h1>
+ <p className="text-muted-foreground mt-1 text-sm">
+ Deploy an existing Flue repository or configure an agent manually.
+ </p>
+ </div>
+
+ <div className="bg-muted mb-6 flex flex-col gap-1 rounded-lg p-1 sm:flex-row">
+ <ModeButton
+ active={mode === 'github'}
+ onClick={() => setMode('github')}
+ icon={GithubMark}
+ title="Import from GitHub"
+ description="Build and deploy an existing Flue agent."
+ />
+ <ModeButton
+ active={mode === 'manual'}
+ onClick={() => setMode('manual')}
+ icon={Bot}
+ title="Configure manually"
+ description="Create a built-in runtime agent from a prompt."
+ />
+ </div>
+
+ {mode === 'github' ? (
+ <GithubImport />
+ ) : (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Configure manually</PanelTitle>
+ <PanelDescription className="mt-1">
+ Sessions pin a snapshot of this definition when they are
+ created.
+ </PanelDescription>
+ </div>
+ </PanelHeader>
+ <PanelContent>
+ <ManualAgentForm onCancel={() => setMode('github')} />
+ </PanelContent>
+ </Panel>
+ )}
+
+ <section className="mt-8 border-t pt-6" aria-labelledby="starter-heading">
+ <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
+ <div className="max-w-xl">
+ <h2 id="starter-heading" className="text-sm font-semibold">
+ Need a starting point?
+ </h2>
+ <p className="text-muted-foreground mt-1 text-sm">
+ Fork the Flue starter, add your agent logic, then return here to
+ deploy it.
+ </p>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" size="sm" asChild>
+ <a href={STARTER_URL} target="_blank" rel="noreferrer">
+ View repository
+ <ExternalLink className="size-3.5" />
+ </a>
+ </Button>
+ <Button variant="outline" size="sm" asChild>
+ <a href={STARTER_FORK_URL} target="_blank" rel="noreferrer">
+ Fork on GitHub
+ <ExternalLink className="size-3.5" />
+ </a>
+ </Button>
+ </div>
+ </div>
+ </section>
+ </div>
+ )
+}
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
index 419c3d1a..948c5d0f 100644
--- a/web/src/pages/Agents.tsx
+++ b/web/src/pages/Agents.tsx
@@ -1,228 +1,43 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
+import { useQuery } from '@tanstack/react-query'
import { useNavigate } from 'react-router-dom'
import { Bot, Plus } from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import {
- getAgents,
- createAgent,
- getCredentials,
- createCredential,
- type Agent,
-} from '@/api/client'
+import { getAgents, type Agent } from '@/api/client'
+import { EmptyState } from '@/components/empty-state'
import { PageHeader } from '@/components/page-header'
import { Panel } from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog'
-import { Field, Input, Select, Textarea } from '@/components/form'
-import { EmptyState } from '@/components/empty-state'
import { ResourceTable, type Column } from '@/components/resource-table'
-import {
- DEFAULT_RUNTIME,
- defaultModelFor,
- getRuntime,
- keyFieldFor,
- providerForModel,
- runtimeOptions,
- withModelGroups,
-} from '@/lib/runtimes'
-
-// Sentinels for the non-credential choices in the credential picker. The model
-// list + credential provider both follow the chosen runtime (see @/lib/runtimes).
-const NEW_CRED = '__new__'
-// "Managed" model access: run via OpenComputer with no BYO key. Billing varies by org
-// (Autumn → credits; otherwise a fixed OpenRouter key cap), so the label stays neutral.
-// Sent to the API as the reserved credential value "managed" (token-billing §6.6).
-const MANAGED = 'managed'
-
-// Friendly starting defaults so "Create agent" works with a single click: a memorable
-// random name (adjective-noun) + a usable general-purpose prompt the user can keep or edit.
-const NAME_ADJECTIVES = [
- 'swift', 'calm', 'bright', 'clever', 'bold', 'quiet', 'keen', 'brave',
- 'nimble', 'sunny', 'lucid', 'witty', 'deft', 'mellow', 'crisp', 'vivid',
-]
-const NAME_NOUNS = [
- 'otter', 'harbor', 'falcon', 'cedar', 'comet', 'delta', 'ember', 'fjord',
- 'grove', 'heron', 'lynx', 'maple', 'nova', 'quartz', 'sparrow', 'willow',
-]
-function randomAgentName(): string {
- const pick = (a: readonly string[]) => a[Math.floor(Math.random() * a.length)]
- return `${pick(NAME_ADJECTIVES)}-${pick(NAME_NOUNS)}`
-}
-const DEFAULT_PROMPT =
- 'You are a helpful AI assistant working in a sandboxed computer. Complete tasks end to end, use the tools available to you, and keep your answers clear and concise. When something is ambiguous, make a sensible assumption and say so.'
+import { Button } from '@/components/ui/button'
export default function Agents() {
- const queryClient = useQueryClient()
const navigate = useNavigate()
const { data: agents, isLoading } = useQuery({
queryKey: ['agents'],
queryFn: getAgents,
})
- // Credentials for the picker (so creating an agent doesn't need a fresh key each time).
- const { data: credentials } = useQuery({
- queryKey: ['credentials'],
- queryFn: getCredentials,
- })
- const [showCreate, setShowCreate] = useState(false)
- const [name, setName] = useState('')
- const [prompt, setPrompt] = useState('')
- const [runtime, setRuntime] = useState(DEFAULT_RUNTIME)
- const [model, setModel] = useState(defaultModelFor(DEFAULT_RUNTIME))
- // Credential selection: a credential id or NEW_CRED (create inline). '' is
- // resolved to a sensible default on dialog open.
- const [credChoice, setCredChoice] = useState('')
- const [newCredName, setNewCredName] = useState('')
- const [newCredKey, setNewCredKey] = useState('')
-
- // The model list follows the runtime; the credential provider + key field follow
- // the selected MODEL's provider prefix. For claude/codex that prefix always equals
- // the runtime's provider; for pi it varies by model, which is what makes pi work.
- const rt = getRuntime(runtime)
- const provider = providerForModel(model) || rt.provider
- const keyField = keyFieldFor(provider)
- const providerCreds = (credentials ?? []).filter(
- (c) => c.provider === provider,
- )
- const hasDefault = providerCreds.some((c) => c.is_default)
-
- // Lowest-friction default, mirroring backend resolution (token-billing §6.6):
- // a BYO org default wins; else Managed (always available to every org).
- const defaultCredFor = (creds: typeof providerCreds) =>
- creds.find((c) => c.is_default)?.id ?? MANAGED
-
- const resetForm = () => {
- setName('')
- setPrompt('')
- setRuntime(DEFAULT_RUNTIME)
- setModel(defaultModelFor(DEFAULT_RUNTIME))
- setCredChoice('')
- setNewCredName('')
- setNewCredKey('')
- }
-
- const openCreate = () => {
- // Pre-fill so the form is submittable immediately — a fresh random name each open.
- setName(randomAgentName())
- setPrompt(DEFAULT_PROMPT)
- setCredChoice(defaultCredFor(providerCreds))
- setShowCreate(true)
- }
-
- // Switching runtime resets the dependent fields so we never submit an invalid
- // (runtime, model) pair or an off-provider credential.
- const onRuntimeChange = (value: string) => {
- setRuntime(value)
- const nextModel = defaultModelFor(value)
- setModel(nextModel)
- setCredChoice(
- defaultCredFor(
- (credentials ?? []).filter(
- (c) => c.provider === providerForModel(nextModel),
- ),
- ),
- )
- setNewCredName('')
- setNewCredKey('')
- }
-
- // Changing the model can change the provider (pi spans providers) — re-point the
- // credential fields at the new provider so we never submit an off-provider key.
- const onModelChange = (value: string) => {
- setModel(value)
- const nextProvider = providerForModel(value)
- if (nextProvider !== provider) {
- setCredChoice(
- defaultCredFor(
- (credentials ?? []).filter((c) => c.provider === nextProvider),
- ),
- )
- setNewCredName('')
- setNewCredKey('')
- }
- }
-
- // Build options: Managed (always offered, no provider — runs without a BYO key) +
- // this runtime's provider creds + "New credential…".
- const credOptions = [
- { value: MANAGED, label: 'Managed · no key needed' },
- ...providerCreds.map((c) => ({
- value: c.id,
- label: `${c.name || 'Unnamed'}${c.last4 ? ` ·· ${c.last4}` : ''}${
- c.is_default ? ' (default)' : ''
- }`,
- })),
- { value: NEW_CRED, label: '+ New credential…' },
- ]
-
- const createMutation = useMutation({
- mutationFn: async () => {
- // Resolve the agent's credential without leaving the dialog:
- // - NEW_CRED → create the credential first, pin the new id.
- // - else → pin the chosen existing credential.
- let credentialId: string | undefined
- if (credChoice === MANAGED) {
- credentialId = MANAGED // run via OpenComputer, no BYO key
- } else if (credChoice === NEW_CRED) {
- const cred = await createCredential({
- key: newCredKey.trim(),
- provider: provider,
- name: newCredName.trim() || undefined,
- is_default: !hasDefault, // first key for this provider becomes its default
- })
- credentialId = cred.id
- } else if (credChoice) {
- credentialId = credChoice
- }
- return createAgent({
- name: name.trim(),
- prompt: prompt.trim(),
- model,
- runtime,
- credential: credentialId,
- })
- },
- onSuccess: (agent) => {
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- void queryClient.invalidateQueries({ queryKey: ['credentials'] })
- setShowCreate(false)
- resetForm()
- // Land on the new agent's screen, not back on the list.
- void navigate(`/agents/${agent.id}`)
- },
- onError: (e) => notifyError("Couldn't create the agent.", e),
- })
const columns: Column<Agent>[] = [
{
key: 'name',
header: 'Name',
- cell: (a) => (
- <span className="text-foreground font-medium">{a.name}</span>
+ cell: (agent) => (
+ <span className="text-foreground font-medium">{agent.name}</span>
),
},
{
key: 'model',
header: 'Model',
- cell: (a) => (
+ cell: (agent) => (
<code className="text-muted-foreground font-mono text-xs">
- {a.model}
+ {agent.model}
</code>
),
},
{
key: 'runtime',
header: 'Runtime',
- cell: (a) => (
+ cell: (agent) => (
<span className="text-muted-foreground text-xs capitalize">
- {a.runtime}
+ {agent.runtime}
</span>
),
},
@@ -230,33 +45,34 @@ export default function Agents() {
key: 'revision',
header: 'Active revision',
align: 'right',
- cell: (a) => (
+ cell: (agent) => (
<span className="text-muted-foreground font-mono text-xs">
- #{a.active_revision?.number ?? a.revision ?? 1}
+ {agent.active_revision
+ ? `#${agent.active_revision.number}`
+ : agent.revision && agent.revision > 0
+ ? `#${agent.revision}`
+ : 'Not deployed'}
</span>
),
},
{
key: 'created',
header: 'Created',
- cell: (a) => (
+ cell: (agent) => (
<span className="text-muted-foreground font-mono text-xs">
- {new Date(a.created_at).toLocaleDateString()}
+ {new Date(agent.created_at).toLocaleDateString()}
</span>
),
},
]
- const canCreate =
- name.trim().length > 0 &&
- prompt.trim().length > 0 &&
- (credChoice !== NEW_CRED || newCredKey.trim().length > 0)
+ const openCreate = () => void navigate('/agents/new')
return (
<div>
<PageHeader
title="Agents"
- description="Reusable definitions — a prompt, model, and runtime a session runs."
+ description="Reusable definitions: a prompt, model, and runtime a session runs."
api={{
method: 'POST',
path: '/v3/agents',
@@ -275,14 +91,14 @@ export default function Agents() {
<ResourceTable
columns={columns}
rows={agents ?? []}
- rowKey={(a) => a.id}
- onRowClick={(a) => void navigate(`/agents/${a.id}`)}
+ rowKey={(agent) => agent.id}
+ onRowClick={(agent) => void navigate(`/agents/${agent.id}`)}
loading={isLoading}
empty={
<EmptyState
icon={Bot}
title="No agents yet"
- description="An agent is the reusable “what” — define it once, then start sessions from it."
+ description="Define an agent once, then start durable sessions from it."
action={
<Button size="sm" onClick={openCreate}>
<Plus className="size-4" />
@@ -293,143 +109,6 @@ export default function Agents() {
}
/>
</Panel>
-
- <Dialog
- open={showCreate}
- onOpenChange={(open) => {
- setShowCreate(open)
- if (!open) setNewCredKey('') // never leave a model key in state after close
- }}
- >
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Create agent</DialogTitle>
- <DialogDescription>
- A reusable definition. Sessions pin a snapshot of it at create
- time.
- </DialogDescription>
- </DialogHeader>
- <form
- className="space-y-4"
- onSubmit={(e) => {
- e.preventDefault()
- if (canCreate) createMutation.mutate()
- }}
- >
- <Field label="Name" htmlFor="agent-name">
- <Input
- id="agent-name"
- value={name}
- onChange={(e) => setName(e.target.value)}
- placeholder="e.g. PR Reviewer"
- />
- </Field>
- <Field
- label="Prompt"
- htmlFor="agent-prompt"
- description="The system prompt that defines how the agent behaves."
- >
- <Textarea
- id="agent-prompt"
- value={prompt}
- onChange={(e) => setPrompt(e.target.value)}
- placeholder="You are a meticulous code reviewer…"
- className="min-h-28"
- />
- </Field>
- <div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
- <Field
- label="Runtime"
- htmlFor="agent-runtime"
- description="The engine, fixed once created."
- >
- <Select
- id="agent-runtime"
- value={runtime}
- onValueChange={onRuntimeChange}
- options={runtimeOptions}
- />
- </Field>
- <Field
- label="Model"
- htmlFor="agent-model"
- description={`Models for the ${rt.label} runtime.`}
- >
- <Select
- // Remount on runtime change: Radix Select.Value blanks out when
- // its options and value change in the same render.
- key={runtime}
- id="agent-model"
- value={model}
- onValueChange={onModelChange}
- options={withModelGroups(rt.models)}
- />
- </Field>
- </div>
- <Field
- label="Credential"
- htmlFor="agent-cred"
- description={
- credChoice === MANAGED
- ? 'Run via OpenComputer, billed to your credits — no key needed.'
- : `The ${provider} key this agent runs on (matches the model). Reuse one from Credentials, or add a new one here.`
- }
- >
- <Select
- key={provider}
- id="agent-cred"
- value={credChoice}
- onValueChange={setCredChoice}
- options={credOptions}
- placeholder="Choose a credential"
- />
- </Field>
- {credChoice === NEW_CRED ? (
- <div className="border-border bg-panel-2 grid grid-cols-1 gap-4 rounded-md border p-3 sm:grid-cols-2">
- <Field label="Credential name" htmlFor="new-cred-name">
- <Input
- id="new-cred-name"
- value={newCredName}
- onChange={(e) => setNewCredName(e.target.value)}
- placeholder="e.g. Production"
- />
- </Field>
- <Field
- label={keyField.keyLabel}
- htmlFor="new-cred-key"
- description="Encrypted in a dedicated secret store."
- >
- <Input
- id="new-cred-key"
- type="password"
- value={newCredKey}
- onChange={(e) => setNewCredKey(e.target.value)}
- placeholder={keyField.keyPlaceholder}
- />
- </Field>
- </div>
- ) : null}
- <DialogFooter className="mt-2">
- <Button
- type="button"
- variant="ghost"
- onClick={() => {
- setShowCreate(false)
- resetForm()
- }}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={createMutation.isPending || !canCreate}
- >
- {createMutation.isPending ? 'Creating…' : 'Create agent'}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
</div>
)
}