Skip to content

An open-source, faster Devin alternative

TypeScript

web, api: remove legacy agent sessions pages and handlers (097 step 7.1)

Mohamed Habib via Computercb53f36c1920
diff --git a/internal/api/dashboard_agents.go b/internal/api/dashboard_agents.go
deleted file mode 100644
index 97938a63..00000000
--- a/internal/api/dashboard_agents.go
+++ /dev/null
@@ -1,193 +0,0 @@
-package api
-
-import (
- "io"
- "log"
- "net/http"
- "net/url"
- "os"
- "strings"
- "time"
-
- "github.com/labstack/echo/v4"
-
- "github.com/opensandbox/opensandbox/internal/auth"
-)
-
-const (
- // inboundJWTTTL is the lifetime of the bearer token sessions-api verifies
- // on the proxied request. Sessions-api validates once at the route entry,
- // so this only needs to cover the initial verification — keep it tight.
- inboundJWTTTL = 90 * time.Second
-
- // downstreamJWTTTL is the lifetime of the JWT sessions-api forwards on
- // its OC API calls (sandbox creation, secret stores, exec.run via SDK).
- // Has to outlast the longest single agent operation: managed-core boot
- // involves checkpoint restore + entrypoint start + adapter waitReady,
- // which can take several minutes. 10m is a comfortable upper bound.
- downstreamJWTTTL = 10 * time.Minute
-
- // downstreamHeaderName is the header sessions-api relays as a Bearer
- // token on its calls back into OC's /api/sandboxes and /api/secret-stores.
- // Sessions-api never mints; OC pre-mints both tokens here.
- downstreamHeaderName = "X-OC-Downstream-Token"
-)
-
-// sessionsAPIBaseURL returns the upstream URL for the agents service. The env
-// var matches the CLI's SESSIONS_API_URL (cmd/oc/internal/config) so a single
-// value drives both surfaces.
-func sessionsAPIBaseURL() string {
- if v := os.Getenv("SESSIONS_API_URL"); v != "" {
- return strings.TrimRight(v, "/")
- }
- return "https://api.opencomputer.dev"
-}
-
-// dashboardAgentsProxy is a thin reverse proxy from /api/dashboard/agents/*
-// → ${SESSIONS_API_URL}/v1/agents/*. It runs after the WorkOS cookie
-// middleware, so the request is already authenticated as a real user.
-//
-// Auth handling:
-// - Mint two identity JWTs (sessions-api inbound, opencomputer-api downstream)
-// using the user's identity from the echo context.
-// - Strip Cookie / X-API-Key on the way out (sessions-api should rely on the
-// Bearer token, never the dashboard cookie).
-// - Set Authorization: Bearer <inbound-jwt>.
-// - Set X-OC-Downstream-Token: <downstream-jwt> for sessions-api to relay.
-//
-// The CLI continues to use sessions-api directly with X-API-Key — that path
-// is untouched.
-func (s *Server) dashboardAgentsProxy(c echo.Context) error {
- if s.jwtIssuer == nil {
- return c.JSON(http.StatusServiceUnavailable, map[string]string{
- "error": "agents proxy unavailable: jwt issuer not configured",
- })
- }
-
- orgID, ok := auth.GetOrgID(c)
- if !ok {
- return c.JSON(http.StatusUnauthorized, map[string]string{
- "error": "org context required",
- })
- }
-
- in := auth.IdentityTokenInput{OrgID: orgID.String(), Audience: auth.AudSessionsAPI}
- if userID := auth.GetUserID(c); userID != nil {
- userStr := userID.String()
- in.UserID = &userStr
- }
- if email, ok := c.Get("user_email").(string); ok && email != "" {
- in.Email = &email
- }
- // Lookup workos_user_id (best-effort — used for analytics attribution).
- if s.store != nil {
- if userID := auth.GetUserID(c); userID != nil {
- if user, err := s.store.GetUserByID(c.Request().Context(), *userID); err == nil {
- if user.WorkOSUserID != nil && *user.WorkOSUserID != "" {
- in.WorkOSUserID = user.WorkOSUserID
- }
- }
- }
- }
-
- inboundToken, err := s.jwtIssuer.IssueIdentityToken(in, inboundJWTTTL)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "failed to mint inbound token",
- })
- }
-
- downstreamIn := in
- downstreamIn.Audience = auth.AudOpenComputerAPI
- downstreamToken, err := s.jwtIssuer.IssueIdentityToken(downstreamIn, downstreamJWTTTL)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "failed to mint downstream token",
- })
- }
-
- // Map /api/dashboard/agents[/...] → /v1/agents[/...]
- upstreamPath := "/v1/agents"
- if rest := strings.TrimPrefix(c.Request().URL.Path, "/api/dashboard/agents"); rest != "" {
- upstreamPath += rest
- }
- upstream, err := url.Parse(sessionsAPIBaseURL() + upstreamPath)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "invalid upstream URL",
- })
- }
- upstream.RawQuery = c.Request().URL.RawQuery
-
- req, err := http.NewRequestWithContext(c.Request().Context(), c.Request().Method, upstream.String(), c.Request().Body)
- if err != nil {
- return c.JSON(http.StatusInternalServerError, map[string]string{
- "error": "failed to build upstream request",
- })
- }
-
- // Forward request headers, but drop the ones that should not cross the
- // service boundary. The cookie carries the dashboard session; sessions-api
- // must rely on the Bearer token instead.
- for k, v := range c.Request().Header {
- switch strings.ToLower(k) {
- case "cookie", "authorization", "x-api-key", "host", "content-length":
- continue
- }
- req.Header[k] = v
- }
- req.Header.Set("Authorization", "Bearer "+inboundToken)
- req.Header.Set(downstreamHeaderName, downstreamToken)
- if ct := c.Request().Header.Get("Content-Type"); ct != "" {
- req.Header.Set("Content-Type", ct)
- }
-
- // Use a client without a fixed timeout so SSE streams (e.g. the
- // instance messages endpoint) can stay open. Idle reads are bounded
- // by the upstream's own keep-alive / write deadlines.
- streamingClient := &http.Client{}
- resp, err := streamingClient.Do(req)
- if err != nil {
- log.Printf("dashboard_agents: upstream call failed: %v", err)
- return c.JSON(http.StatusBadGateway, map[string]string{
- "error": "upstream request failed",
- })
- }
- defer resp.Body.Close()
-
- for k, v := range resp.Header {
- // Hop-by-hop headers shouldn't be forwarded.
- switch strings.ToLower(k) {
- case "transfer-encoding", "connection", "keep-alive":
- continue
- }
- c.Response().Header()[k] = v
- }
- c.Response().WriteHeader(resp.StatusCode)
-
- // Streaming-aware copy: flush after every read so SSE events from the
- // upstream (text/event-stream Content-Type) reach the browser as soon
- // as they're produced. io.Copy on its own does not call Flush; the
- // browser would only see events when net/http's own buffer fills,
- // which kills the chat UX.
- flusher, _ := c.Response().Writer.(http.Flusher)
- buf := make([]byte, 4096)
- for {
- n, readErr := resp.Body.Read(buf)
- if n > 0 {
- if _, writeErr := c.Response().Writer.Write(buf[:n]); writeErr != nil {
- log.Printf("dashboard_agents: write to client failed: %v", writeErr)
- return nil
- }
- if flusher != nil {
- flusher.Flush()
- }
- }
- if readErr != nil {
- if readErr != io.EOF {
- log.Printf("dashboard_agents: read from upstream failed: %v", readErr)
- }
- return nil
- }
- }
-}
diff --git a/internal/api/router.go b/internal/api/router.go
index 27c35325..10f73116 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -469,10 +469,7 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
idash.GET("/images", s.dashboardListImages)
idash.DELETE("/images/:id", s.dashboardDeleteImage)
idash.DELETE("/snapshots/:name", s.dashboardDeleteSnapshot)
- // Agents — currently proxied to an external service from each cell.
- // Easier to keep that wiring intact than reimplement on the edge.
- idash.Any("/agents", s.dashboardAgentsProxy)
- idash.Any("/agents/*", s.dashboardAgentsProxy)
+ // Per-agent paywalled-feature subscriptions.
idash.GET("/agents/:agentId/entitlements", s.dashboardListAgentEntitlements)
idash.POST("/agents/:agentId/subscriptions/:feature", s.dashboardSubscribeAgentFeature)
idash.DELETE("/agents/:agentId/subscriptions/:feature", s.dashboardCancelAgentFeature)
@@ -873,20 +870,11 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, o
// Admin endpoints
- // Agents — reverse-proxy to sessions-api. Mints short-lived identity
- // JWTs for the inbound (sessions-api) and downstream (OC API) hops so
- // no API key is needed end-to-end. CLI users bypass this and hit
- // sessions-api directly with X-API-Key.
- dash.Any("/agents", s.dashboardAgentsProxy)
// Per-agent paywalled-feature subscriptions (telegram et al).
- // Mounted BEFORE the catch-all /agents/* proxy so they don't
- // get forwarded to sessions-api.
dash.GET("/agents/:agentId/entitlements", s.dashboardListAgentEntitlements)
dash.POST("/agents/:agentId/subscriptions/:feature", s.dashboardSubscribeAgentFeature)
dash.DELETE("/agents/:agentId/subscriptions/:feature", s.dashboardCancelAgentFeature)
- dash.Any("/agents/*", s.dashboardAgentsProxy)
-
// Session detail + stats
dash.GET("/sessions/:sandboxId", s.dashboardGetSession)
dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)
diff --git a/web/src/App.tsx b/web/src/App.tsx
index bd1c7901..0e785d13 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -10,14 +10,7 @@ import { templateDeployPathFromSearch } from './managed-agents/templates'
// Route pages are code-split so the initial bundle stays small; the heaviest
// 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 AgentSetup = lazy(() => import('./pages/AgentSetup'))
const Credentials = lazy(() => import('./pages/Credentials'))
-const Sessions = lazy(() => import('./pages/Sessions'))
-const SessionDetail = lazy(() => import('./pages/SessionDetail'))
const Browsers = lazy(() => import('./pages/Browsers'))
const Sandboxes = lazy(() => import('./pages/Sandboxes'))
const APIKeys = lazy(() => import('./pages/APIKeys'))
@@ -147,19 +140,7 @@ export default function App() {
path="managed-agents/:agentId"
element={<ManagedAgentDetail />}
/>
- {/* Agent plane */}
- <Route path="agents" element={<Agents />} />
- <Route path="agents/new" element={<AgentNew />} />
- <Route path="agents/:agentId/setup" element={<AgentSetup />} />
- <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 />} />
- <Route path="sessions" element={<Sessions />} />
- <Route path="sessions/:sessionId" element={<SessionDetail />} />
<Route path="browsers" element={<Browsers />} />
{/* Sandbox plane */}
<Route path="sandboxes" element={<Sandboxes />} />
diff --git a/web/src/api/agent-invocation-client.test.ts b/web/src/api/agent-invocation-client.test.ts
deleted file mode 100644
index 922cd08d..00000000
--- a/web/src/api/agent-invocation-client.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import {
- createAgentHook,
- getAgentHooks,
- revokeAgentHook,
-} from './client'
-
-const agentId = 'agt_0123456789abcdef01234567'
-
-afterEach(() => vi.unstubAllGlobals())
-
-describe('Hook management dashboard client', () => {
- it('parses copy-once creation and secret-free list responses', async () => {
- const fetchMock = vi.fn((input: string | URL | Request) => {
- const path =
- typeof input === 'string'
- ? input
- : input instanceof URL
- ? input.href
- : input.url
- if (path.includes('?')) {
- return Promise.resolve(Response.json({ data: [], next_cursor: null }))
- }
- return Promise.resolve(
- Response.json(
- {
- hook: {
- id: 'hk_0123456789abcdef01234567',
- agent_id: agentId,
- name: 'grafana-prod',
- status: 'active',
- secret_last4: 'xYz0',
- revoked_reason: null,
- expires_at: null,
- created_at: '2026-07-22T00:00:00.000Z',
- },
- hook_url: 'https://agent.test/hooks/secret',
- },
- { status: 201 },
- ),
- )
- })
- vi.stubGlobal('fetch', fetchMock)
-
- const created = await createAgentHook(agentId, { name: 'grafana-prod' })
- expect(created.hook_url).toBe('https://agent.test/hooks/secret')
- await expect(getAgentHooks(agentId)).resolves.toEqual({
- data: [],
- next_cursor: null,
- })
- })
-
- it('revokes without expecting a response body', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => Promise.resolve(new Response(null, { status: 204 }))),
- )
-
- await expect(
- revokeAgentHook(agentId, 'hk_0123456789abcdef01234567'),
- ).resolves.toBeUndefined()
- })
-})
diff --git a/web/src/api/agents.ts b/web/src/api/agents.ts
deleted file mode 100644
index 1d6d09b1..00000000
--- a/web/src/api/agents.ts
+++ /dev/null
@@ -1,316 +0,0 @@
-// Dormant agent API client — the agent dashboard pages were removed (orphaned).
-// Kept for reference; the upcoming Durable Sessions UI will build its own.
-// Nothing imports this yet.
-
-import { apiFetch } from './client'
-
-// ── Agents (proxied to sessions-api at /api/dashboard/agents/*) ──
-
-export interface Agent {
- id: string
- display_name: string
- core: string | null
- model: string | null
- channels: Array<{
- name: string
- bot_username?: string | null
- connected_at?: string
- }>
- packages: Array<{ name: string; installed_at?: string }>
- secret_store: string | null
- config: Record<string, unknown>
- created_at: string
- updated_at: string
-}
-
-export interface AgentDetail extends Agent {
- status: 'ready' | 'starting' | 'degraded' | 'error' | 'unknown'
- instance_id: string | null
- instance_status: string | null
- sandbox_id: string | null
- core_status: {
- status: string
- reason?: string
- message?: string
- updated_at?: string
- } | null
- channel_status: Record<
- string,
- { status: string; phase?: string; message?: string }
- >
- package_status: Record<
- string,
- { status: string; phase?: string; message?: string }
- >
- conditions: Array<{
- type: string
- status: string
- reason?: string
- message?: string
- }>
- current_operation: AgentOperation | null
- last_error: { phase: string; message: string; at: string } | null
-}
-
-export interface AgentOperation {
- id: string
- agent_id: string
- kind: string
- target_type?: string | null
- target_key?: string | null
- phase: string
- state: 'queued' | 'running' | 'success' | 'error' | 'canceled'
- message?: string | null
- created_at: string
- updated_at: string
-}
-
-export const listAgents = () => apiFetch<{ agents: Agent[] }>('/agents')
-
-export const getAgent = (id: string) =>
- apiFetch<AgentDetail>(`/agents/${encodeURIComponent(id)}`)
-
-export const createAgent = (input: {
- id: string
- display_name?: string
- core?: string
- model?: string
- config?: Record<string, unknown>
- secrets?: Record<string, string>
-}) =>
- apiFetch<AgentDetail>('/agents', {
- method: 'POST',
- body: JSON.stringify(input),
- })
-
-export const deleteAgent = (id: string) =>
- apiFetch<{ id: string; deleted: boolean }>(
- `/agents/${encodeURIComponent(id)}`,
- {
- method: 'DELETE',
- },
- )
-
-export const installGbrain = (agentId: string) =>
- apiFetch<{
- agent_id: string
- package: string
- status: string
- operation: AgentOperation
- }>(`/agents/${encodeURIComponent(agentId)}/packages/gbrain`, {
- method: 'POST',
- })
-
-export const uninstallGbrain = (agentId: string) =>
- apiFetch<{ agent_id: string; package: string; status: string }>(
- `/agents/${encodeURIComponent(agentId)}/packages/gbrain`,
- { method: 'DELETE' },
- )
-
-export const connectTelegram = (agentId: string, botToken: string) =>
- apiFetch<{
- agent_id: string
- channel: string
- status: string
- operation: AgentOperation
- }>(`/agents/${encodeURIComponent(agentId)}/channels/telegram`, {
- method: 'POST',
- body: JSON.stringify({ bot_token: botToken }),
- })
-
-export const disconnectTelegram = (agentId: string) =>
- apiFetch<{ agent_id: string; channel: string; status: string }>(
- `/agents/${encodeURIComponent(agentId)}/channels/telegram`,
- { method: 'DELETE' },
- )
-
-export interface AgentEvent {
- id: string
- agent_id: string
- type: 'info' | 'warning' | 'error'
- phase: string
- message: string
- at: string
-}
-
-export const getAgentEvents = (agentId: string, limit = 50) =>
- apiFetch<{ events: AgentEvent[]; next_before: string | null }>(
- `/agents/${encodeURIComponent(agentId)}/events?limit=${limit}`,
- )
-
-export const getAgentOperations = (agentId: string, limit = 20) =>
- apiFetch<{ operations: AgentOperation[]; next_before: string | null }>(
- `/agents/${encodeURIComponent(agentId)}/operations?limit=${limit}`,
- )
-
-export const restartAgent = (agentId: string) =>
- apiFetch<{ agent_id: string; status: string }>(
- `/agents/${encodeURIComponent(agentId)}/restart`,
- { method: 'POST' },
- )
-
-export const getAgentLogs = (agentId: string, tail = 300) =>
- apiFetch<{
- agent_id: string
- sandbox_id: string
- source: string
- lines: number
- content: string
- }>(`/agents/${encodeURIComponent(agentId)}/logs?tail=${tail}`)
-
-// ── Per-agent paywalled feature subscriptions (Telegram et al) ──
-
-// Known values: 'ungated' | 'subscription_required'; typed as string so a new
-// server reason never fails typing.
-export type EntitlementReason = string
-
-export interface AgentEntitlement {
- feature: string
- entitled: boolean
- reason?: EntitlementReason
- price_monthly_cents?: number
- status?: string
- current_period_end?: string
- cancel_at_period_end?: boolean
- stripe_subscription_id?: string
-}
-
-export const listAgentEntitlements = (agentId: string) =>
- apiFetch<{ agent_id: string; entitlements: AgentEntitlement[] }>(
- `/agents/${encodeURIComponent(agentId)}/entitlements`,
- )
-
-export type SubscribeResult =
- | {
- status: 'active'
- feature: string
- agent_id: string
- subscription_id: string
- price_id: string
- }
- | {
- status: 'already_subscribed'
- feature: string
- agent_id: string
- subscription_id: string
- }
- | { status: 'ungated'; feature: string; agent_id: string }
- | {
- status: 'checkout_required'
- feature: string
- agent_id: string
- checkout_url: string
- }
-
-export const subscribeAgentFeature = (agentId: string, feature: string) =>
- apiFetch<SubscribeResult>(
- `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,
- { method: 'POST' },
- )
-
-export interface OrgAgentSubscription {
- agent_id: string
- feature: string
- status: string
- active: boolean
- price_monthly_cents: number
- current_period_end?: string
- cancel_at_period_end: boolean
- canceled_at?: string
- created_at: string
- stripe_subscription_id: string
-}
-
-export const listOrgAgentSubscriptions = () =>
- apiFetch<{ subscriptions: OrgAgentSubscription[] }>(
- '/billing/agent-subscriptions',
- )
-
-export const cancelAgentFeature = (agentId: string, feature: string) =>
- apiFetch<{
- status: string
- feature: string
- agent_id: string
- cancel_at_period_end: boolean
- current_period_end?: string
- }>(
- `/agents/${encodeURIComponent(agentId)}/subscriptions/${encodeURIComponent(feature)}`,
- { method: 'DELETE' },
- )
-
-/**
- * Streams a chat turn to an agent's instance and yields parsed SSE events
- * as they arrive. The upstream (sessions-api POST /v1/agents/:id/instances/:id/messages)
- * emits `data: {type:"text",content:"..."}` and `data: {type:"done"}`.
- *
- * Uses fetch + ReadableStream because EventSource is GET-only.
- */
-export type ChatEvent =
- | { type: 'text'; content: string; conversation_id?: string }
- | { type: 'done' }
- | { type: 'raw'; data: string }
-
-export interface ChatTurn {
- role: 'user' | 'assistant' | 'system'
- content: string
-}
-
-export async function* streamAgentChat(
- agentId: string,
- instanceId: string,
- content: string,
- conversationId?: string,
- history?: ChatTurn[],
-): AsyncGenerator<ChatEvent, void, unknown> {
- // OpenAI-style chat-completions is stateless: the gateway needs the
- // full conversation each turn to have any memory of prior messages.
- // Caller passes `history` (already including the new user turn).
- // For backwards compat with older callers, we still accept `content`
- // as a single-turn shortcut.
- const body: Record<string, unknown> = {}
- if (history && history.length > 0) {
- body.messages = history
- } else {
- body.content = content
- }
- if (conversationId) body.conversation_id = conversationId
-
- const res = await fetch(
- `/api/dashboard/agents/${encodeURIComponent(agentId)}/instances/${encodeURIComponent(instanceId)}/messages`,
- {
- method: 'POST',
- credentials: 'include',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(body),
- },
- )
- if (!res.ok || !res.body) {
- const text = await res.text().catch(() => '')
- throw new Error(`chat ${res.status}: ${text || 'no body'}`)
- }
-
- const reader = res.body.getReader()
- const decoder = new TextDecoder()
- let buffer = ''
- while (true) {
- const { done, value } = await reader.read()
- if (done) return
- buffer += decoder.decode(value, { stream: true })
- let idx: number
- while ((idx = buffer.indexOf('\n\n')) !== -1) {
- const block = buffer.slice(0, idx)
- buffer = buffer.slice(idx + 2)
- const data = block
- .split('\n')
- .filter((line) => line.startsWith('data:'))
- .map((line) => line.slice(5).trimStart())
- .join('\n')
- if (!data) continue
- try {
- yield JSON.parse(data) as ChatEvent
- } catch {
- yield { type: 'raw', data }
- }
- }
- }
-}
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index c69b5d90..9712b171 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -32,42 +32,9 @@ export type {
SandboxUsage,
BrowserSession,
BrowserProfile,
- Agent,
- AgentRevision,
- AgentSkills,
- SkillItem,
- AgentDeploy,
- AgentDeployment,
- AgentDeploymentLog,
- DeployApp,
- RepositoryAccess,
- RepositoryAccessPolicy,
- RepositoryAccessRepository,
- RepositorySourceInspection,
- ManagedSlackAuthorizeResponse,
- ManagedSlackConnection,
- ManagedSlackWorkspaceConnection,
- ManagedSlackDisconnectResponse,
- Session,
- SessionSource,
- AgentSnapshot,
- SessionEvent,
- Turn,
- SessionResult,
- Destination,
- Delivery,
SandboxWebhook,
SandboxWebhookDelivery,
Credential,
- ModelAccessConnection,
- ModelAccessBinding,
- ModelAccessConnectResponse,
- EffectiveModelRoute,
- AgentSecurityNotification,
- AgentHook,
- AgentHookCreate,
- SessionUsage,
- TurnUsage,
} from './schemas'
const API_BASE = '/api/dashboard'
@@ -441,19 +408,6 @@ export const switchOrg = (orgId: string) =>
S.OrgSchema,
)
-export const listAgentSecurityNotifications = () =>
- apiFetch(
- '/agent-security-notifications?include_acknowledged=false&limit=100',
- {},
- S.AgentSecurityNotificationListSchema,
- )
-
-export const acknowledgeAgentSecurityNotification = (id: string) =>
- apiFetch<void>(
- `/agent-security-notifications/${encodeURIComponent(id)}/acknowledge`,
- { method: 'POST' },
- )
-
// Credits
export const getCredits = () => apiFetch('/org/credits', {}, S.CreditsSchema)
@@ -570,447 +524,10 @@ export const getBrowserProfiles = () =>
(r) => r.profiles,
)
-// ── Durable Agent Sessions ───────────────────────────────────────────────────
-// A separate service (sessions-api). Reached through the OC edge under
-// `/api/dashboard/v3/*`, so these reuse apiFetch (cookie auth, validation, mock).
-// Org-key management lives server-side at the edge; live event/steer can move to
-// a browser-direct client-token path later without changing these signatures.
-
-// Agents — the reusable definition (prompt, model, runtime, credential).
-// List endpoints wrap rows in { data: [...] }; callers want the array.
-export const getAgents = () =>
- apiFetch('/v3/agents', {}, S.AgentListSchema).then((r) => r.data)
-
-export const getAgent = (id: string) =>
- apiFetch(`/v3/agents/${id}`, {}, S.AgentSchema)
-
-export const createAgent = (body: {
- name: string
- prompt: string
- model: string
- runtime: string
- // The request field is `credential` (the response carries `credential_id`).
- credential?: string
- // `key` sugar: mints a model credential of the runtime's provider for this
- // agent (write-only). Without it (and no org default) sessions 422 no_credential.
- key?: string
-}) =>
- apiFetch(
- '/v3/agents',
- { method: 'POST', body: JSON.stringify(body) },
- S.AgentSchema,
- )
-
-// PATCH bumps revision; name is immutable (create idempotency key). `credential`
-// switches which credential the agent runs on; `key` (legacy) rotates the pinned
-// credential's value — rotation now lives on the Credentials page.
-export const updateAgent = (
- id: string,
- body: Partial<{
- prompt: string
- model: string
- key: string
- credential: string | null // null clears the pin → org default resolves
- }>,
-) =>
- apiFetch(
- `/v3/agents/${id}`,
- { method: 'PATCH', body: JSON.stringify(body) },
- S.AgentSchema,
- )
-
-export const getAgentHooks = (agentId: string, cursor?: string) => {
- const query = new URLSearchParams({ include_revoked: 'true', limit: '100' })
- if (cursor) query.set('cursor', cursor)
- return apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/hooks?${query.toString()}`,
- {},
- S.AgentHookListSchema,
- )
-}
-
-export const createAgentHook = (
- agentId: string,
- body: { name: string; expires_at?: string | null },
-) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/hooks`,
- { method: 'POST', body: JSON.stringify(body) },
- S.AgentHookCreateSchema,
- )
-
-export const revokeAgentHook = (agentId: string, hookId: string) =>
- apiFetch<void>(
- `/v3/agents/${encodeURIComponent(agentId)}/hooks/${encodeURIComponent(hookId)}`,
- { method: 'DELETE' },
- )
-
-// Agent Revisions (design 009) — the deploy history of an agent's behavior. List
-// endpoints wrap rows in { data: [...] }; callers want the array. Rollback = activate
-// an earlier revision (by id or number); it moves the production pointer.
-export const getAgentRevisions = (agentId: string) =>
- apiFetch(
- `/v3/agents/${agentId}/revisions`,
- {},
- S.AgentRevisionListSchema,
- ).then((r) => r.data)
-
-export const getAgentDeploys = (agentId: string) =>
- apiFetch(`/v3/agents/${agentId}/deploys`, {}, S.AgentDeployListSchema).then(
- (r) => r.data,
- )
-
-export const activateRevision = (agentId: string, rev: string | number) =>
- apiFetch(
- `/v3/agents/${agentId}/revisions/${rev}/activate`,
- { method: 'POST', body: JSON.stringify({}) },
- S.ActivateRevisionSchema,
- )
-
-// Schedules sub-resource (design 015) — cron for agents. A schedule fires an agent on a cron;
-// each firing starts one session on the active revision. Reached via the /v3 passthrough.
-export type ScheduleOverlap = 'skip' | 'allow'
-export type ScheduleState = 'active' | 'paused' | 'auto_paused'
-export type ScheduleRunOutcome = 'enacted' | 'skipped' | 'failed'
-
-export interface Schedule {
- id: string
- agent_id: string
- name: string
- cron: string
- tz: string | null
- input: string
- overlap: ScheduleOverlap
- state: ScheduleState
- next_fire_at: string
- last_fired_at: string | null
- consecutive_failures: number
- last_error: string | null
- created_at: string
- updated_at: string
-}
-
-export interface ScheduleRun {
- id: string
- schedule_id: string
- scheduled_for: string | null
- fired_at: string
- outcome: ScheduleRunOutcome
- session_id: string | null
- error: string | null
-}
-
-export const getSchedules = (agentId: string) =>
- apiFetch<{ schedules: Schedule[] }>(`/v3/agents/${agentId}/schedules`).then(
- (r) => r.schedules,
- )
-
-export const createSchedule = (
- agentId: string,
- body: {
- name: string
- cron: string
- tz?: string | null
- input: string
- overlap?: ScheduleOverlap
- },
-) =>
- apiFetch<{ schedule: Schedule }>(`/v3/agents/${agentId}/schedules`, {
- method: 'POST',
- body: JSON.stringify(body),
- }).then((r) => r.schedule)
-
-// PATCH accepts any of { cron, tz, input, overlap, paused }. `paused` toggles pause/resume.
-export const updateSchedule = (
- agentId: string,
- scheduleId: string,
- body: Partial<{
- cron: string
- tz: string | null
- input: string
- overlap: ScheduleOverlap
- paused: boolean
- }>,
-) =>
- apiFetch<{ schedule: Schedule }>(
- `/v3/agents/${agentId}/schedules/${scheduleId}`,
- { method: 'PATCH', body: JSON.stringify(body) },
- ).then((r) => r.schedule)
-
-export const deleteSchedule = (agentId: string, scheduleId: string) =>
- apiFetch<void>(`/v3/agents/${agentId}/schedules/${scheduleId}`, {
- method: 'DELETE',
- })
-
-// Test-fire now — enacts synchronously (a failed fire still returns a run with outcome:"failed").
-export const fireSchedule = (agentId: string, scheduleId: string) =>
- apiFetch<{ run: ScheduleRun }>(
- `/v3/agents/${agentId}/schedules/${scheduleId}/fire`,
- { method: 'POST', body: JSON.stringify({}) },
- ).then((r) => r.run)
-
-export const getScheduleRuns = (
- agentId: string,
- scheduleId: string,
- limit = 10,
-) =>
- apiFetch<{ runs: ScheduleRun[]; next_cursor: string | null }>(
- `/v3/agents/${agentId}/schedules/${scheduleId}/runs?limit=${limit}`,
- ).then((r) => r.runs)
-
-// Skills sub-resource (design 009 §8) — the API owns zip → validate → bundle, so the
-// dashboard is a thin consumer: read the file list, upload a .zip, or clear.
-export const getAgentSkills = (agentId: string) =>
- apiFetch(`/v3/agents/${agentId}/skills`, {}, S.AgentSkillsSchema)
-
-// Upload a .zip of skills → the API unzips + deploys a new revision (active behavior with
-// skills replaced). The raw file is the body; no client-side parsing.
-export const putAgentSkills = (agentId: string, zip: File | Blob) =>
- apiFetch(
- `/v3/agents/${agentId}/skills`,
- {
- method: 'PUT',
- body: zip,
- headers: { 'Content-Type': 'application/zip' },
- },
- S.DeployResultSchema,
- )
-
-// Remove all skills → deploys a revision from the active behavior with no skills.
-export const deleteAgentSkills = (agentId: string) =>
- apiFetch(
- `/v3/agents/${agentId}/skills`,
- { method: 'DELETE' },
- S.DeployResultSchema,
- )
-
-// 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 getRepositoryAccess = (agentId: string) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/repository-access`,
- {},
- S.RepositoryAccessSchema,
- )
-
-export const updateRepositoryAccess = (
- agentId: string,
- policy: S.RepositoryAccessPolicy,
-) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/repository-access`,
- { method: 'PUT', body: JSON.stringify(policy) },
- S.RepositoryAccessSchema,
- )
-
-export const reviewRepositoryAgent = (body: {
- repo: string
- path: string
- production_ref: string
-}) =>
- apiFetch(
- '/v3/github/deploy-app/inspect',
- { method: 'POST', body: JSON.stringify(body) },
- S.RepositorySourceInspectionSchema,
- )
-
-export const importAgentFromGithub = (
- body: {
- name: string
- source: {
- type: 'github'
- repo: string
- path: string
- production_ref: string
- }
- review: {
- sha: string
- source_profile: 'flue-app-v1' | 'flue-prompt-v1'
- fingerprint: 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,
- )
-
-export const linkDeploymentSource = (
- agentId: string,
- body: {
- repo: string
- path: string
- production_ref?: string
- deploy_now?: boolean
- },
-) =>
- apiFetch(
- `/v3/agents/${agentId}/deployment-source`,
- { method: 'POST', body: JSON.stringify(body) },
- S.LinkResultSchema,
- )
-
-export const unlinkDeploymentSource = (agentId: string) =>
- apiFetch<void>(`/v3/agents/${agentId}/deployment-source`, {
- method: 'DELETE',
- })
-
-// Deploy the linked repo's current production-branch HEAD now (no git push needed).
-export const deployFromGithub = (agentId: string, idempotencyKey: string) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/deployments`,
- {
- method: 'POST',
- body: JSON.stringify({ input: { type: 'github' } }),
- headers: { 'Idempotency-Key': idempotencyKey },
- },
- S.AgentDeploymentCommandResponseSchema,
- )
-
-export const getAgentDeployments = (
- agentId: string,
- options: { before?: string; limit?: number } = {},
-) => {
- const query = new URLSearchParams()
- if (options.before) query.set('before', options.before)
- if (options.limit) query.set('limit', String(options.limit))
- const qs = query.toString()
- return apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/deployments${qs ? `?${qs}` : ''}`,
- {},
- S.AgentDeploymentListSchema,
- )
-}
-
-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.
-// `getSlackConnection` maps the 404 "not connected" into null so callers can
-// branch on absence without treating it as an error.
-export async function getSlackConnection(agentId: string) {
- try {
- return await apiFetch(
- `/v3/agents/${agentId}/slack`,
- {},
- S.SlackConnectionSchema,
- )
- } catch (e) {
- if (e instanceof Error && /no slack connection/i.test(e.message))
- return null
- throw e
- }
-}
-
-// `reconnect: true` is required to replace an ALREADY-ACTIVE connection (the server
-// refuses to tear down a live one otherwise). First connect / pending / error → false.
-export const startSlackConnect = (agentId: string, reconnect = false) =>
- apiFetch(
- `/v3/agents/${agentId}/slack/manifest`,
- { method: 'POST', body: JSON.stringify({ reconnect }) },
- S.SlackManifestResponseSchema,
- )
-
-export const completeSlackConnect = (
- agentId: string,
- body: { app_id: string; bot_token: string; signing_secret: string },
-) =>
- apiFetch(
- `/v3/agents/${agentId}/slack`,
- { method: 'POST', body: JSON.stringify(body) },
- S.SlackConnectionSchema,
- )
-
-export const disconnectSlack = (agentId: string) =>
- apiFetch<void>(`/v3/agents/${agentId}/slack`, { method: 'DELETE' })
-
-// Managed Slack is the OpenComputer-operated onboarding app. It is a separate
-// resource from the builder-owned app above so both may coexist during an
-// explicit handoff.
-export const authorizeManagedSlack = (
- agentId: string,
- returnDeploymentId?: string,
-) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/slack/managed/authorize`,
- {
- method: 'POST',
- body: JSON.stringify(
- returnDeploymentId ? { return_deployment_id: returnDeploymentId } : {},
- ),
- },
- S.ManagedSlackAuthorizeResponseSchema,
- )
-
-export async function getManagedSlackConnection(agentId: string) {
- try {
- return await apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/slack/managed`,
- {},
- S.ManagedSlackConnectionSchema,
- )
- } catch (error) {
- if (error instanceof ApiError && error.status === 404) return null
- throw error
- }
-}
-
-export const getManagedSlackConnections = () =>
- apiFetch(
- '/v3/slack/managed/connections',
- {},
- S.ManagedSlackWorkspaceConnectionListSchema,
- ).then((result) => result.data)
-
-export const disconnectManagedSlack = (agentId: string) =>
- apiFetch(
- `/v3/agents/${encodeURIComponent(agentId)}/slack/managed`,
- { method: 'DELETE' },
- S.ManagedSlackDisconnectResponseSchema,
- )
-
-// Credentials — reusable model-provider keys (the raw key is write-only). An
-// agent pins one (credential_id); sessions resolve the agent's, else the org
-// default for the provider.
+// Credentials — model-provider keys for Durable Agent Sessions, reached through
+// the edge's /api/dashboard/v3/* proxy to sessions-api. The agents and sessions
+// pages are gone; only the Credentials page still calls these, and it is
+// removed in a later change.
export const getCredentials = () =>
apiFetch('/v3/credentials', {}, S.CredentialListSchema).then((r) => r.data)
@@ -1038,7 +555,7 @@ export const setDefaultCredential = (id: string) =>
)
// Rotate a credential's secret VALUE (versioned, write-only key). Returns updated
-// metadata (new last4). Switching which credential an agent uses is updateAgent({ credential }).
+// metadata (new last4).
export const rotateCredential = (id: string, key: string) =>
apiFetch(
`/v3/credentials/${id}`,
@@ -1046,234 +563,6 @@ export const rotateCredential = (id: string, key: string) =>
S.CredentialSchema,
)
-// ── Model access (work 011) — org-owned Claude/Codex subscription connections ──
-// The provider token is write-only; every response is normalized metadata only.
-// Secret-bearing provider callbacks terminate at the private credential boundary.
-export const getModelAccessConnections = () =>
- apiFetch(
- '/v3/model-access/connections',
- {},
- S.ModelAccessConnectionListSchema,
- ).then((r) => r.data)
-
-// Starts the personal Codex subscription OAuth flow. Returns a pending intent
-// with an authorize_url the dashboard redirects to. No token is accepted here;
-// the provider credential never crosses the browser.
-export const connectModelAccess = (body: {
- provider: 'openai' | 'anthropic'
- token?: string
- label?: string
-}) =>
- apiFetch(
- '/v3/model-access/connections',
- { method: 'POST', body: JSON.stringify(body) },
- S.ModelAccessConnectResponseSchema,
- )
-
-// Completes the OAuth callback (exchanged server-side at the private credential
-// boundary), returning the connected connection. The authorization code is a
-// one-time exchange value, not a stored credential.
-export const completeModelAccess = (id: string, code: string, state: string) =>
- apiFetch(
- `/v3/model-access/connections/${encodeURIComponent(id)}/complete`,
- { method: 'POST', body: JSON.stringify({ code, state }) },
- S.ModelAccessConnectionSchema,
- )
-
-// Re-validate the held credential against the provider (refresh entitlement /
-// account hint / status). Never returns the token.
-export const validateModelAccessConnection = (id: string) =>
- apiFetch(
- `/v3/model-access/connections/${encodeURIComponent(id)}/validate`,
- { method: 'POST' },
- S.ModelAccessConnectionSchema,
- )
-
-// Disconnect revokes at the provider when supported, then deletes local secret
-// material even if remote revocation fails.
-export const disconnectModelAccess = (id: string) =>
- apiFetch<void>(`/v3/model-access/connections/${encodeURIComponent(id)}`, {
- method: 'DELETE',
- })
-
-// Project-environment enablement of the single org connection for a provider.
-export const getModelAccessBindings = (projectId: string) =>
- apiFetch(
- `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings`,
- {},
- S.ModelAccessBindingListSchema,
- ).then((r) => r.data)
-
-export const putModelAccessBinding = (
- projectId: string,
- provider: 'anthropic' | 'openai',
- environment: 'default' | 'development' | 'production',
- enabled: boolean,
-) =>
- apiFetch(
- `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings/${provider}/${environment}`,
- { method: 'PUT', body: JSON.stringify({ enabled }) },
- S.ModelAccessBindingSchema,
- )
-
-export const deleteModelAccessBinding = (
- projectId: string,
- provider: 'anthropic' | 'openai',
- environment: 'default' | 'development' | 'production',
-) =>
- apiFetch<void>(
- `/v3/projects/${encodeURIComponent(projectId)}/model-access/bindings/${provider}/${environment}`,
- { method: 'DELETE' },
- )
-
-// Sessions — the durable runs.
-export const getSessions = (
- params: {
- agent?: string
- status?: string
- after?: string
- limit?: number
- cursor?: string
- } = {},
-) => {
- const q = new URLSearchParams()
- if (params.agent) q.set('agent', params.agent)
- if (params.status) q.set('status', params.status)
- if (params.after) q.set('after', params.after)
- if (params.limit) q.set('limit', String(params.limit))
- if (params.cursor) q.set('cursor', params.cursor)
- const qs = q.toString()
- return apiFetch(
- `/v3/sessions${qs ? `?${qs}` : ''}`,
- {},
- S.SessionListSchema,
- ).then((r) => r.data)
-}
-
-export const getSession = (id: string) =>
- apiFetch(`/v3/sessions/${id}`, {}, S.SessionSchema)
-
-export const getSessionSources = (id: string) =>
- apiFetch(
- `/v3/sessions/${encodeURIComponent(id)}/sources`,
- {},
- S.SessionSourceListSchema,
- )
-
-// The API wants { agent: <id>, input } (input required). An optional `sources[]` attaches
-// a WORKING repo the agent checks out + opens PRs from — the control plane pins the ref's
-// HEAD when `sha` is omitted (design 010 §24.0). The response is an envelope
-// { session, client_token } — return the session.
-export const createSession = (
- body: {
- agent: string
- input: string
- // Optional per-session model override — runs this model instead of the agent's.
- // Omit to inherit the agent's model. Not supported for flue agents.
- model?: string
- sources?: { repo: string; ref: string; name?: string }[]
- },
- idempotencyKey?: string,
-) =>
- apiFetch(
- '/v3/sessions',
- {
- method: 'POST',
- body: JSON.stringify(body),
- // sessions-api dedups create on the Idempotency-Key header (the edge proxy
- // forwards it) so a retried start-session is safe.
- headers: idempotencyKey
- ? { 'Idempotency-Key': idempotencyKey }
- : undefined,
- },
- z.object({ session: S.SessionSchema, client_token: z.string().optional() }),
- ).then((r) => r.session)
-
-export const cancelSession = (id: string) =>
- apiFetch<void>(`/v3/sessions/${id}/cancel`, { method: 'POST' })
-
-export const archiveSession = (id: string) =>
- apiFetch<void>(`/v3/sessions/${id}/archive`, { method: 'POST' })
-
-// Events — append-only session log. Plain GET today; an SSE (`?stream=sse`)
-// browser-direct path replaces the fetch in the live view later.
-export const getSessionEvents = (id: string, level?: string) =>
- apiFetch(
- `/v3/sessions/${id}/events${level ? `?level=${level}` : ''}`,
- {},
- S.SessionEventListSchema,
- ).then((r) => r.data)
-
-// Turns — the per-submission execution records behind a session (state, timing,
-// usage, error). Read-only; powers the submission-health panel. Newest first.
-export const getSessionTurns = (id: string) =>
- apiFetch(`/v3/sessions/${id}/turns`, {}, S.SessionTurnListSchema).then(
- (r) => r.data,
- )
-
-// The latest turn + its result event (if the turn produced one).
-export const getSessionResult = (id: string) =>
- apiFetch(`/v3/sessions/${id}/result`, {}, S.SessionResultSchema)
-
-// Steer — post a user message into a session.
-export const sendMessage = (
- id: string,
- text: string,
- idempotencyKey?: string,
-) =>
- apiFetch<{ event: { id: string; seq: number } }>(
- `/v3/sessions/${id}/messages`,
- {
- method: 'POST',
- body: JSON.stringify({ text, idempotency_key: idempotencyKey }),
- },
- )
-
-// Webhooks — destinations are session-scoped.
-export const getDestinations = (id: string) =>
- apiFetch(
- `/v3/sessions/${id}/destinations`,
- {},
- z.object({
- data: z.array(S.DestinationSchema),
- next_cursor: z.string().nullish(),
- }),
- ).then((r) => r.data)
-
-export const createDestination = (
- id: string,
- body: {
- url: string
- secret?: string
- level?: string
- types?: string[]
- },
-) =>
- apiFetch(
- `/v3/sessions/${id}/destinations`,
- { method: 'POST', body: JSON.stringify(body) },
- S.DestinationSchema,
- )
-
-export const deleteDestination = (id: string, did: string) =>
- apiFetch<void>(`/v3/sessions/${id}/destinations/${did}`, { method: 'DELETE' })
-
-// Deliveries — the send ledger for a session's destinations.
-export const getDeliveries = (id: string) =>
- apiFetch(
- `/v3/sessions/${id}/deliveries`,
- {},
- z.object({
- data: z.array(S.DeliverySchema),
- next_cursor: z.string().nullish(),
- }),
- ).then((r) => r.data)
-
-export const redeliver = (id: string, deliveryId: string) =>
- apiFetch<void>(`/v3/sessions/${id}/deliveries/${deliveryId}/redeliver`, {
- method: 'POST',
- })
-
// ── Sandbox lifecycle webhooks (org-scoped, Svix-backed at the edge) ─────────
// Reached via /api/dashboard/webhooks* (cookie auth → org), mirroring the public
// /api/webhooks API.
diff --git a/web/src/api/deploy-app-client.test.ts b/web/src/api/deploy-app-client.test.ts
deleted file mode 100644
index 770160f9..00000000
--- a/web/src/api/deploy-app-client.test.ts
+++ /dev/null
@@ -1,88 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { getDeployApp, importAgentFromGithub } from './client'
-
-const deployAppResponse = {
- installed: false,
- install_url: null,
- configure_url: null,
- account: null,
- repository_selection: null,
- repositories: [],
-}
-
-afterEach(() => {
- vi.unstubAllGlobals()
-})
-
-describe('deploy app client', () => {
- it('returns GitHub installation state without a separate capability fork', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => Promise.resolve(Response.json(deployAppResponse))),
- )
-
- await expect(getDeployApp()).resolves.toEqual(deployAppResponse)
- })
-
- it('submits the exact review receipt and preserves source-change recovery', async () => {
- let captured: RequestInit | undefined
- const fetchMock = vi.fn(
- (_input: string | URL | Request, init?: RequestInit) => {
- captured = init
- return Promise.resolve(
- Response.json(
- {
- error: {
- type: 'source_changed_re_review',
- message: 'repository source changed since review',
- },
- },
- { status: 409 },
- ),
- )
- },
- )
- vi.stubGlobal('fetch', fetchMock)
-
- await expect(
- importAgentFromGithub(
- {
- name: 'Support triage',
- credential: 'managed',
- source: {
- type: 'github',
- repo: 'repo_0123456789abcdef01234567',
- path: 'agents/support',
- production_ref: 'main',
- },
- review: {
- sha: 'a'.repeat(40),
- source_profile: 'flue-app-v1',
- fingerprint: `sha256:${'b'.repeat(64)}`,
- },
- },
- 'import-command-1',
- ),
- ).rejects.toMatchObject({
- status: 409,
- type: 'source_changed_re_review',
- })
-
- expect(captured?.method).toBe('POST')
- expect(new Headers(captured?.headers).get('Idempotency-Key')).toBe(
- 'import-command-1',
- )
- const requestBody = captured?.body
- if (typeof requestBody !== 'string') {
- throw new Error('import request body must be JSON')
- }
- const parsedBody = JSON.parse(requestBody) as unknown
- expect(parsedBody).toMatchObject({
- review: {
- sha: 'a'.repeat(40),
- source_profile: 'flue-app-v1',
- fingerprint: `sha256:${'b'.repeat(64)}`,
- },
- })
- })
-})
diff --git a/web/src/api/deployment-schemas.test.ts b/web/src/api/deployment-schemas.test.ts
deleted file mode 100644
index bd4fae2d..00000000
--- a/web/src/api/deployment-schemas.test.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- AgentSchema,
- AgentDeploymentCommandResponseSchema,
- AgentDeploymentListSchema,
- 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('preserves the legacy Flue admission proof without inventing live status', () => {
- const parsed = AgentSchema.parse({
- id: 'agt_legacy',
- invoke_url: 'https://agt-legacy.agents.opencomputer.dev',
- name: 'Legacy Flue agent',
- prompt: null,
- model: 'anthropic/claude-haiku-4-5',
- runtime: 'flue',
- revision: 1,
- active_revision_id: 'rev_legacy',
- deployment_status: {
- deployment_id: 'dep_legacy',
- state: 'ready',
- result: 'created',
- error_class: null,
- live_touched: false,
- live_status: null,
- legacy_live_compatible: true,
- updated_at: '2026-07-14T20:00:00.000Z',
- },
- flue: { agent_name: 'legacy', live: null },
- created_at: '2026-07-14T00:00:00.000Z',
- })
-
- expect(parsed.deployment_status?.legacy_live_compatible).toBe(true)
- expect(parsed.deployment_status?.live_status).toBeNull()
- })
-
- 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('parses the exact cursor envelope for deployment history', () => {
- const parsed = AgentDeploymentListSchema.parse({
- data: [deployment],
- next_cursor: 'opaque-history-cursor',
- })
-
- expect(parsed.data[0]?.id).toBe(deployment.id)
- expect(parsed.next_cursor).toBe('opaque-history-cursor')
- expect(() =>
- AgentDeploymentListSchema.parse({ data: [deployment] }),
- ).toThrow()
- })
-
- it('requires the deployment id returned by a deploy command', () => {
- const response = {
- deployment: {
- id: 'dep_0123456789abcdef01234567',
- state: 'accepted',
- revision_id: null,
- active: false,
- },
- }
-
- expect(
- AgentDeploymentCommandResponseSchema.parse(response).deployment.id,
- ).toBe(response.deployment.id)
- expect(() =>
- AgentDeploymentCommandResponseSchema.parse({
- deployment: { ...response.deployment, id: undefined },
- }),
- ).toThrow()
- })
-
- 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,
- linked_sources: [],
- },
- ],
- })
-
- expect(parsed.repositories[0]?.id).toBeNull()
- })
-
- it('parses owner-scoped linked repository roots for early conflict UX', () => {
- const parsed = DeployAppSchema.parse({
- installed: true,
- repositories: [
- {
- id: 'repo_0123456789abcdef01234567',
- full_name: 'example/flue-agent',
- default_branch: 'main',
- private: false,
- linked_sources: [
- {
- path: '',
- production_ref: 'main',
- status: 'active',
- agent: {
- id: 'agt_0123456789abcdef01234567',
- name: 'Support triage',
- },
- },
- ],
- },
- ],
- })
-
- expect(parsed.repositories[0]?.linked_sources[0]?.agent.name).toBe(
- 'Support triage',
- )
- })
-
- 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/managed-slack-client.test.ts b/web/src/api/managed-slack-client.test.ts
deleted file mode 100644
index 5dae857a..00000000
--- a/web/src/api/managed-slack-client.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { ApiError, getManagedSlackConnection } from './client'
-import { mockFetch } from './mock'
-
-afterEach(() => vi.unstubAllGlobals())
-
-describe('managed Slack missing-resource handling', () => {
- it('maps a real API 404 to no managed connection', async () => {
- vi.stubGlobal(
- 'fetch',
- vi.fn(() =>
- Promise.resolve(Response.json({ error: 'Not found' }, { status: 404 })),
- ),
- )
-
- await expect(
- getManagedSlackConnection('agt_aaaaaaaaaaaaaaaaaaaaaaaa'),
- ).resolves.toBeNull()
- })
-
- it('does not swallow an unrelated status-bearing Error', async () => {
- const transportError = Object.assign(new Error('Proxy failed'), {
- status: 404,
- })
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => Promise.reject(transportError)),
- )
-
- await expect(
- getManagedSlackConnection('agt_aaaaaaaaaaaaaaaaaaaaaaaa'),
- ).rejects.toBe(transportError)
- })
-
- it('uses the same ApiError contract in preview mocks', () => {
- expect(() =>
- mockFetch('/v3/agents/agt_aaaaaaaaaaaaaaaaaaaaaaaa/slack/managed'),
- ).toThrow(ApiError)
- })
-})
diff --git a/web/src/api/mock-contracts.test.ts b/web/src/api/mock-contracts.test.ts
deleted file mode 100644
index a76822c9..00000000
--- a/web/src/api/mock-contracts.test.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { mockFetch } from './mock'
-import {
- AgentListSchema,
- AgentSecurityNotificationListSchema,
- RepositoryAccessSchema,
- RepositorySourceInspectionSchema,
- SessionListSchema,
- SessionSourceListSchema,
- SessionTurnListSchema,
- TurnUsageSchema,
-} from './schemas'
-
-describe('preview API contracts', () => {
- it('keeps the repository review fixture valid against the live schema', () => {
- const response = mockFetch('/v3/github/deploy-app/inspect', {
- method: 'POST',
- })
-
- expect(() => RepositorySourceInspectionSchema.parse(response)).not.toThrow()
- })
-
- it('keeps repository access and source-detail fixtures valid', () => {
- expect(() =>
- RepositoryAccessSchema.parse(
- mockFetch('/v3/agents/agt_fedcba9876543210fedcba98/repository-access'),
- ),
- ).not.toThrow()
- expect(() =>
- SessionSourceListSchema.parse(
- mockFetch('/v3/sessions/ses_a1b2c3/sources'),
- ),
- ).not.toThrow()
- })
-
- it('keeps agent and canonical usage fixtures valid', () => {
- expect(() => AgentListSchema.parse(mockFetch('/v3/agents'))).not.toThrow()
- expect(() =>
- SessionListSchema.parse(mockFetch('/v3/sessions')),
- ).not.toThrow()
- expect(() =>
- SessionTurnListSchema.parse(mockFetch('/v3/sessions/ses_a1b2c3/turns')),
- ).not.toThrow()
- })
-
- it('keeps the global agent-security fixture valid', () => {
- expect(() =>
- AgentSecurityNotificationListSchema.parse(
- mockFetch(
- '/agent-security-notifications?include_acknowledged=false&limit=100',
- ),
- ),
- ).not.toThrow()
- })
-
- it('accepts a reported turn whose total is an explicit lower bound', () => {
- expect(() =>
- TurnUsageSchema.parse({
- reported: true,
- complete: false,
- input_tokens: 10,
- output_tokens: 2,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- tokens: 12,
- }),
- ).not.toThrow()
- })
-})
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index d5081c98..e3eb857e 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -541,450 +541,6 @@ const orgInvitations = [
},
]
-// ── Durable Agent Sessions ─────────────────────────────────────────────
-const agents = [
- {
- id: 'agt_0123456789abcdef01234567',
- invoke_url: 'https://agt-0123456789abcdef01234567.agents.opencomputer.dev',
- name: 'PR Reviewer',
- prompt:
- 'You are a meticulous code reviewer. Flag correctness, security, and clarity issues; be concise and cite line numbers.',
- prompt_hash: 'sha256:9c1a4f',
- model: 'anthropic/claude-opus-4-8',
- runtime: 'claude',
- credential_id: 'cred_anth_1',
- revision: 3,
- created_at: at(20),
- },
- {
- id: 'agt_89abcdef0123456789abcdef',
- invoke_url: 'https://agt-89abcdef0123456789abcdef.agents.opencomputer.dev',
- name: 'Docs Writer',
- prompt:
- 'You write clear, friendly developer documentation. Prefer short sentences and runnable examples.',
- prompt_hash: 'sha256:42bd07',
- model: 'anthropic/claude-sonnet-5',
- runtime: 'claude',
- credential_id: null,
- revision: 1,
- created_at: at(6),
- },
-]
-
-// ── Deploy from GitHub (admin) ───────────────────────────────────────────────
-// The AgentDeploySource panel renders one of three states off two endpoints
-// (GET /v3/github/deploy-app + GET …/deployment-source). The backend can't
-// produce these locally yet (no OC-App install record), so flip DEPLOY_PREVIEW
-// to eyeball each state with no backend:
-// 'not_installed' → the "Install GitHub App" CTA
-// 'installed' → the repo picker (App installed, this agent not yet linked)
-// 'connected' → a linked agent showing live status + Disconnect
-const DEPLOY_PREVIEW = 'installed' as
- | 'not_installed'
- | 'installed'
- | 'connected'
-
-const deployAppInstalled = {
- installed: true,
- install_url: 'https://github.com/apps/opencomputerdev/installations/new',
- configure_url:
- 'https://github.com/apps/opencomputerdev/installations/select_target',
- account: 'acme',
- repository_selection: 'selected' as const,
- repositories: [
- {
- id: 'repo_01k0acmeagents000000000',
- full_name: 'acme/agents',
- default_branch: 'main',
- private: true,
- },
- {
- id: 'repo_01k0supportbot00000000',
- full_name: 'acme/customer-support-automation-and-triage',
- default_branch: 'main',
- private: false,
- },
- {
- id: 'repo_01k0acmeinfra000000000',
- full_name: 'acme/infra',
- default_branch: 'production',
- private: true,
- },
- ],
-}
-const deployAppNotInstalled = {
- installed: false,
- install_url: 'https://github.com/apps/opencomputerdev/installations/new',
- configure_url: null,
- account: null,
- repository_selection: null,
- repositories: [],
-}
-const deployApp =
- DEPLOY_PREVIEW === 'not_installed'
- ? deployAppNotInstalled
- : deployAppInstalled
-
-const repositoryAccess = {
- policy: {
- mode: 'selected' as const,
- repository_ids: [
- 'repo_01k0acmeagents000000000',
- 'repo_01k0supportbot00000000',
- ],
- },
- grant: {
- status: 'active' as const,
- account: 'acme',
- repository_selection: 'selected' as const,
- install_url: 'https://github.com/apps/opencomputerdev/installations/new',
- configure_url:
- 'https://github.com/apps/opencomputerdev/installations/select_target',
- truncated: false,
- },
- effective_repositories: deployAppInstalled.repositories
- .slice(0, 2)
- .map((repo) => ({
- id: repo.id,
- full_name: repo.full_name,
- default_branch: repo.default_branch,
- private: repo.private,
- })),
- unavailable_selected_repositories: [],
-}
-
-// The linked source for the 'connected' preview (echoed for any agent id).
-const deploymentSource = {
- agent_id: 'agt_0123456789abcdef01234567',
- repo_id: 'repo_acme_agents',
- path: 'agents/pr-reviewer',
- production_ref: 'main',
- status: 'active',
- latest_seen_sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
- active_deployed_sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
- full_name: 'acme/agents',
-}
-
-const flueInspection = {
- repository: {
- id: 'repo_01k0supportbot00000000',
- full_name: 'acme/support-bot',
- default_branch: 'main',
- },
- root: '',
- production_ref: 'main',
- sha: 'cbb8766d972199b01d03389d2680970dc29d1d34',
- interpretation: {
- disposition: 'exact' as const,
- source_profile: 'flue-app-v1' as const,
- source_profile_version: 1 as const,
- summary: 'Flue agent detected',
- reason_code: 'flue_detected',
- assumptions: [],
- agent: {
- runtime: 'flue' as const,
- model: 'anthropic/claude-haiku-4-5',
- },
- },
- profile: {
- source_profile: 'flue-app-v1' as const,
- source_profile_version: 1 as const,
- 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: [],
- },
- review_fingerprint: `sha256:${'b'.repeat(64)}`,
- candidate_roots: [],
- candidate_roots_truncated: false,
-}
-
-const importedAgent = {
- id: 'agt_fedcba9876543210fedcba98',
- invoke_url: 'https://agt-fedcba9876543210fedcba98.agents.opencomputer.dev',
- 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,
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- review_fingerprint: flueInspection.review_fingerprint,
-}
-
-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',
- allowed_actions: ['view_commit', 'deploy_latest'],
- 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 = [
- {
- id: 'rev_3',
- number: 3,
- digest: 'sha256:c0ffee0011223344',
- created_at: at(0, 1),
- active: true,
- sha: '4a3f654010a5c16a101a6f0b3bf7aec1d3839d4f',
- ref: 'main',
- },
- {
- id: 'rev_2',
- number: 2,
- digest: 'sha256:deadbeef55667788',
- created_at: at(0, 3),
- active: false,
- sha: null,
- ref: null,
- },
- {
- id: 'rev_1',
- number: 1,
- digest: 'sha256:0123456789abcdef',
- created_at: at(2),
- active: false,
- sha: null,
- ref: null,
- },
-]
-const agentDeploys = [
- {
- id: 'dep_3',
- state: 'ready',
- result: 'created',
- source: { via: 'repo', git_sha: '4a3f654010a5c16a' },
- actor: null,
- revision_id: 'rev_3',
- created_at: at(0, 1),
- },
- {
- id: 'dep_2',
- state: 'ready',
- result: 'created',
- source: { via: 'api' },
- actor: null,
- revision_id: 'rev_2',
- created_at: at(0, 3),
- },
- {
- id: 'dep_1',
- state: 'failed',
- result: 'failed',
- source: { via: 'repo', git_sha: 'badc0ffee1234567' },
- actor: null,
- revision_id: null,
- created_at: at(1),
- },
-]
-const agentSkills = {
- revision: { id: 'rev_3', number: 3, digest: 'sha256:c0ffee0011223344' },
- skill_bundle_digest: 'sha256:c0ffee0011223344',
- skills: [
- {
- name: 'hello',
- description: 'A trivial example skill.',
- files: [{ path: 'hello/SKILL.md', mode: 33188, size: 240 }],
- },
- ],
-}
-
-// A connected Slack app for the first agent (the AgentDetail Slack panel).
-const slackConnection = {
- id: 'sla_5p6q7r',
- agent_id: 'agt_0123456789abcdef01234567',
- handle: 'PR Reviewer',
- slack_app_id: 'A0123ABCDEF',
- team_id: 'T0123ABCDEF',
- account_login: 'Acme',
- status: 'active',
- bot_token_verified: true,
- signing_verified: false,
- created_at: at(5),
- updated_at: at(0, 2),
-}
-
-// START-intent response for the Slack connect wizard (POST …/slack/manifest).
-const slackManifest = {
- manifest: {
- display_information: { name: 'PR Reviewer' },
- features: {
- bot_user: { display_name: 'PR Reviewer', always_online: true },
- },
- oauth_config: { scopes: { bot: ['app_mentions:read', 'chat:write'] } },
- settings: {
- event_subscriptions: {
- request_url: 'https://api.opencomputer.dev/v3/slack/events/abc123nonce',
- bot_events: ['app_mention'],
- },
- },
- },
- create_url: 'https://api.slack.com/apps',
- steps: [
- 'Open api.slack.com/apps → Create New App → From a manifest.',
- 'Pick your workspace, paste the manifest, and click Create.',
- 'Click Install to Workspace and approve.',
- 'Copy three values back here: App ID, Bot User OAuth Token (xoxb-…), and Signing Secret.',
- ],
- status: 'pending',
-}
-
const credentials = [
{
id: 'cred_anth_1',
@@ -1004,246 +560,6 @@ const credentials = [
},
]
-const sessions = [
- {
- // Flue reports best-effort per-session attribution; its gateway remains the
- // monetary authority.
- id: 'ses_a1b2c3',
- status: 'running',
- agent_id: 'agt_0123456789abcdef01234567',
- agent_snapshot: { runtime: 'flue', model: 'anthropic/claude-haiku-4-5' },
- head: 24,
- usage: {
- active_seconds: 18,
- reported_turns: 1,
- unreported_turns: 0,
- complete: true,
- input_tokens: 1240,
- output_tokens: 185,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 620,
- tokens: 2045,
- attribution: 'best_effort',
- },
- created_at: at(0, 1),
- last_turn: { state: 'running' },
- sandboxes: { brain: 'sbx_a1b2c3d4e5', hands: 'sbx_f6g7h8i9j0' },
- },
- {
- id: 'ses_d4e5f6',
- status: 'awaiting_input',
- agent_id: 'agt_0123456789abcdef01234567',
- agent_snapshot: { runtime: 'claude', model: 'anthropic/claude-sonnet-5' },
- head: 12,
- usage: {
- active_seconds: 42,
- reported_turns: 2,
- unreported_turns: 0,
- complete: true,
- input_tokens: 8200,
- output_tokens: 640,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- tokens: 8840,
- total_cost_usd: 0.0231,
- attribution: 'exact',
- },
- created_at: at(0, 3),
- last_turn: { state: 'ok', yield_reason: 'needs_input' },
- },
- {
- id: 'ses_g7h8i9',
- status: 'idle',
- agent_id: 'agt_89abcdef0123456789abcdef',
- agent_snapshot: { runtime: 'pi', model: 'anthropic/claude-sonnet-5' },
- head: 41,
- usage: {},
- created_at: at(1, 2),
- last_turn: { state: 'ok', yield_reason: 'completed' },
- },
- {
- id: 'ses_j1k2l3',
- status: 'failed',
- agent_id: 'agt_0123456789abcdef01234567',
- agent_snapshot: { runtime: 'codex', model: 'openai/gpt-5.3-codex' },
- head: 8,
- usage: {},
- created_at: at(2, 5),
- last_turn: { state: 'error', yield_reason: 'error' },
- },
- {
- id: 'ses_m4n5o6',
- status: 'archived',
- agent_id: 'agt_89abcdef0123456789abcdef',
- agent_snapshot: { runtime: 'claude', model: 'anthropic/claude-opus-4-8' },
- head: 60,
- usage: {},
- created_at: at(4, 1),
- last_turn: { state: 'ok', yield_reason: 'completed' },
- },
-]
-
-const sessionSources = [
- {
- name: 'app',
- repo_id: 'repo_01k0acmeagents000000000',
- full_name: 'acme/agents',
- requested_ref: 'main',
- status: 'resolved',
- path: '/workspace/sources/app',
- sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
- resolved_sha: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0',
- },
-]
-
-const sessionEvents = [
- {
- id: 'evt_1',
- seq: 1,
- type: 'user.message',
- level: 'user',
- actor: { type: 'user', display: 'You' },
- body: {
- text: 'Review PR #412 and open a follow-up if anything needs fixing.',
- },
- ts: at(0, 1),
- },
- {
- id: 'evt_2',
- seq: 2,
- type: 'turn.started',
- level: 'progress',
- actor: { type: 'runtime' },
- ts: at(0, 1),
- },
- {
- id: 'evt_3',
- seq: 3,
- type: 'agent.thinking',
- level: 'progress',
- actor: { type: 'agent', display: 'PR Reviewer' },
- body: {
- text: 'Fetch the PR head, then read the auth middleware diff before commenting.',
- },
- ts: at(0, 1),
- },
- {
- id: 'evt_4',
- seq: 4,
- type: 'tool.call',
- level: 'progress',
- actor: { type: 'runtime' },
- body: { tool: 'bash', input: 'git fetch origin pull/412/head' },
- ts: at(0, 1),
- },
- {
- id: 'evt_5',
- seq: 5,
- type: 'exec.completed',
- level: 'progress',
- actor: { type: 'runtime' },
- body: {
- tool: 'bash',
- summary: 'fetched pull/412/head → FETCH_HEAD',
- duration_ms: 412,
- },
- ts: at(0, 1),
- },
- {
- id: 'evt_6',
- seq: 6,
- type: 'agent.message',
- level: 'user',
- actor: { type: 'agent', display: 'PR Reviewer' },
- body: {
- text: 'The diff touches the auth middleware. The token-refresh path looks correct, but the retry has no ceiling — I will flag it.',
- },
- ts: at(0, 1),
- },
- {
- id: 'evt_7',
- seq: 7,
- type: 'turn.completed',
- level: 'user',
- actor: { type: 'runtime' },
- body: { yield_reason: 'needs_input' },
- ts: at(0, 1),
- },
-]
-
-// Turns power the submission-health panel (GET /v3/sessions/:id/turns), newest first.
-const sessionTurns = [
- {
- id: 'trn_2',
- state: 'ok',
- yield_reason: 'needs_input',
- started_at: at(0, 1),
- completed_at: at(0, 1),
- active_seconds: 7,
- usage: {
- reported: true,
- input_tokens: 4200,
- output_tokens: 310,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- tokens: 4510,
- total_cost_usd: 0.0121,
- },
- },
- {
- id: 'trn_1',
- state: 'error',
- yield_reason: 'error',
- started_at: at(0, 2),
- completed_at: at(0, 2),
- active_seconds: 3,
- usage: { reported: false },
- error: {
- code: 'provision_infra',
- message: 'brain sandbox failed to start',
- },
- },
-]
-
-const destinations = [
- {
- id: 'dst_1',
- url: 'https://acme.dev/hooks/oc',
- level: 'user',
- types: ['turn.completed', 'error.*'],
- enabled: true,
- has_secret: true,
- created_at: at(0, 2),
- updated_at: at(0, 2),
- },
-]
-
-const deliveries = [
- {
- id: 'dlv_1',
- destination: 'dst_1',
- event_id: 'evt_7',
- event_seq: 7,
- status: 'delivered',
- attempts: 1,
- last_attempt_at: at(0, 1),
- response_code: 200,
- created_at: at(0, 1),
- },
- {
- id: 'dlv_2',
- destination: 'dst_1',
- event_id: 'evt_6',
- event_seq: 6,
- status: 'failed',
- attempts: 3,
- last_attempt_at: at(0, 1),
- response_code: 502,
- error: 'upstream returned 502',
- created_at: at(0, 1),
- },
-]
-
const sandboxWebhooks = [
{
id: 'whk_1',
@@ -1289,7 +605,7 @@ const sandboxWebhookDeliveries = [
type Handler = () => unknown
// A handler may return NOT_FOUND to mimic a 404 (mockFetch throws, like a real
-// missing resource) — used for an agent with no deployment-source link.
+// missing resource). No handler uses it today.
const NOT_FOUND = Symbol('not_found')
const managedAgentItems: Array<{
@@ -1725,10 +1041,6 @@ function previewOrgSecrets() {
// Ordered most-specific first. Matched against the path (without /api/dashboard).
const ROUTES: Array<[RegExp, Handler]> = [
[/^\/me$/, () => me],
- [
- /^\/agent-security-notifications(?:\?.*)?$/,
- () => ({ data: [], next_cursor: null }),
- ],
[/^\/managed-agents\/agents$/, () => ({ agents: managedAgentItems })],
[/^\/managed-agents\/computer$/, previewComputer],
[/^\/managed-agents\/computer\/secrets$/, previewOrgSecrets],
@@ -1928,68 +1240,8 @@ const ROUTES: Array<[RegExp, Handler]> = [
[/^\/org\/invitations$/, () => orgInvitations],
[/^\/org\/custom-domain$/, () => ({})],
[/^\/org$/, () => org],
- [/^\/agents$/, () => []],
- // Durable Agent Sessions — lists return the { data: [...] } envelope.
- [/^\/v3\/slack\/managed\/connections$/, () => ({ data: [] })],
- [/^\/v3\/agents\/[^/]+\/slack\/managed$/, () => NOT_FOUND],
- [/^\/v3\/agents\/[^/]+\/slack$/, () => slackConnection],
- [/^\/v3\/github\/deploy-app$/, () => deployApp],
- [/^\/v3\/agents\/[^/]+\/repository-access$/, () => repositoryAccess],
- [
- /^\/v3\/agents\/[^/]+\/deployments\/[^/]+\/logs(?:\?.*)?$/,
- () => ({
- data: flueDeploymentLogs,
- next_cursor: 'deployment-log-103',
- has_more: false,
- }),
- ],
- [
- /^\/v3\/agents\/[^/]+\/deployments\/dep_flue_failed$/,
- () => failedFlueDeployment,
- ],
- [
- /^\/v3\/agents\/agt_fedcba9876543210fedcba98\/deployments(?:\?.*)?$/,
- () => ({
- data: [flueDeployment, failedFlueDeployment],
- next_cursor: null,
- }),
- ],
- [
- /^\/v3\/agents\/[^/]+\/deployments(?:\?.*)?$/,
- () => ({ data: [], next_cursor: null }),
- ],
- [/^\/v3\/agents\/[^/]+\/deployments\/[^/]+$/, () => flueDeployment],
- [
- /^\/v3\/agents\/agt_fedcba9876543210fedcba98\/deployment-source$/,
- () => ({ source: importedSource }),
- ],
- [
- /^\/v3\/agents\/[^/]+\/deployment-source$/,
- () =>
- DEPLOY_PREVIEW === 'connected' ? { source: deploymentSource } : NOT_FOUND,
- ],
- [/^\/v3\/agents\/[^/]+\/deploys$/, () => ({ data: agentDeploys })],
- [/^\/v3\/agents\/[^/]+\/revisions$/, () => ({ data: agentRevisions })],
- [/^\/v3\/agents\/[^/]+\/skills$/, () => agentSkills],
- [
- /^\/v3\/agents\/[^/]+\/hooks(?:\?.*)?$/,
- () => ({ data: [], next_cursor: null }),
- ],
- [/^\/v3\/agents\/agt_fedcba9876543210fedcba98$/, () => importedAgent],
- [/^\/v3\/agents\/[^/]+$/, () => agents[0]],
- [/^\/v3\/agents$/, () => ({ data: [...agents, importedAgent] })],
+ // The Credentials page is the last /v3 caller (removed in a later change).
[/^\/v3\/credentials$/, () => ({ data: credentials })],
- [/^\/v3\/sessions\/[^/]+\/sources$/, () => sessionSources],
- [/^\/v3\/sessions\/[^/]+\/events/, () => ({ data: sessionEvents })],
- [/^\/v3\/sessions\/[^/]+\/turns$/, () => ({ data: sessionTurns })],
- [
- /^\/v3\/sessions\/[^/]+\/result$/,
- () => ({ last_turn: sessionTurns[0], result: sessionEvents[6] }),
- ],
- [/^\/v3\/sessions\/[^/]+\/destinations$/, () => ({ data: destinations })],
- [/^\/v3\/sessions\/[^/]+\/deliveries$/, () => ({ data: deliveries })],
- [/^\/v3\/sessions\/[^/]+$/, () => sessions[0]],
- [/^\/v3\/sessions(\?.*)?$/, () => ({ data: sessions, next_cursor: null })],
[
/^\/webhooks\/[^/]+\/deliveries$/,
() => ({ data: sandboxWebhookDeliveries }),
@@ -2052,33 +1304,6 @@ const POST_ROUTES: [RegExp, () => unknown][] = [
/^\/managed-agents\/sessions\/[^/]+\/suspend$/,
() => ({ id: 'session_preview', status: 'suspended' }),
],
- [/^\/v3\/agents\/[^/]+\/repository-access$/, () => repositoryAccess],
- [/^\/v3\/github\/deploy-app\/inspect$/, () => flueInspection],
- [
- /^\/v3\/agents\/import$/,
- () => ({
- agent: importedAgent,
- source: importedSource,
- deployment: flueDeployment,
- }),
- ],
- [
- /^\/v3\/agents\/[^/]+\/deployments$/,
- () => ({
- deployment: {
- id: flueDeployment.id,
- state: flueDeployment.state,
- revision_id: flueDeployment.revision_id,
- active: flueDeployment.active,
- },
- }),
- ],
- [/^\/v3\/agents$/, () => agents[0]],
- [/^\/v3\/agents\/[^/]+\/slack\/manifest$/, () => slackManifest],
- [
- /^\/v3\/agents\/[^/]+\/slack$/,
- () => ({ ...slackConnection, status: 'active' }),
- ],
]
export function mockFetch<T>(path: string, options: RequestInit = {}): T {
diff --git a/web/src/api/repository-access-client.test.ts b/web/src/api/repository-access-client.test.ts
deleted file mode 100644
index cabe916b..00000000
--- a/web/src/api/repository-access-client.test.ts
+++ /dev/null
@@ -1,85 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import {
- getRepositoryAccess,
- getSessionSources,
- updateRepositoryAccess,
-} from './client'
-
-const access = {
- policy: { mode: 'selected' as const, repository_ids: ['repo_1'] },
- grant: {
- status: 'active' as const,
- account: 'acme',
- repository_selection: 'selected' as const,
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- truncated: false,
- },
- effective_repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/app',
- default_branch: 'main',
- private: true,
- },
- ],
- unavailable_selected_repositories: [],
-}
-
-afterEach(() => vi.unstubAllGlobals())
-
-describe('repository access client', () => {
- it('reads and atomically replaces an agent policy', async () => {
- const calls: Array<{ input: string; init?: RequestInit }> = []
- vi.stubGlobal(
- 'fetch',
- vi.fn((input: string | URL | Request, init?: RequestInit) => {
- const url =
- typeof input === 'string'
- ? input
- : input instanceof URL
- ? input.href
- : input.url
- calls.push({ input: url, init })
- return Promise.resolve(Response.json(access))
- }),
- )
-
- await expect(getRepositoryAccess('agt_/unsafe')).resolves.toEqual(access)
- await expect(
- updateRepositoryAccess('agt_/unsafe', {
- mode: 'selected',
- repository_ids: ['repo_1'],
- }),
- ).resolves.toEqual(access)
-
- expect(calls[0]?.input).toBe(
- '/api/dashboard/v3/agents/agt_%2Funsafe/repository-access',
- )
- expect(calls[1]?.init?.method).toBe('PUT')
- expect(calls[1]?.init?.body).toBe(
- JSON.stringify({ mode: 'selected', repository_ids: ['repo_1'] }),
- )
- })
-
- it('reads source identity and the pinned ref from session detail', async () => {
- const sources = [
- {
- name: 'app',
- repo_id: 'repo_1',
- full_name: 'acme/app',
- requested_ref: 'main',
- status: 'resolved',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- resolved_sha: 'b'.repeat(40),
- },
- ]
- vi.stubGlobal(
- 'fetch',
- vi.fn(() => Promise.resolve(Response.json(sources))),
- )
-
- await expect(getSessionSources('ses_1')).resolves.toEqual(sources)
- })
-})
diff --git a/web/src/api/repository-access-schemas.test.ts b/web/src/api/repository-access-schemas.test.ts
deleted file mode 100644
index 0051c90e..00000000
--- a/web/src/api/repository-access-schemas.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { RepositoryAccessSchema, SessionSourceListSchema } from './schemas'
-
-describe('repository access schemas', () => {
- it('accepts an intentionally empty selected policy and a truncated grant', () => {
- expect(
- RepositoryAccessSchema.parse({
- policy: { mode: 'selected', repository_ids: [] },
- grant: {
- status: 'active',
- account: 'acme',
- repository_selection: 'selected',
- install_url: 'https://github.test/install',
- configure_url: null,
- truncated: true,
- },
- effective_repositories: [],
- unavailable_selected_repositories: [
- { id: 'repo_hidden', full_name: 'acme/hidden' },
- ],
- }).grant.truncated,
- ).toBe(true)
- })
-
- it('requires null effective repositories when the server reports no list', () => {
- const result = RepositoryAccessSchema.safeParse({
- policy: { mode: 'all' },
- grant: {
- status: 'unavailable',
- account: null,
- repository_selection: null,
- install_url: 'https://github.test/install',
- configure_url: null,
- truncated: false,
- },
- effective_repositories: null,
- unavailable_selected_repositories: [],
- })
- expect(result.success).toBe(true)
- })
-
- it('keeps new source identity fields optional for older responses', () => {
- expect(
- SessionSourceListSchema.parse([
- {
- name: 'app',
- status: 'pending',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- },
- ]),
- ).toHaveLength(1)
- })
-})
diff --git a/web/src/api/repository-inspection-schemas.test.ts b/web/src/api/repository-inspection-schemas.test.ts
deleted file mode 100644
index 0b3a07a0..00000000
--- a/web/src/api/repository-inspection-schemas.test.ts
+++ /dev/null
@@ -1,236 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { RepositorySourceInspectionSchema } from './schemas'
-
-const reviewFingerprint = `sha256:${'b'.repeat(64)}`
-
-const common = {
- repository: {
- id: 'repo_0123456789abcdef01234567',
- full_name: 'example/agent',
- default_branch: 'main',
- },
- root: '',
- production_ref: 'main',
- sha: 'a'.repeat(40),
- review_fingerprint: reviewFingerprint,
- candidate_roots: [],
- candidate_roots_truncated: false,
-}
-
-describe('repository source inspection schema', () => {
- it('accepts a full Flue app without losing its review projection', () => {
- const parsed = RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'exact',
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- summary: 'Flue agent detected',
- reason_code: 'flue_detected',
- assumptions: [],
- agent: { runtime: 'flue', model: 'anthropic/claude-haiku-4-5' },
- },
- profile: {
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- manifest: {
- schema_version: 1,
- entrypoint: 'support-triage',
- model: 'anthropic/claude-haiku-4-5',
- runtime: { family: 'flue', type: 'default' },
- vars: {},
- },
- package: {
- name: 'support-agent',
- node_engine: '>=22.19 <23',
- flue_cli: '^1.0.0',
- },
- lockfile: { version: 3 },
- builder: { node: '22.19.0' },
- source: { files: 12, bytes: 4096 },
- variable_names: [],
- warnings: [],
- },
- })
-
- expect(parsed.profile?.manifest.entrypoint).toBe('support-triage')
- expect(parsed.review_fingerprint).toBe(reviewFingerprint)
- })
-
- it('accepts the bounded prompt-defined Flue profile', () => {
- const parsed = RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'exact',
- source_profile: 'flue-prompt-v1',
- source_profile_version: 1,
- summary: 'Prompt-defined Flue agent detected',
- reason_code: 'flue_prompt_detected',
- assumptions: [],
- agent: { runtime: 'flue', model: 'anthropic/claude-haiku-4-5' },
- },
- profile: {
- source_profile: 'flue-prompt-v1',
- source_profile_version: 1,
- manifest: {
- schema_version: 1,
- entrypoint: 'support-triage',
- model: 'anthropic/claude-haiku-4-5',
- runtime: { family: 'flue', type: 'default' },
- vars: {},
- },
- package: {
- name: 'opencomputer-flue-prompt-agent',
- node_engine: '>=22.19 <23',
- flue_cli: '1.0.0-beta.9',
- },
- lockfile: { version: 3 },
- builder: {
- node: '22.19.0',
- synthesis_template: 'flue-prompt-template-v1',
- },
- source: { files: 4, bytes: 2048 },
- prompt: { bytes: 256 },
- skills: { count: 2, bytes: 1024, names: ['review', 'triage'] },
- variable_names: [],
- warnings: [],
- },
- })
-
- expect(parsed.profile?.source_profile).toBe('flue-prompt-v1')
- if (parsed.profile?.source_profile === 'flue-prompt-v1') {
- expect(parsed.profile.skills.names).toEqual(['review', 'triage'])
- expect(parsed.profile.builder.synthesis_template).toBe(
- 'flue-prompt-template-v1',
- )
- }
- })
-
- it('treats broken Flue and unrecognized source as review results', () => {
- const invalid = RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'invalid',
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- summary: 'Flue manifest missing',
- reason_code: 'flue_manifest_missing',
- issues: [
- {
- code: 'flue_manifest_missing',
- message: 'Add agent.toml to this Flue root.',
- },
- ],
- },
- profile: null,
- })
- const unrecognized = RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'unrecognized',
- source_profile: null,
- source_profile_version: null,
- summary: "We couldn't find an agent definition in this folder",
- reason_code: 'unrecognized_source',
- },
- profile: null,
- candidate_roots: [
- {
- path: 'agents/support',
- source_profile: null,
- summary: 'Agent manifest found',
- marker: 'agent.toml',
- },
- {
- path: 'apps/triage',
- source_profile: 'flue-app-v1',
- summary: 'Flue configuration found',
- marker: 'flue.config.ts',
- },
- ],
- candidate_roots_truncated: true,
- })
-
- expect(invalid.interpretation.disposition).toBe('invalid')
- expect(unrecognized.candidate_roots).toHaveLength(2)
- expect(unrecognized.candidate_roots_truncated).toBe(true)
- })
-
- it('rejects speculative profiles and fallback dispositions', () => {
- expect(() =>
- RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'exact',
- source_profile: 'oc-soft-agent-v1',
- source_profile_version: 1,
- summary: 'Soft agent detected',
- reason_code: 'soft_agent_detected',
- assumptions: [],
- agent: { runtime: 'pi', model: 'openai/gpt-5' },
- },
- profile: null,
- }),
- ).toThrow()
- expect(() =>
- RepositorySourceInspectionSchema.parse({
- ...common,
- interpretation: {
- disposition: 'fallback',
- source_profile: null,
- source_profile_version: null,
- summary: 'Generated defaults',
- reason_code: 'fallback',
- },
- profile: null,
- }),
- ).toThrow()
- })
-
- it('rejects crossed invalid profile identities and malformed receipts', () => {
- const invalid = {
- ...common,
- profile: null,
- interpretation: {
- disposition: 'invalid',
- summary: 'Invalid source',
- reason_code: 'manifest_invalid',
- issues: [],
- },
- }
- expect(() =>
- RepositorySourceInspectionSchema.parse({
- ...invalid,
- interpretation: {
- ...invalid.interpretation,
- source_profile: 'flue-app-v1',
- source_profile_version: null,
- },
- }),
- ).toThrow()
- expect(() =>
- RepositorySourceInspectionSchema.parse({
- ...invalid,
- interpretation: {
- ...invalid.interpretation,
- source_profile: null,
- source_profile_version: 1,
- },
- }),
- ).toThrow()
- expect(() =>
- RepositorySourceInspectionSchema.parse({
- ...common,
- review_fingerprint: 'sha256:not-a-digest',
- profile: null,
- interpretation: {
- disposition: 'unrecognized',
- source_profile: null,
- source_profile_version: null,
- summary: 'No agent found',
- reason_code: 'unrecognized_source',
- },
- }),
- ).toThrow()
- })
-})
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index c5e0b8a5..b1cd424b 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -408,521 +408,9 @@ export const SandboxWebhookDeliveryListSchema = z.object({
data: z.array(SandboxWebhookDeliverySchema),
})
-// ── Durable Agent Sessions ───────────────────────────────────────────────────
-// Mirrors the sessions-api contract verbatim (snake_case as the API returns
-// it) — no transform layer to keep in sync. Reached via the edge proxy; lenient
-// string fields so a new server enum never fails validation.
-
-export const AgentSchema = z.object({
- id: z.string(),
- name: z.string(),
- invoke_url: z.string(),
- prompt: z.string().nullish(),
- prompt_hash: z.string().nullish(),
- model: z.string(),
- runtime: z.string(),
- credential_id: z.string().nullable().optional(),
- revision: z.number().optional(),
- // Agent Revisions (design 009): the active production pointer + a summary of it.
- active_revision_id: z.string().nullish(),
- active_revision: z
- .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(),
- legacy_live_compatible: z.boolean().optional(),
- 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? }.
-export const AgentListSchema = z.object({
- data: z.array(AgentSchema),
- next_cursor: z.string().nullish(),
-})
-
-// Agent Revisions (design 009) — immutable deployed versions of an agent's behavior.
-// `active` flags the production pointer; rollback = activate an earlier revision.
-export const AgentRevisionSchema = z.object({
- id: z.string(),
- number: z.number(),
- digest: z.string(),
- created_at: z.string(),
- active: z.boolean(),
- sha: z.string().nullish(), // commit that produced it (null for dashboard/inline revisions)
- ref: z.string().nullish(), // branch the commit came from
-})
-export const AgentRevisionListSchema = z.object({
- data: z.array(AgentRevisionSchema),
-})
-// A deploy event (provenance + state); one revision can be produced by many deploys.
-export const AgentDeploySchema = z.object({
- id: z.string(),
- state: z.string(), // validating | uploading | ready | failed
- result: z.string().nullish(), // created | deduped | failed
- source: record.nullish(), // { via, repo_id?, path?, git_sha? }
- actor: z.string().nullish(),
- revision_id: z.string().nullish(),
- created_at: z.string(),
-})
-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 AgentDeploymentListSchema = z.object({
- data: z.array(AgentDeploymentSchema),
- next_cursor: z.string().nullable(),
-})
-
-export const AgentDeploymentCommandResponseSchema = z.object({
- deployment: z.object({
- id: z.string(),
- state: z.string(),
- revision_id: z.string().nullish(),
- active: z.boolean(),
- }),
-})
-
-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(),
-})
-// A file within a skill (path/mode/size).
-export const SkillFileSchema = z.object({
- path: z.string(),
- mode: z.number(),
- size: z.number(),
-})
-// A skill — the domain unit: a folder with a SKILL.md (name + description from frontmatter).
-export const SkillItemSchema = z.object({
- name: z.string(),
- description: z.string().nullish(),
- files: z.array(SkillFileSchema).default([]),
-})
-// The agent's skills (GET …/skills) — the active revision's skills, enumerated.
-export const AgentSkillsSchema = z.object({
- revision: z
- .object({ id: z.string(), number: z.number(), digest: z.string() })
- .nullish(),
- skill_bundle_digest: z.string().nullish(),
- skills: z.array(SkillItemSchema).default([]),
-})
-// The deploy-shaped response from POST …/revisions.
-export const DeployResultSchema = z.object({
- deploy_id: z.string(),
- state: z.string(),
- result: z.string().nullish(),
- revision: z
- .object({
- id: z.string(),
- number: z.number(),
- digest: z.string(),
- active: z.boolean(),
- })
- .nullish(),
-})
-
-// Deployment source — the agent ⟷ repo dir bind for push-to-deploy (deploy-from-github).
-export const DeploymentSourceSchema = z.object({
- agent_id: z.string(),
- repo_id: z.string(),
- path: z.string(),
- production_ref: z.string(),
- status: z.string(), // active | source_profile_changed | path_missing | ref_missing | auth_required | repo_not_selected | app_suspended | error
- latest_seen_sha: z.string().nullish(),
- active_deployed_sha: z.string().nullish(),
- full_name: z.string().nullish(), // "owner/repo" (joined from the repo row)
- source_profile: z.enum(['flue-app-v1', 'flue-prompt-v1']).nullish(),
- source_profile_version: z.literal(1).nullish(),
- review_fingerprint: z.string().nullish(),
-})
-export const DeploymentSourceResponseSchema = z.object({
- source: DeploymentSourceSchema,
-})
-
-// 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(),
- linked_sources: z
- .array(
- z.object({
- path: z.string(),
- production_ref: z.string(),
- status: z.string(),
- agent: z.object({ id: z.string(), name: z.string() }),
- }),
- )
- .default([]),
-})
-export const DeployAppSchema = z.object({
- installed: z.boolean(),
- install_url: z.string().nullish(),
- configure_url: z.string().nullish(),
- account: z.string().nullish(),
- repository_selection: z.enum(['all', 'selected']).nullish(),
- repositories: z.array(DeployAppRepoSchema).default([]),
-})
-
-// GitHub repositories a Flue agent may use as working sources. This is
-// intentionally separate from DeploymentSourceSchema: a deployment source
-// provides the agent's code, while this policy bounds repositories the running
-// agent may check out and publish to.
-export const RepositoryAccessPolicySchema = z.union([
- z.object({ mode: z.literal('all') }),
- z.object({
- mode: z.literal('selected'),
- repository_ids: z.array(z.string()),
- }),
-])
-export const RepositoryAccessRepositorySchema = z.object({
- id: z.string(),
- full_name: z.string(),
- default_branch: z.string(),
- private: z.boolean(),
-})
-export const RepositoryAccessSchema = z.object({
- policy: RepositoryAccessPolicySchema,
- grant: z.object({
- status: z.enum(['active', 'not_installed', 'unavailable']),
- account: z.string().nullable(),
- repository_selection: z.enum(['all', 'selected']).nullable(),
- install_url: z.string(),
- configure_url: z.string().nullable(),
- truncated: z.boolean(),
- }),
- effective_repositories: z.array(RepositoryAccessRepositorySchema).nullable(),
- unavailable_selected_repositories: z
- .array(z.object({ id: z.string(), full_name: z.string() }))
- .default([]),
-})
-export const LinkResultSchema = z.object({
- source: DeploymentSourceSchema,
- deployment_id: z.string().nullish(),
- deploy_error: z.object({ type: z.string(), message: z.string() }).nullish(),
-})
-
-export const RepositoryReviewIssueSchema = z.object({
- code: z.string(),
- message: z.string(),
- path: z.string().optional(),
-})
-
-export const RepositoryCandidateRootSchema = z.object({
- path: z.string(),
- source_profile: z.enum(['flue-app-v1', 'flue-prompt-v1']).nullable(),
- summary: z.string(),
- marker: z.enum([
- 'agent.toml',
- 'flue.config.ts',
- 'flue.config.js',
- 'flue.config.mjs',
- 'flue.config.cjs',
- ]),
-})
-
-const FlueSourceProfileBaseSchema = z.object({
- source_profile_version: z.literal(1),
- 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(),
- synthesis_template: z.string().optional(),
- }),
- source: z.object({ files: z.number(), bytes: z.number() }),
- variable_names: z.array(z.string()).default([]),
- warnings: z.array(RepositoryReviewIssueSchema).default([]),
-})
-
-export const FlueSourceProfileSchema = z.union([
- FlueSourceProfileBaseSchema.extend({
- source_profile: z.literal('flue-app-v1'),
- }),
- FlueSourceProfileBaseSchema.extend({
- source_profile: z.literal('flue-prompt-v1'),
- prompt: z.object({ bytes: z.number() }),
- skills: z.object({
- count: z.number(),
- bytes: z.number(),
- names: z.array(z.string()),
- }),
- builder: z.object({
- node: z.string(),
- synthesis_template: z.string(),
- }),
- }),
-])
-
-const ExactRepositorySourceInterpretationBase = z.object({
- disposition: z.literal('exact'),
- source_profile_version: z.literal(1),
- summary: z.string(),
- reason_code: z.string(),
- assumptions: z.array(z.string()).default([]),
- agent: z.object({
- runtime: z.literal('flue'),
- model: z.string(),
- }),
-})
-
-const ExactRepositorySourceInterpretationSchema = z.union([
- ExactRepositorySourceInterpretationBase.extend({
- source_profile: z.literal('flue-app-v1'),
- }),
- ExactRepositorySourceInterpretationBase.extend({
- source_profile: z.literal('flue-prompt-v1'),
- }),
-])
-
-const InvalidRepositorySourceInterpretationBase = z.object({
- disposition: z.literal('invalid'),
- summary: z.string(),
- reason_code: z.string(),
- issues: z.array(RepositoryReviewIssueSchema).default([]),
-})
-
-const InvalidRepositorySourceInterpretationSchema = z.union([
- InvalidRepositorySourceInterpretationBase.extend({
- source_profile: z.literal('flue-app-v1'),
- source_profile_version: z.literal(1),
- }),
- InvalidRepositorySourceInterpretationBase.extend({
- source_profile: z.literal('flue-prompt-v1'),
- source_profile_version: z.literal(1),
- }),
- InvalidRepositorySourceInterpretationBase.extend({
- source_profile: z.null(),
- source_profile_version: z.null(),
- }),
-])
-
-const UnrecognizedRepositorySourceInterpretationSchema = z.object({
- disposition: z.literal('unrecognized'),
- source_profile: z.null(),
- source_profile_version: z.null(),
- summary: z.string(),
- reason_code: z.literal('unrecognized_source'),
-})
-
-export const RepositorySourceInterpretationSchema = z.union([
- ExactRepositorySourceInterpretationSchema,
- InvalidRepositorySourceInterpretationSchema,
- UnrecognizedRepositorySourceInterpretationSchema,
-])
-
-export const RepositorySourceInspectionSchema = 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().regex(/^[0-9a-f]{40}$/i),
- interpretation: RepositorySourceInterpretationSchema,
- profile: FlueSourceProfileSchema.nullable(),
- review_fingerprint: z.string().regex(/^sha256:[0-9a-f]{64}$/),
- candidate_roots: z.array(RepositoryCandidateRootSchema).max(20).default([]),
- candidate_roots_truncated: z.boolean(),
- })
- .superRefine((review, context) => {
- const exact = review.interpretation.disposition === 'exact'
- if (exact !== (review.profile !== null)) {
- context.addIssue({
- code: 'custom',
- path: ['profile'],
- message: exact
- ? 'an exact source interpretation requires its profile projection'
- : 'a non-exact source interpretation cannot include a deployable profile',
- })
- }
- })
-
-export const ImportAgentResponseSchema = z.object({
- agent: AgentSchema,
- source: DeploymentSourceSchema,
- deployment: AgentDeploymentSchema,
-})
-
+// ── Durable Agent Sessions credentials ─────────────────────────────────────
+// Only the Credentials page still reads these (via the edge's /v3 proxy to
+// sessions-api); it is removed in a later change.
// 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({
@@ -938,470 +426,7 @@ export const CredentialListSchema = z.object({
next_cursor: z.string().nullish(),
})
-// ── Model access (work 011: bring-your-own Codex subscription) ──────────────
-// An organization-owned connection to a Codex subscription. The provider token
-// is write-only and never appears on this object; the API returns only
-// normalized metadata. At most one Codex connection per organization is
-// enforced server-side (unique (organization_id, provider)).
-export const ModelAccessConnectionSchema = z.object({
- id: z.string(),
- organization_id: z.string(),
- connected_by_user_id: z.string(),
- provider: z.enum(['anthropic', 'openai', 'openrouter', 'openai_compatible']),
- kind: z.enum([
- 'claude_subscription',
- 'codex_subscription',
- 'openrouter_api_key',
- 'openai_compatible_api',
- ]),
- label: z.string(),
- base_url: z.string().url().nullish(),
- external_account_hint: z.string().nullish(),
- status: z.enum([
- 'connecting',
- 'connected',
- 'reauth_required',
- 'provider_limited',
- 'plan_ineligible',
- 'revoked',
- 'unavailable',
- ]),
- // Provider-reported entitlement/model snapshot, when a sanctioned capability
- // surface exists. Opaque to the dashboard; display hints only, never authz.
- entitlement_snapshot: z.unknown().nullish(),
- checked_at: z.string().nullish(),
- created_at: z.string().nullish(),
- updated_at: z.string().nullish(),
-})
-export const ModelAccessConnectionListSchema = z.object({
- data: z.array(ModelAccessConnectionSchema),
-})
-
-// Connect: starts the personal Codex subscription OAuth flow. Returns a pending
-// intent the dashboard redirects to, with the authorize_url. `label` is a
-// display override and defaults server-side.
-export const ModelAccessConnectRequestSchema = z.discriminatedUnion(
- 'provider',
- [
- z.object({ provider: z.literal('openai'), label: z.string().optional() }),
- z.object({
- provider: z.literal('anthropic'),
- token: z.string(),
- label: z.string().optional(),
- }),
- ],
-)
-export const ModelAccessConnectResponseSchema = z.union([
- ModelAccessConnectionSchema,
- z.object({
- connection: ModelAccessConnectionSchema,
- status: z.literal('pending'),
- authorize_url: z.string(),
- expires_at: z.string(),
- }),
-])
-
-// A project-environment enablement of the single org connection for a provider.
-// One binding per (project, environment, provider). Created disabled by default.
-export const ModelAccessBindingSchema = z.object({
- organization_id: z.string(),
- project_id: z.string(),
- environment: z.enum(['development', 'production']),
- provider: z.enum(['anthropic', 'openai']),
- connection_id: z.string(),
- enabled: z.boolean(),
- enabled_by_user_id: z.string().nullish(),
- created_at: z.string().nullish(),
- updated_at: z.string().nullish(),
-})
-export const ModelAccessBindingListSchema = z.object({
- data: z.array(ModelAccessBindingSchema),
-})
-export const ModelAccessBindingPutRequestSchema = z.object({
- enabled: z.boolean(),
-})
-
-// Typed error for model-access failures (resolution + dispatch).
-export const ModelAccessErrorSchema = z.object({
- error: z.object({
- code: z.enum([
- 'model_access_unavailable',
- 'plan_ineligible',
- 'provider_not_connected',
- 'model_not_in_subscription',
- 'reauth_required',
- 'provider_allowance_exhausted',
- 'subscription_unavailable',
- ]),
- message: z.string(),
- // Present when both the subscription and Managed reasons must be shown.
- subscription_reason: z.string().nullish(),
- managed_reason: z.string().nullish(),
- }),
-})
-
-// The immutable record of how one provider call was routed and billed.
-export const EffectiveModelRouteSchema = z.object({
- requested: z.object({ provider: z.string(), model: z.string() }).nullable(),
- effective: z.object({ provider: z.string(), model: z.string() }),
- runtime: z.enum(['claude', 'codex', 'opencode']),
- access: z.object({
- type: z.enum(['managed', 'external_subscription', 'external_api_key']),
- connection_id: z.string().nullish(),
- connection_kind: z
- .enum([
- 'claude_subscription',
- 'codex_subscription',
- 'openrouter_api_key',
- 'openai_compatible_api',
- ])
- .nullish(),
- }),
- fallback: z
- .object({
- from: z.literal('external_subscription'),
- reason: z.enum([
- 'provider_not_connected',
- 'model_not_in_subscription',
- 'reauth_required',
- 'provider_allowance_exhausted',
- 'subscription_unavailable',
- ]),
- })
- .nullish(),
- open_computer_model_charge_usd: z.number(),
-})
-
-// Slack connection (sessions-api `serializeSlackApp`) — an agent's BYO Slack app.
-// Never carries secrets (bot token / signing secret stay in the secret backend).
-// `handle` is the agent's name; slack_app_id/team_id/account_login fill in once
-// connected. status: pending | active | revoked | error.
-export const SlackConnectionSchema = z.object({
- id: z.string(),
- agent_id: z.string(),
- handle: z.string().nullish(),
- slack_app_id: z.string().nullable().optional(),
- team_id: z.string().nullable().optional(),
- account_login: z.string().nullable().optional(),
- open_url: z.string().nullable().optional(),
- status: z.string(),
- bot_token_verified: z.boolean().optional(),
- signing_verified: z.boolean().optional(),
- created_at: z.string().nullish(),
- updated_at: z.string().nullish(),
-})
-// START intent: the generated manifest (an object to copy), the Slack apps URL,
-// and the ordered human steps the wizard renders.
-export const SlackManifestResponseSchema = z.object({
- manifest: record,
- create_url: z.string(),
- steps: z.array(z.string()),
- status: z.string(),
-})
-
-export const ManagedSlackConnectionSchema = z.object({
- mode: z.literal('managed'),
- status: z.enum(['active', 'disconnected', 'error', 'revoked']),
- workspace: z.object({ id: z.string(), name: z.string().nullish() }).nullish(),
- app: z.object({ id: z.string(), handle: z.string().nullish() }).nullish(),
- open_url: z.string().nullish(),
- connected_at: z.string().nullish(),
- error_code: z.string().nullish(),
-})
-
-export const ManagedSlackWorkspaceConnectionSchema =
- ManagedSlackConnectionSchema.extend({
- agent: z.object({ id: z.string(), name: z.string() }),
- })
-
-export const ManagedSlackWorkspaceConnectionListSchema = z.object({
- data: z.array(ManagedSlackWorkspaceConnectionSchema),
-})
-
-// A race-safe authorize is idempotent: if the connection became active after
-// the dashboard status read, the API returns that active connection instead of
-// minting another OAuth intent.
-export const ManagedSlackAuthorizeResponseSchema = z.union([
- z.object({
- mode: z.literal('managed'),
- status: z.literal('pending'),
- authorize_url: z.string(),
- expires_at: z.string(),
- }),
- ManagedSlackConnectionSchema.refine((value) => value.status === 'active'),
-])
-
-export const ManagedSlackDisconnectResponseSchema = z.object({
- ok: z.literal(true),
- status: z.literal('disconnected'),
-})
-
-// The pinned effective agent tuple (design 009 §3.5) the session ran with. `runtime`
-// is what distinguishes flue from the brain-box runtimes (claude/codex/pi) in read views.
-export const AgentSnapshotSchema = z.object({
- runtime: z.string().nullish(),
- model: z.string().nullish(),
- prompt_hash: z.string().nullish(),
- revision: z.union([z.string(), z.number()]).nullish(),
- agent_revision_number: z.number().nullish(),
- digest: z.string().nullish(),
- skill_bundle_digest: z.string().nullish(),
-})
-
-const UsageAttributionSchema = z.enum(['exact', 'best_effort'])
-const ReportedTurnUsageSchema = z.object({
- reported: z.literal(true),
- complete: z.literal(false).optional(),
- input_tokens: z.number().int().nonnegative(),
- output_tokens: z.number().int().nonnegative(),
- cache_creation_input_tokens: z.number().int().nonnegative(),
- cache_read_input_tokens: z.number().int().nonnegative(),
- tokens: z.number().int().nonnegative(),
- total_cost_usd: z.number().nonnegative().optional(),
- attribution: UsageAttributionSchema.optional(),
-})
-const UnreportedTurnUsageSchema = z.object({
- reported: z.literal(false),
- attribution: UsageAttributionSchema.optional(),
-})
-const HistoricalEmptyUsageSchema = z.object({}).strict()
-export const TurnUsageSchema = z.union([
- ReportedTurnUsageSchema,
- UnreportedTurnUsageSchema,
- HistoricalEmptyUsageSchema,
-])
-export const SessionUsageSchema = z.union([
- z.object({
- active_seconds: z.number().int().nonnegative(),
- reported_turns: z.number().int().nonnegative(),
- unreported_turns: z.number().int().nonnegative(),
- complete: z.boolean(),
- input_tokens: z.number().int().nonnegative().optional(),
- output_tokens: z.number().int().nonnegative().optional(),
- cache_creation_input_tokens: z.number().int().nonnegative().optional(),
- cache_read_input_tokens: z.number().int().nonnegative().optional(),
- tokens: z.number().int().nonnegative().optional(),
- total_cost_usd: z.number().nonnegative().optional(),
- attribution: UsageAttributionSchema.optional(),
- }),
- HistoricalEmptyUsageSchema,
-])
-
-export const SessionSchema = z.object({
- id: z.string(),
- status: z.string(),
- agent_id: z.string().nullable().optional(),
- agent_snapshot: AgentSnapshotSchema.nullish(),
- credential_id: z.string().nullable().optional(),
- head: z.coerce.number().optional(), // current event seq; API returns it as a string ("0")
- last_turn: record.nullish(),
- usage: SessionUsageSchema.nullish(),
- limits: record.nullish(),
- metadata: record.nullish(),
- // The OC sandboxes this session runs on (agent-sandbox-ownership Phase 1).
- sandboxes: z
- .object({
- brain: z.string().nullish(),
- hands: z.string().nullish(),
- })
- .nullish(),
- created_at: z.string(),
-})
-export const SessionListSchema = z.object({
- data: z.array(SessionSchema),
- next_cursor: z.string().nullish(),
-})
-
-export const SessionSourceSchema = z.object({
- name: z.string(),
- status: z.enum([
- 'pending',
- 'materializing',
- 'resolved',
- 'failed',
- 'unavailable',
- 'auth_required',
- ]),
- path: z.string(),
- sha: z.string(),
- resolved_sha: z.string().optional(),
- repo_id: z.string().optional(),
- full_name: z.string().optional(),
- requested_ref: z.string().optional(),
- error_code: z.string().optional(),
- error_message: z.string().optional(),
- retryable: z.boolean().optional(),
-})
-export const SessionSourceListSchema = z.array(SessionSourceSchema)
-
-export const ActorSchema = z.object({
- id: z.string().optional(),
- display: z.string().optional(),
- type: z.string().optional(),
-})
-
-export const SessionEventSchema = z.object({
- id: z.string(),
- seq: z.number(),
- session: z.string().optional(), // owning session id (present on SSE frames)
- type: z.string(),
- level: z.string(),
- actor: ActorSchema.optional(),
- body: z.unknown().optional(),
- // Set together when the body spilled to blob storage (body > 32KB): the inline
- // `body` is absent/partial, `content_ref` points at the blob, `body_bytes` is the size.
- content_ref: z.string().nullish(),
- body_truncated: z.boolean().nullish(),
- // PostgreSQL bigint values are serialized as strings by the sessions API.
- // Coerce here so spilled event bodies remain visible in the live timeline.
- body_bytes: z.coerce.number().nullish(),
- refs: record.nullish(),
- source: z.string().optional(),
- turn_id: z.string().nullable().optional(),
- ts: z.string().optional(),
- created_at: z.string().optional(),
-})
-export const SessionEventListSchema = z.object({
- data: z.array(SessionEventSchema),
- next_cursor: z.string().nullish(),
-})
-
-export const TurnSchema = z.object({
- id: z.string(),
- state: z.string(),
- yield_reason: z.string().nullable().optional(),
- attempt: z.number().optional(),
- started_at: z.string().nullable().optional(),
- completed_at: z.string().nullable().optional(),
- active_seconds: z.number().nullish(),
- result_event_id: z.string().nullish(),
- usage: TurnUsageSchema.nullish(),
- error: z.unknown().nullish(), // server serializes the error as an opaque object, not a string
-})
-export const SessionTurnListSchema = z.object({
- data: z.array(TurnSchema),
- next_cursor: z.string().nullish(),
-})
-// GET /v3/sessions/:id/result → the latest turn + its result event (if any).
-export const SessionResultSchema = z.object({
- last_turn: TurnSchema.nullable(),
- result: SessionEventSchema.nullable(),
-})
-
-export const AgentHookSchema = z.object({
- id: z.string(),
- agent_id: z.string(),
- name: z.string(),
- status: z.enum(['active', 'expired', 'revoked']),
- secret_last4: z.string(),
- revoked_reason: z.enum(['manual', 'secret_exposure']).nullable(),
- expires_at: z.string().nullable(),
- created_at: z.string(),
-})
-export const AgentHookListSchema = z.object({
- data: z.array(AgentHookSchema),
- next_cursor: z.string().nullable(),
-})
-export const AgentHookCreateSchema = z.object({
- hook: AgentHookSchema,
- hook_url: z.string(),
-})
-
-export const AgentSecurityNotificationSchema = z.object({
- id: z.string(),
- agentId: z.string(),
- hookId: z.string(),
- kind: z.literal('secret_exposure'),
- occurredAt: z.string(),
- acknowledgedAt: z.string().nullable(),
- acknowledgedBy: z.string().nullable(),
-})
-export const AgentSecurityNotificationListSchema = z.object({
- data: z.array(AgentSecurityNotificationSchema),
- next_cursor: z.string().nullable(),
-})
-
-export const DestinationSchema = z.object({
- id: z.string(),
- url: z.string(),
- level: z.string().optional(),
- types: z.array(z.string()).nullish(),
- include_raw: z.boolean().optional(),
- enabled: z.boolean(),
- has_secret: z.boolean().optional(),
- created_after_seq: z.number().nullable().optional(),
- created_at: z.string(),
- updated_at: z.string().optional(),
-})
-
-export const DeliverySchema = z.object({
- id: z.string(),
- destination: z.string().optional(), // the API field is `destination`, not `destination_id`
- event_id: z.string().optional(),
- event_seq: z.number().optional(),
- status: z.string(),
- attempts: z.number().optional(),
- last_attempt_at: z.string().nullable().optional(),
- response_code: z.number().nullable().optional(),
- error: z.string().nullable().optional(),
- created_at: z.string(),
-})
-
-export type Agent = z.infer<typeof AgentSchema>
-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 DeploymentSource = z.infer<typeof DeploymentSourceSchema>
-export type DeployApp = z.infer<typeof DeployAppSchema>
-export type RepositoryAccessPolicy = z.infer<
- typeof RepositoryAccessPolicySchema
->
-export type RepositoryAccessRepository = z.infer<
- typeof RepositoryAccessRepositorySchema
->
-export type RepositoryAccess = z.infer<typeof RepositoryAccessSchema>
-export type RepositorySourceInspection = z.infer<
- typeof RepositorySourceInspectionSchema
->
export type Credential = z.infer<typeof CredentialSchema>
-export type ModelAccessConnection = z.infer<typeof ModelAccessConnectionSchema>
-export type ModelAccessBinding = z.infer<typeof ModelAccessBindingSchema>
-export type ModelAccessConnectResponse = z.infer<
- typeof ModelAccessConnectResponseSchema
->
-export type EffectiveModelRoute = z.infer<typeof EffectiveModelRouteSchema>
-export type SlackConnection = z.infer<typeof SlackConnectionSchema>
-export type SlackManifestResponse = z.infer<typeof SlackManifestResponseSchema>
-export type ManagedSlackAuthorizeResponse = z.infer<
- typeof ManagedSlackAuthorizeResponseSchema
->
-export type ManagedSlackConnection = z.infer<
- typeof ManagedSlackConnectionSchema
->
-export type ManagedSlackWorkspaceConnection = z.infer<
- typeof ManagedSlackWorkspaceConnectionSchema
->
-export type ManagedSlackDisconnectResponse = z.infer<
- typeof ManagedSlackDisconnectResponseSchema
->
-export type Session = z.infer<typeof SessionSchema>
-export type SessionSource = z.infer<typeof SessionSourceSchema>
-export type AgentSnapshot = z.infer<typeof AgentSnapshotSchema>
-export type SessionEvent = z.infer<typeof SessionEventSchema>
-export type Turn = z.infer<typeof TurnSchema>
-export type SessionResult = z.infer<typeof SessionResultSchema>
-export type TurnUsage = z.infer<typeof TurnUsageSchema>
-export type SessionUsage = z.infer<typeof SessionUsageSchema>
-export type AgentHook = z.infer<typeof AgentHookSchema>
-export type AgentHookCreate = z.infer<typeof AgentHookCreateSchema>
-export type AgentSecurityNotification = z.infer<
- typeof AgentSecurityNotificationSchema
->
-export type Destination = z.infer<typeof DestinationSchema>
-export type Delivery = z.infer<typeof DeliverySchema>
export type OrgInfo = z.infer<typeof OrgInfoSchema>
export type MeResponse = z.infer<typeof MeResponseSchema>
diff --git a/web/src/api/slack-schemas.test.ts b/web/src/api/slack-schemas.test.ts
deleted file mode 100644
index b9cc8ea7..00000000
--- a/web/src/api/slack-schemas.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { authorizeManagedSlack } from './client'
-import {
- ManagedSlackAuthorizeResponseSchema,
- ManagedSlackConnectionSchema,
- ManagedSlackWorkspaceConnectionListSchema,
-} from './schemas'
-
-afterEach(() => {
- vi.unstubAllGlobals()
-})
-
-describe('managed Slack response schemas', () => {
- it('accepts the browser-safe active connection', () => {
- const result = ManagedSlackConnectionSchema.parse({
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:00:00Z',
- })
-
- expect(result.status).toBe('active')
- expect(JSON.stringify(result)).not.toContain('xoxb-')
- })
-
- it('accepts owner-scoped workspace claims without credentials', () => {
- const result = ManagedSlackWorkspaceConnectionListSchema.parse({
- data: [
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:00:00Z',
- agent: { id: 'agt_1', name: 'Support triage' },
- },
- ],
- })
-
- expect(result.data[0]?.agent.name).toBe('Support triage')
- expect(JSON.stringify(result)).not.toContain('xoxb-')
- })
-
- it('accepts only the fixed managed OAuth start shape', () => {
- expect(
- ManagedSlackAuthorizeResponseSchema.parse({
- mode: 'managed',
- status: 'pending',
- authorize_url: 'https://slack.com/oauth/v2/authorize?state=opaque',
- expires_at: '2026-07-16T18:10:00Z',
- }),
- ).toMatchObject({ mode: 'managed', status: 'pending' })
-
- expect(() =>
- ManagedSlackAuthorizeResponseSchema.parse({
- mode: 'byo',
- status: 'active',
- authorize_url: 'https://example.test',
- expires_at: '2026-07-16T18:10:00Z',
- }),
- ).toThrow()
- })
-
- it('sends the exact deployment as structured OAuth return context', async () => {
- let captured: RequestInit | undefined
- vi.stubGlobal(
- 'fetch',
- vi.fn((_input: string | URL | Request, init?: RequestInit) => {
- captured = init
- return Promise.resolve(
- Response.json({
- mode: 'managed',
- status: 'pending',
- authorize_url: 'https://slack.com/oauth/v2/authorize?state=opaque',
- expires_at: '2026-07-16T18:10:00Z',
- }),
- )
- }),
- )
-
- await authorizeManagedSlack('agt_example', 'dep_first')
-
- expect(captured?.method).toBe('POST')
- expect(captured?.body).toEqual(expect.any(String))
- expect(JSON.parse(captured?.body as string)).toEqual({
- return_deployment_id: 'dep_first',
- })
- })
-
- it('accepts an idempotent active response from authorize', () => {
- expect(
- ManagedSlackAuthorizeResponseSchema.parse({
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:10:00Z',
- }),
- ).toMatchObject({ mode: 'managed', status: 'active' })
- })
-})
diff --git a/web/src/components/agent-deploy-source.test.tsx b/web/src/components/agent-deploy-source.test.tsx
deleted file mode 100644
index b0d84285..00000000
--- a/web/src/components/agent-deploy-source.test.tsx
+++ /dev/null
@@ -1,121 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import type { DeploymentSource } from '@/api/schemas'
-import {
- AgentDeploySource,
- DeploymentSourceSummary,
-} from '@/components/agent-deploy-source'
-
-const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const source: DeploymentSource = {
- agent_id: agentId,
- repo_id: 'repo_aaaaaaaaaaaaaaaaaaaaaaaa',
- path: '',
- production_ref: 'main',
- status: 'active',
- latest_seen_sha: 'a'.repeat(40),
- active_deployed_sha: 'a'.repeat(40),
- full_name: 'diggerhq/oc-flue-starter',
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- review_fingerprint: `sha256:${'b'.repeat(64)}`,
-}
-
-function renderPinnedSource(nextSource: DeploymentSource = source) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(['agent-deploy-source', agentId], nextSource)
- queryClient.setQueryData(['deploy-app'], {
- installed: true,
- install_url: null,
- configure_url: 'https://github.com/settings/installations/123',
- account: 'diggerhq',
- repository_selection: 'selected',
- repositories: [],
- })
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <AgentDeploySource agentId={agentId} profilePinned />
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-function renderSourceSummary(nextSource: DeploymentSource | null) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(['agent-deploy-source', agentId], nextSource)
- queryClient.setQueryData(['deploy-app'], {
- installed: true,
- install_url: null,
- configure_url: 'https://github.com/settings/installations/123',
- account: 'diggerhq',
- repository_selection: 'selected',
- repositories: [],
- })
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <DeploymentSourceSummary agentId={agentId} onOpenSettings={() => {}} />
- </QueryClientProvider>,
- )
-}
-
-describe('profile-pinned repository management', () => {
- it('shows the reviewed source and safe management actions without an editable picker', () => {
- const html = renderPinnedSource()
-
- expect(html).toContain('Repository</h2>')
- expect(html).toContain('diggerhq/oc-flue-starter')
- expect(html).toContain('Production branch')
- expect(html).toContain('Repository root')
- expect(html).toContain('Configure GitHub')
- expect(html).toContain('Unlink repository')
- expect(html).toContain(
- 'It does not delete this agent, its active revision, or its sessions.',
- )
- expect(html).not.toContain('<input')
- expect(html).not.toContain('Select a repo')
- })
-
- it('keeps the restore-or-unlink recovery when the pinned profile changes', () => {
- const html = renderPinnedSource({
- ...source,
- status: 'source_profile_changed',
- latest_seen_sha: 'c'.repeat(40),
- })
-
- expect(html).toContain(
- 'This repository no longer matches the agent type it was imported as',
- )
- expect(html).toContain('View source changes')
- expect(html).toContain('Unlink source')
- expect(html).not.toContain('Configure GitHub')
- })
-})
-
-describe('deployment source summary', () => {
- it('shows the connected source without duplicating the editor', () => {
- const html = renderSourceSummary(source)
-
- expect(html).toContain('GitHub</h2>')
- expect(html).toContain('diggerhq/oc-flue-starter')
- expect(html).toContain('main')
- expect(html).toContain('Manage GitHub')
- expect(html).not.toContain('Select a repo')
- })
-
- it('distinguishes an installed GitHub app from an agent source', () => {
- const html = renderSourceSummary(null)
-
- expect(html).toContain('GitHub app connected')
- expect(html).toContain('diggerhq · No source repository')
- expect(html).toContain('Manage GitHub')
- })
-})
diff --git a/web/src/components/agent-deploy-source.tsx b/web/src/components/agent-deploy-source.tsx
deleted file mode 100644
index cf16ffea..00000000
--- a/web/src/components/agent-deploy-source.tsx
+++ /dev/null
@@ -1,587 +0,0 @@
-import { useEffect, useRef, useState } from 'react'
-import {
- useMutation,
- useQuery,
- useQueryClient,
- type QueryClient,
-} from '@tanstack/react-query'
-import { useNavigate } from 'react-router-dom'
-import { Unplug, ExternalLink, RotateCw } from 'lucide-react'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import {
- ApiError,
- getDeployApp,
- getDeploymentSource,
- linkDeploymentSource,
- unlinkDeploymentSource,
-} from '@/api/client'
-import type { DeploymentSource } from '@/api/schemas'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
-import { Input, Select } from '@/components/form'
-import { GithubMark } from '@/components/github-mark'
-import { SourceProfileChangedRecovery } from '@/components/source-profile-changed-recovery'
-import type { RepositorySeed } from '@/lib/repository-onboarding'
-
-function repositoryStatus(source: DeploymentSource): string {
- switch (source.status) {
- case 'active':
- return `Pushes to ${source.production_ref} create deployments automatically.`
- case 'auth_required':
- return 'Reconnect GitHub to resume automatic deployments.'
- case 'repo_not_selected':
- return 'Grant this repository to the GitHub App to resume deployments.'
- case 'app_suspended':
- return 'The GitHub App installation is suspended.'
- case 'path_missing':
- return 'The configured root directory is missing.'
- case 'ref_missing':
- return 'The configured production branch is missing.'
- default:
- return 'This repository connection needs attention.'
- }
-}
-
-/**
- * A reviewed repository import is profile-pinned. It can be inspected,
- * authorized, or unlinked here, but never switched in place through the
- * legacy free-form picker because a new source must pass repository review.
- */
-export function PinnedRepositorySource({
- source,
- configureUrl,
- installUrl,
- pending,
- onUnlink,
-}: {
- source: DeploymentSource
- configureUrl?: string | null
- installUrl?: string | null
- pending: boolean
- onUnlink: () => void
-}) {
- const [confirming, setConfirming] = useState(false)
- const githubUrl = configureUrl ?? installUrl
- const githubLabel = configureUrl ? 'Configure GitHub' : 'Reconnect GitHub'
-
- return (
- <>
- <Panel id="repository-source" className="overflow-hidden">
- <PanelHeader>
- <div className="min-w-0">
- <PanelTitle>Repository</PanelTitle>
- <PanelDescription className="mt-1 text-xs">
- {repositoryStatus(source)}
- </PanelDescription>
- </div>
- <GithubMark className="text-muted-foreground size-4 shrink-0" />
- </PanelHeader>
- <PanelContent className="space-y-4">
- <dl className="space-y-3 text-xs">
- <div className="space-y-1">
- <dt className="text-muted-foreground">Repository</dt>
- <dd className="font-mono text-sm break-all">
- {source.full_name ?? source.repo_id}
- </dd>
- </div>
- <div className="grid grid-cols-2 gap-3">
- <div className="min-w-0 space-y-1">
- <dt className="text-muted-foreground">Production branch</dt>
- <dd className="truncate font-mono">{source.production_ref}</dd>
- </div>
- <div className="min-w-0 space-y-1">
- <dt className="text-muted-foreground">Root directory</dt>
- <dd className="truncate font-mono">
- {source.path || 'Repository root'}
- </dd>
- </div>
- </div>
- </dl>
-
- <div className="flex flex-wrap gap-2">
- {githubUrl ? (
- <Button size="sm" variant="outline" asChild>
- <a href={githubUrl} target="_blank" rel="noreferrer">
- {githubLabel}
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- ) : null}
- <Button
- size="sm"
- variant="destructive"
- disabled={pending}
- onClick={() => setConfirming(true)}
- >
- <Unplug className="size-4" />
- Unlink repository
- </Button>
- </div>
- <p className="text-muted-foreground text-xs leading-relaxed">
- Unlinking stops deploy-on-push. It does not delete this agent, its
- active revision, or its sessions.
- </p>
- </PanelContent>
- </Panel>
- <ConfirmDialog
- open={confirming}
- onOpenChange={setConfirming}
- title="Unlink this repository?"
- description={`Push-to-deploy from ${source.full_name ?? 'this repository'} will stop. The existing agent, active revision, and sessions will remain available. You can then import this repository into another agent.`}
- confirmLabel="Unlink repository"
- destructive
- pending={pending}
- onConfirm={onUnlink}
- />
- </>
- )
-}
-
-// A connect / redeploy kicks off a GitHub deploy that runs ASYNC — the new revision (prompt +
-// skills) isn't live until it activates. Poll the source until the deploy lands
-// (active_deployed_sha caught up to latest_seen_sha), keeping the card in step, then refresh the
-// dependent views so the Overview + Skills update without a manual page reload. Bounded (~60s).
-async function pollDeployUntilActive(
- agentId: string,
- queryClient: QueryClient,
-) {
- for (let i = 0; i < 24; i++) {
- await new Promise((r) => setTimeout(r, 2500))
- try {
- const src = (await getDeploymentSource(agentId)).source
- queryClient.setQueryData(['agent-deploy-source', agentId], src)
- if (
- src?.active_deployed_sha &&
- src.active_deployed_sha === src.latest_seen_sha
- ) {
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- void queryClient.invalidateQueries({
- queryKey: ['agent-skills', agentId],
- })
- void queryClient.invalidateQueries({
- queryKey: ['agent-revisions', agentId],
- })
- return
- }
- } catch {
- return
- }
- }
-}
-
-/**
- * Source settings — minimal. Connect a GitHub repo as the agent's source:
- * not installed → a single Connect (install) button; installed → an editable repo / directory /
- * branch picker (pre-filled when already linked) + a quiet Disconnect + an "Add more repos" link.
- * Pushes to the branch create new revisions; re-applying the picker (Update) pulls HEAD into one.
- * No card title, no nested borders — just the lightweight controls that matter.
- */
-export function AgentDeploySource({
- agentId,
- profilePinned = false,
-}: {
- agentId: string
- /** Reviewed imports can be managed or unlinked, but not switched in place. */
- profilePinned?: boolean
-}) {
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const [repo, setRepo] = useState('')
- const [path, setPath] = useState('')
- const [branch, setBranch] = useState('main')
- // "You just connected" is a transient onboarding moment — only true when the App flips to
- // installed *within this session* (i.e. the user returned from the install tab). NOT set on a
- // fresh load of an already-installed agent, and cleared on Disconnect — so the "pick a repo"
- // nudge never lingers on unlinked/inline-only agents or reappears after an explicit disconnect.
- const [justConnected, setJustConnected] = useState(false)
- const [unlinkedImport, setUnlinkedImport] = useState<RepositorySeed | null>(
- null,
- )
-
- const { data: app, isLoading: appLoading } = useQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- // The App is installed in another tab; refetch whenever the user returns so the
- // card flips to the repo picker immediately (staleTime would otherwise hide it).
- refetchOnWindowFocus: 'always',
- })
- const {
- data: source,
- isLoading: srcLoading,
- isError: srcError,
- refetch: refetchSource,
- } = useQuery({
- queryKey: ['agent-deploy-source', agentId],
- queryFn: async () => {
- try {
- return (await getDeploymentSource(agentId)).source
- } catch (e) {
- if (e instanceof ApiError && e.status === 404) return null // not linked
- throw e // a real failure (500/auth/proxy) must not masquerade as "not connected"
- }
- },
- refetchOnWindowFocus: 'always',
- })
-
- // Detect the false→true install transition: latch "just connected" only if we saw the
- // not-installed state earlier this session (so a fresh load of an already-installed agent
- // doesn't look like a transition).
- const seenNotInstalled = useRef(false)
- useEffect(() => {
- if (!app) return
- if (!app.installed) seenNotInstalled.current = true
- else if (seenNotInstalled.current) setJustConnected(true)
- }, [app])
-
- // Pre-fill the picker from the current link once, so "connected" is an editable picker.
- const hydratedRef = useRef(false)
- useEffect(() => {
- if (source && !profilePinned && !hydratedRef.current) {
- hydratedRef.current = true
- setRepo(source.full_name ?? '')
- setPath(source.path ?? '')
- setBranch(source.production_ref || 'main')
- }
- }, [profilePinned, source])
-
- const invalidate = () => {
- void queryClient.invalidateQueries({
- queryKey: ['agent-deploy-source', agentId],
- })
- void queryClient.invalidateQueries({
- queryKey: ['agent-revisions', agentId],
- })
- void queryClient.invalidateQueries({ queryKey: ['agent-skills', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- }
-
- const link = useMutation({
- mutationFn: () =>
- linkDeploymentSource(agentId, {
- repo,
- path: path.trim(),
- production_ref: branch.trim() || 'main',
- }),
- onSuccess: (r) => {
- invalidate()
- if (r.deploy_error) {
- notifyError(
- `Connected, but the first revision couldn't be created (${r.deploy_error.message}).`,
- new Error(r.deploy_error.type),
- )
- } else {
- notifySuccess(
- source
- ? 'Redeploying — pulling the latest commit into a new revision.'
- : 'Connected — creating the first revision.',
- )
- // The GitHub deploy runs async — refresh the prompt + skills once it activates.
- void pollDeployUntilActive(agentId, queryClient)
- }
- },
- onError: (e) => notifyError("Couldn't connect the repo.", e),
- })
- const unlink = useMutation({
- mutationFn: (options?: { prepareReimport?: boolean }) => {
- void options
- return unlinkDeploymentSource(agentId)
- },
- onSuccess: (_result, options) => {
- if (options?.prepareReimport && source) {
- setUnlinkedImport({
- repo: source.repo_id,
- path: source.path,
- productionRef: source.production_ref,
- })
- }
- invalidate()
- hydratedRef.current = false
- setJustConnected(false) // an explicit disconnect is not an onboarding moment
- setRepo('')
- setPath('')
- setBranch('main')
- notifySuccess('Repository unlinked. Existing revisions are unchanged.')
- },
- onError: (e) => notifyError("Couldn't unlink the repository.", e),
- })
-
- const pickRepo = (fullName: string) => {
- setRepo(fullName)
- const r = app?.repositories.find((x) => x.full_name === fullName)
- if (r?.default_branch) setBranch(r.default_branch)
- }
-
- // Repo options — include the linked repo even if it's not in the installable list.
- const repoOptions = (app?.repositories ?? []).map((r) => ({
- value: r.full_name,
- label: r.full_name,
- }))
- if (
- source?.full_name &&
- !repoOptions.some((o) => o.value === source.full_name)
- ) {
- repoOptions.unshift({ value: source.full_name, label: source.full_name })
- }
-
- if (profilePinned && !unlinkedImport && !srcLoading && !srcError && !source) {
- return null
- }
-
- if (
- profilePinned &&
- !unlinkedImport &&
- !srcLoading &&
- !srcError &&
- source &&
- source.status !== 'source_profile_changed'
- ) {
- return (
- <PinnedRepositorySource
- source={source}
- configureUrl={app?.configure_url}
- installUrl={app?.install_url}
- pending={unlink.isPending}
- onUnlink={() => unlink.mutate({ prepareReimport: true })}
- />
- )
- }
-
- return (
- <Panel className="overflow-hidden">
- <PanelContent className="space-y-3">
- {unlinkedImport ? (
- <div className="space-y-3">
- <p className="text-sm font-medium">Repository unlinked</p>
- <p className="text-muted-foreground text-xs">
- Push-to-deploy stopped. The existing agent, active revision, and
- sessions are unchanged.
- </p>
- <Button
- size="sm"
- onClick={() =>
- void navigate('/agents/new', {
- state: { repositoryImport: unlinkedImport },
- })
- }
- >
- Import repository as new agent
- </Button>
- </div>
- ) : srcLoading || (!profilePinned && appLoading) ? (
- <p className="text-muted-foreground text-xs">Loading…</p>
- ) : srcError ? (
- <div className="space-y-2">
- <p className="text-xs text-red-600 dark:text-red-500">
- Couldn’t load the repo connection.
- </p>
- <Button
- size="sm"
- variant="outline"
- onClick={() => void refetchSource()}
- >
- Retry
- </Button>
- </div>
- ) : source?.status === 'source_profile_changed' ? (
- <SourceProfileChangedRecovery
- source={source}
- pending={unlink.isPending}
- onUnlink={() => unlink.mutate({ prepareReimport: true })}
- />
- ) : !app?.installed ? (
- <div className="space-y-3">
- <Button
- size="sm"
- variant="outline"
- disabled={!app?.install_url}
- asChild
- >
- <a
- href={app?.install_url ?? '#'}
- target="_blank"
- rel="noreferrer"
- >
- <GithubMark className="size-4" />
- Connect repository
- </a>
- </Button>
- <p className="text-muted-foreground text-xs">
- Or use the CLI: <code className="font-mono">oc agent deploy</code>
- </p>
- </div>
- ) : (
- <div className="space-y-3">
- {justConnected && !source ? (
- <p className="text-xs">
- <span className="font-medium text-green-600 dark:text-green-500">
- GitHub connected.
- </span>{' '}
- <span className="text-muted-foreground">
- Last step — pick a repo to deploy from.
- </span>
- </p>
- ) : null}
- <Select
- value={repo}
- onValueChange={pickRepo}
- placeholder={
- repoOptions.length ? 'Select a repo' : 'No repos available'
- }
- disabled={repoOptions.length === 0}
- options={repoOptions}
- />
- <div className="flex gap-2">
- <Input
- value={path}
- onChange={(e) => setPath(e.target.value)}
- placeholder="directory"
- />
- <Input
- value={branch}
- onChange={(e) => setBranch(e.target.value)}
- placeholder="main"
- className="max-w-28"
- />
- </div>
- <div className="flex items-center gap-2">
- {source ? (
- <Button
- size="sm"
- variant="outline"
- title="Redeploy — pull the latest commit into a new revision"
- disabled={link.isPending || !repo}
- onClick={() => link.mutate()}
- >
- <RotateCw
- className={`size-4 ${link.isPending ? 'animate-spin' : ''}`}
- />
- </Button>
- ) : (
- <Button
- size="sm"
- variant="outline"
- disabled={link.isPending || !repo}
- onClick={() => link.mutate()}
- >
- {link.isPending ? 'Deploying…' : 'Deploy'}
- </Button>
- )}
- {source ? (
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground"
- disabled={unlink.isPending}
- onClick={() => unlink.mutate({ prepareReimport: false })}
- >
- <Unplug className="size-4" />
- Disconnect
- </Button>
- ) : null}
- </div>
- {app.configure_url ? (
- <a
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs"
- href={app.configure_url}
- target="_blank"
- rel="noreferrer"
- >
- <ExternalLink className="size-3" />
- Add more repos
- </a>
- ) : null}
- <p className="text-muted-foreground text-xs">
- Or use the CLI: <code className="font-mono">oc agent deploy</code>
- </p>
- </div>
- )}
- </PanelContent>
- </Panel>
- )
-}
-
-export function DeploymentSourceSummary({
- agentId,
- onOpenSettings,
-}: {
- agentId: string
- onOpenSettings: () => void
-}) {
- const appQuery = useQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- })
- const sourceQuery = useQuery({
- queryKey: ['agent-deploy-source', agentId],
- queryFn: async () => {
- try {
- return (await getDeploymentSource(agentId)).source
- } catch (error) {
- if (error instanceof ApiError && error.status === 404) return null
- throw error
- }
- },
- })
- const source = sourceQuery.data
- const loading = appQuery.isLoading || sourceQuery.isLoading
- const unavailable = appQuery.isError || sourceQuery.isError
-
- let title = 'Not connected'
- let detail = 'Connect the GitHub app to deploy this agent from a repository.'
- if (source) {
- title = source.full_name || 'Repository connected'
- detail = [source.path || null, source.production_ref]
- .filter(Boolean)
- .join(' · ')
- } else if (appQuery.data?.installed) {
- title = 'GitHub app connected'
- detail = appQuery.data.account
- ? `${appQuery.data.account} · No source repository`
- : 'No source repository'
- }
-
- return (
- <Panel>
- <PanelHeader className="border-b-0 pb-2">
- <PanelTitle className="flex items-center gap-2">
- <GithubMark className="size-4" /> GitHub
- </PanelTitle>
- </PanelHeader>
- <PanelContent className="pt-1">
- {loading ? (
- <Skeleton className="h-10 w-full" />
- ) : unavailable ? (
- <p className="text-muted-foreground text-sm">
- GitHub status is unavailable.
- </p>
- ) : (
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">{title}</p>
- <p className="text-muted-foreground mt-0.5 truncate text-xs">
- {detail}
- </p>
- </div>
- )}
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground mt-2 -ml-3"
- onClick={onOpenSettings}
- >
- {source || appQuery.data?.installed
- ? 'Manage GitHub'
- : 'Connect GitHub'}
- </Button>
- </PanelContent>
- </Panel>
- )
-}
diff --git a/web/src/components/agent-deployments.tsx b/web/src/components/agent-deployments.tsx
deleted file mode 100644
index 09a622df..00000000
--- a/web/src/components/agent-deployments.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-import { useInfiniteQuery } from '@tanstack/react-query'
-import { Link } from 'react-router-dom'
-import { GitBranch, History } from 'lucide-react'
-import { getAgentDeployments, type AgentDeployment } from '@/api/client'
-import { EmptyState } from '@/components/empty-state'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelFooter,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { ResourceTable, type Column } from '@/components/resource-table'
-import { StatusBadge } from '@/components/status-badge'
-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
-import { Button } from '@/components/ui/button'
-
-function titleCase(value: string): string {
- const words = value.replace(/_/g, ' ')
- return words.charAt(0).toUpperCase() + words.slice(1)
-}
-
-function deploymentResult(deployment: AgentDeployment): string {
- if (deployment.error?.class) return titleCase(deployment.error.class)
- if (deployment.revision?.number != null) {
- return `Revision #${deployment.revision.number}${deployment.active ? ' · Active' : ''}`
- }
- if (deployment.state === 'skipped') return 'No change'
- if (deployment.result) return titleCase(deployment.result)
- return titleCase(deployment.phase)
-}
-
-function DeploymentSource({ deployment }: { deployment: AgentDeployment }) {
- const relation = deployment.source_relation
- const repo = relation?.repo?.full_name
- const ref = relation?.ref ?? relation?.production_ref ?? deployment.ref
- const sha = relation?.sha ?? deployment.sha
-
- if (!repo && !ref && !sha) {
- return (
- <span className="text-muted-foreground text-xs capitalize">
- {deployment.input_type}
- </span>
- )
- }
-
- return (
- <span className="block min-w-0">
- <span className="text-foreground flex items-center gap-1 text-xs">
- <GitBranch className="size-3 shrink-0" aria-hidden />
- <span className="max-w-52 truncate" title={repo ?? undefined}>
- {repo ?? 'Repository'}
- </span>
- </span>
- <span className="text-muted-foreground mt-0.5 block font-mono text-xs">
- {[ref, sha?.slice(0, 7)].filter(Boolean).join(' · ')}
- </span>
- </span>
- )
-}
-
-export function AgentDeployments({ agentId }: { agentId: string }) {
- const deploymentsQuery = useInfiniteQuery({
- queryKey: ['agent-deployments', agentId],
- initialPageParam: null as string | null,
- queryFn: ({ pageParam }) =>
- getAgentDeployments(agentId, {
- before: pageParam ?? undefined,
- limit: 25,
- }),
- getNextPageParam: (lastPage) => lastPage.next_cursor,
- refetchInterval: (query) =>
- query.state.data?.pages.some((page) =>
- page.data.some((deployment) => !deployment.terminal),
- )
- ? 2500
- : false,
- })
-
- const deployments = Array.from(
- new Map(
- (deploymentsQuery.data?.pages.flatMap((page) => page.data) ?? []).map(
- (deployment) => [deployment.id, deployment],
- ),
- ).values(),
- )
-
- const columns: Column<AgentDeployment>[] = [
- {
- key: 'deployment',
- header: 'Deployment',
- cell: (deployment) => (
- <Link
- to={`/agents/${agentId}/deployments/${deployment.id}`}
- className="text-foreground font-mono text-xs underline-offset-4 hover:underline"
- >
- {deployment.id}
- </Link>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (deployment) => <StatusBadge status={deployment.state} />,
- },
- {
- key: 'source',
- header: 'Source',
- cell: (deployment) => <DeploymentSource deployment={deployment} />,
- },
- {
- key: 'result',
- header: 'Result',
- cell: (deployment) => (
- <span
- className="text-muted-foreground block max-w-48 truncate text-xs"
- title={deploymentResult(deployment)}
- >
- {deploymentResult(deployment)}
- </span>
- ),
- },
- {
- key: 'created',
- header: 'Created',
- align: 'right',
- cell: (deployment) => (
- <time
- dateTime={deployment.created_at}
- className="text-muted-foreground font-mono text-xs whitespace-nowrap"
- >
- {new Date(deployment.created_at).toLocaleString()}
- </time>
- ),
- },
- ]
-
- const initialError = deploymentsQuery.isError && deployments.length === 0
-
- return (
- <Panel className="overflow-hidden">
- <PanelHeader>
- <div>
- <PanelTitle>Deployments</PanelTitle>
- <PanelDescription className="mt-1">
- Each build attempt keeps its source, outcome, and persisted log.
- </PanelDescription>
- </div>
- </PanelHeader>
-
- {initialError ? (
- <PanelContent>
- <Alert variant="destructive">
- <AlertTitle>Deployment history could not be loaded</AlertTitle>
- <AlertDescription>
- Retry this read. Existing deployments and logs are unchanged.
- </AlertDescription>
- <div className="mt-2">
- <Button
- size="sm"
- variant="outline"
- onClick={() => void deploymentsQuery.refetch()}
- >
- Retry history
- </Button>
- </div>
- </Alert>
- </PanelContent>
- ) : (
- <ResourceTable
- columns={columns}
- rows={deployments}
- rowKey={(deployment) => deployment.id}
- loading={deploymentsQuery.isLoading}
- empty={
- <EmptyState
- icon={History}
- title="No deployments yet"
- description="Repository imports and deploys will appear here with their build logs."
- />
- }
- />
- )}
-
- {!initialError &&
- (deploymentsQuery.hasNextPage || deploymentsQuery.error) ? (
- <PanelFooter className="justify-between">
- <span className="text-muted-foreground text-xs">
- {deploymentsQuery.error
- ? 'History could not be refreshed.'
- : 'Newest deployments first.'}
- </span>
- {deploymentsQuery.hasNextPage ? (
- <Button
- size="sm"
- variant="outline"
- disabled={deploymentsQuery.isFetchingNextPage}
- onClick={() => void deploymentsQuery.fetchNextPage()}
- >
- {deploymentsQuery.isFetchingNextPage
- ? 'Loading…'
- : 'Load older deployments'}
- </Button>
- ) : deploymentsQuery.error ? (
- <Button
- size="sm"
- variant="outline"
- onClick={() => void deploymentsQuery.refetch()}
- >
- Retry history
- </Button>
- ) : null}
- </PanelFooter>
- ) : null}
- </Panel>
- )
-}
diff --git a/web/src/components/agent-hooks-panel.tsx b/web/src/components/agent-hooks-panel.tsx
deleted file mode 100644
index 769c5a99..00000000
--- a/web/src/components/agent-hooks-panel.tsx
+++ /dev/null
@@ -1,292 +0,0 @@
-import { useState } from 'react'
-import {
- useInfiniteQuery,
- useMutation,
- useQueryClient,
-} from '@tanstack/react-query'
-import { KeyRound, Plus, Trash2 } from 'lucide-react'
-import {
- createAgentHook,
- getAgentHooks,
- revokeAgentHook,
- type AgentHook,
- type AgentHookCreate,
-} from '@/api/client'
-import { notifyError } from '@/lib/errors'
-import {
- Panel,
- PanelContent,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { Field, Input } from '@/components/form'
-import { CopyRow } from '@/components/copy-row'
-import { StatusBadge } from '@/components/status-badge'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { ApiHint } from '@/components/api-hint'
-
-function revokedReason(reason: AgentHook['revoked_reason']): string | null {
- if (reason === 'secret_exposure') return 'Secret exposure detected'
- if (reason === 'manual') return 'Revoked manually'
- return null
-}
-
-function expiryLabel(value: string | null): string {
- return value ? `Expires ${new Date(value).toLocaleString()}` : 'No expiry'
-}
-
-export function AgentHooksPanel({ agentId }: { agentId: string }) {
- const queryClient = useQueryClient()
- const [creating, setCreating] = useState(false)
- const [createPending, setCreatePending] = useState(false)
- const [name, setName] = useState('')
- const [expiresAt, setExpiresAt] = useState('')
- const [created, setCreated] = useState<AgentHookCreate | null>(null)
- const [revoke, setRevoke] = useState<AgentHook | null>(null)
- const query = useInfiniteQuery({
- queryKey: ['agent-hooks', agentId],
- queryFn: ({ pageParam }) => getAgentHooks(agentId, pageParam),
- initialPageParam: undefined as string | undefined,
- getNextPageParam: (page) => page.next_cursor ?? undefined,
- })
- const hooks = query.data?.pages.flatMap((page) => page.data) ?? []
-
- const invalidate = () =>
- queryClient.invalidateQueries({ queryKey: ['agent-hooks', agentId] })
- const submitCreate = async () => {
- setCreatePending(true)
- try {
- const result = await createAgentHook(agentId, {
- name: name.trim(),
- ...(expiresAt ? { expires_at: new Date(expiresAt).toISOString() } : {}),
- })
- // The complete Hook URL stays only in this component until dismissed.
- setCreated(result)
- setCreating(false)
- setName('')
- setExpiresAt('')
- void invalidate()
- } catch (error) {
- notifyError("Couldn't create the Hook URL.", error)
- } finally {
- setCreatePending(false)
- }
- }
- const revokeMutation = useMutation({
- mutationFn: (hook: AgentHook) => revokeAgentHook(agentId, hook.id),
- onSuccess: () => {
- setRevoke(null)
- void invalidate()
- },
- onError: (error) => notifyError("Couldn't revoke the Hook URL.", error),
- })
-
- return (
- <Panel id="hooks" tabIndex={-1} className="scroll-mt-36 outline-none">
- <PanelHeader>
- <div>
- <PanelTitle>Hook URLs</PanelTitle>
- <p className="text-muted-foreground mt-1 text-xs">
- One named, revocable URL per external sender.
- </p>
- </div>
- <ApiHint
- method="POST"
- path={`/v3/agents/${agentId}/hooks`}
- sdk="oc.agents.hooks.create(id, …)"
- docs="https://docs.opencomputer.dev/agent-sessions/hooks"
- />
- </PanelHeader>
-
- {created ? (
- <PanelContent className="border-b">
- <div className="border-status-warning/40 bg-status-warning-bg rounded-md border p-3">
- <p className="text-foreground text-sm font-medium">
- Copy {created.hook.name}&apos;s complete URL now
- </p>
- <p className="text-muted-foreground mt-1 text-xs">
- It cannot be retrieved after you close this notice.
- </p>
- <CopyRow
- value={created.hook_url}
- maskable
- className="bg-background mt-3"
- />
- <Button
- type="button"
- size="sm"
- variant="ghost"
- className="mt-2"
- onClick={() => setCreated(null)}
- >
- I&apos;ve copied it
- </Button>
- </div>
- </PanelContent>
- ) : null}
-
- {creating ? (
- <PanelContent className="border-b">
- <form
- className="space-y-3"
- onSubmit={(event) => {
- event.preventDefault()
- if (name.trim()) void submitCreate()
- }}
- >
- <Field label="Name" htmlFor="hook-name">
- <Input
- id="hook-name"
- value={name}
- onChange={(event) => setName(event.target.value)}
- placeholder="grafana-prod"
- pattern="[a-z0-9][a-z0-9-]{0,63}"
- required
- />
- </Field>
- <Field
- label="Expires"
- htmlFor="hook-expiry"
- description="Optional. Leave empty for no expiry."
- >
- <Input
- id="hook-expiry"
- type="datetime-local"
- value={expiresAt}
- onChange={(event) => setExpiresAt(event.target.value)}
- />
- </Field>
- <div className="flex justify-end gap-2">
- <Button
- type="button"
- size="sm"
- variant="ghost"
- disabled={createPending}
- onClick={() => setCreating(false)}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- size="sm"
- disabled={!name.trim() || createPending}
- >
- {createPending ? 'Creating…' : 'Create Hook URL'}
- </Button>
- </div>
- </form>
- </PanelContent>
- ) : null}
-
- <div className="divide-y">
- {query.isLoading ? (
- <p className="text-muted-foreground px-5 py-4 text-xs">Loading…</p>
- ) : query.isError ? (
- <div className="px-5 py-5 text-center">
- <p className="text-sm font-medium">Hook URLs unavailable</p>
- <p className="text-muted-foreground mt-1 text-xs">
- Could not load this agent&apos;s Hooks.
- </p>
- <Button
- type="button"
- size="sm"
- variant="outline"
- className="mt-3"
- onClick={() => void query.refetch()}
- >
- Try again
- </Button>
- </div>
- ) : hooks.length === 0 ? (
- <div className="px-5 py-5 text-center">
- <KeyRound className="text-muted-foreground mx-auto size-5" />
- <p className="mt-2 text-sm font-medium">No Hook URLs</p>
- <p className="text-muted-foreground mt-1 text-xs">
- Create one when an external system needs to start this agent.
- </p>
- </div>
- ) : (
- hooks.map((hook) => {
- const reason = revokedReason(hook.revoked_reason)
- return (
- <div key={hook.id} className="px-5 py-3">
- <div className="flex items-start justify-between gap-3">
- <div className="min-w-0">
- <div className="flex flex-wrap items-center gap-2">
- <span className="text-sm font-medium">{hook.name}</span>
- <StatusBadge status={hook.status} />
- </div>
- <p className="text-muted-foreground mt-1 font-mono text-[11px]">
- {hook.id} · ends in {hook.secret_last4}
- </p>
- <p className="text-muted-foreground mt-1 text-xs">
- Created {new Date(hook.created_at).toLocaleString()} ·{' '}
- {expiryLabel(hook.expires_at)}
- </p>
- {reason ? (
- <p className="text-status-error mt-0.5 text-xs">
- {reason}
- </p>
- ) : null}
- </div>
- {hook.status !== 'revoked' ? (
- <Button
- type="button"
- size="icon-xs"
- variant="ghost"
- aria-label={`Revoke ${hook.name}`}
- onClick={() => setRevoke(hook)}
- >
- <Trash2 className="size-3.5" />
- </Button>
- ) : null}
- </div>
- </div>
- )
- })
- )}
- </div>
-
- <div className="flex items-center justify-between border-t px-5 py-3">
- {query.hasNextPage ? (
- <Button
- type="button"
- size="sm"
- variant="ghost"
- disabled={query.isFetchingNextPage}
- onClick={() => void query.fetchNextPage()}
- >
- {query.isFetchingNextPage ? 'Loading…' : 'Load older'}
- </Button>
- ) : (
- <span />
- )}
- <Button
- type="button"
- size="sm"
- variant="outline"
- disabled={creating || !!created}
- onClick={() => setCreating(true)}
- >
- <Plus className="size-3.5" /> New Hook URL
- </Button>
- </div>
-
- <ConfirmDialog
- open={!!revoke}
- onOpenChange={(open) => {
- if (!open) setRevoke(null)
- }}
- title={`Revoke ${revoke?.name ?? 'this Hook'}?`}
- description="The sender will immediately lose access. This cannot be undone. Create a replacement before revoking if the integration must stay live."
- confirmLabel="Revoke Hook"
- destructive
- pending={revokeMutation.isPending}
- onConfirm={() => {
- if (revoke) revokeMutation.mutate(revoke)
- }}
- />
- </Panel>
- )
-}
diff --git a/web/src/components/agent-invocation-panels.test.tsx b/web/src/components/agent-invocation-panels.test.tsx
deleted file mode 100644
index b3f00159..00000000
--- a/web/src/components/agent-invocation-panels.test.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import { AgentHooksPanel } from './agent-hooks-panel'
-
-const agentId = 'agt_0123456789abcdef01234567'
-
-function renderPanels() {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(['agent-hooks', agentId], {
- pages: [
- {
- data: [
- {
- id: 'hk_0123456789abcdef01234567',
- agent_id: agentId,
- name: 'grafana-prod',
- status: 'revoked',
- secret_last4: 'xYz0',
- revoked_reason: 'secret_exposure',
- expires_at: null,
- created_at: '2026-07-22T00:00:00.000Z',
- },
- ],
- next_cursor: null,
- },
- ],
- pageParams: [undefined],
- })
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <AgentHooksPanel agentId={agentId} />
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-describe('Agent Hook settings', () => {
- it('renders Hook audit metadata without recovering its secret', () => {
- const markup = renderPanels()
-
- expect(markup).toContain('grafana-prod')
- expect(markup).toContain('Secret exposure detected')
- expect(markup).toContain('ends in xYz0')
- expect(markup).not.toContain('/hooks/secret')
- })
-})
diff --git a/web/src/components/agent-revisions.tsx b/web/src/components/agent-revisions.tsx
deleted file mode 100644
index 6e83dcb0..00000000
--- a/web/src/components/agent-revisions.tsx
+++ /dev/null
@@ -1,180 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { History, RotateCcw, ArrowUp, GitBranch } from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import {
- getAgentRevisions,
- getAgentDeploys,
- activateRevision,
- type AgentRevision,
-} from '@/api/client'
-import { Panel, PanelHeader, PanelTitle } from '@/components/panel'
-import { ResourceTable, type Column } from '@/components/resource-table'
-import { StatusBadge } from '@/components/status-badge'
-import { Button } from '@/components/ui/button'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { EmptyState } from '@/components/empty-state'
-
-// Short, legible digest (e.g. "sha256:a14f940d82") for the table.
-const shortDigest = (d: string) => d.slice(0, 19)
-const sourceVia = (s?: Record<string, unknown> | null) =>
- (s && typeof s.via === 'string' && s.via) || 'api'
-
-/**
- * Agent Revisions panel (design 009 §13): the deploy history of an agent's behavior,
- * the active production pointer made visible, one-click rollback (activate an earlier
- * revision), and a compact deploy timeline (provenance + state).
- */
-export function AgentRevisions({ agentId }: { agentId: string }) {
- const queryClient = useQueryClient()
- const [pending, setPending] = useState<AgentRevision | null>(null)
-
- const { data: revisions = [], isLoading } = useQuery({
- queryKey: ['agent-revisions', agentId],
- queryFn: () => getAgentRevisions(agentId),
- })
- const { data: deploys = [] } = useQuery({
- queryKey: ['agent-deploys', agentId],
- queryFn: () => getAgentDeploys(agentId),
- })
- // A revision's provenance lives on the deploy that CREATED it (one revision, many
- // deploys — source is a deploy field). Fold source.via into the revisions table so
- // we don't need a second, near-duplicate table.
- const createdVia = new Map<string, string>()
- for (const d of deploys) {
- if (d.revision_id && d.result === 'created')
- createdVia.set(d.revision_id, sourceVia(d.source))
- }
-
- const activateMutation = useMutation({
- mutationFn: (rev: AgentRevision) => activateRevision(agentId, rev.number),
- onSuccess: () => {
- void queryClient.invalidateQueries({
- queryKey: ['agent-revisions', agentId],
- })
- void queryClient.invalidateQueries({
- queryKey: ['agent-deploys', agentId],
- })
- // prompt/model are sourced from the active revision → refresh the agent too.
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- setPending(null)
- },
- onError: (e) => {
- notifyError("Couldn't activate that revision.", e)
- setPending(null)
- },
- })
-
- const revisionColumns: Column<AgentRevision>[] = [
- {
- key: 'number',
- header: 'Revision',
- cell: (r) => (
- <span className="text-foreground font-mono text-[13px]">
- #{r.number}
- </span>
- ),
- },
- {
- key: 'source',
- header: 'Source',
- cell: (r) =>
- r.sha ? (
- <span className="text-muted-foreground inline-flex items-center gap-1 font-mono text-xs">
- <GitBranch className="size-3 shrink-0" />
- {r.ref ? `${r.ref} · ` : ''}
- {r.sha.slice(0, 7)}
- </span>
- ) : (
- <span className="text-muted-foreground text-xs capitalize">
- {createdVia.get(r.id) ?? 'dashboard'}
- </span>
- ),
- },
- {
- key: 'digest',
- header: 'Digest',
- cell: (r) => (
- <span className="text-muted-foreground font-mono text-xs">
- {shortDigest(r.digest)}
- </span>
- ),
- },
- {
- key: 'created',
- header: 'Created',
- cell: (r) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(r.created_at).toLocaleString()}
- </span>
- ),
- },
- {
- key: 'action',
- header: '',
- align: 'right',
- cell: (r) => {
- if (r.active) return <StatusBadge status="active" />
- // Activating an older revision is a rollback; a newer one is a promote. Show just the
- // icon (it repeats down the column); the label slides in on hover so it stays legible.
- const isRollback = !!revisions[0] && r.number < revisions[0].number
- const Icon = isRollback ? RotateCcw : ArrowUp
- const label = isRollback ? 'Roll back' : 'Activate'
- return (
- <Button
- variant="ghost"
- size="xs"
- aria-label={label}
- title={label}
- className="group text-muted-foreground hover:text-foreground gap-0"
- disabled={activateMutation.isPending}
- onClick={() => setPending(r)}
- >
- <Icon className="size-3.5 shrink-0" />
- {/* Reserve the label's width always so the reveal-on-hover doesn't reflow the column. */}
- <span className="ml-1.5 inline-block w-[4.25rem] text-left opacity-0 transition-opacity duration-150 ease-out group-hover:opacity-100 motion-reduce:transition-none">
- {label}
- </span>
- </Button>
- )
- },
- },
- ]
-
- return (
- <Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Revisions</PanelTitle>
- <span className="text-muted-foreground text-xs">
- Each deploy is an immutable revision. Rolling back re-points the
- active one.
- </span>
- </PanelHeader>
-
- <ResourceTable
- columns={revisionColumns}
- rows={revisions}
- rowKey={(r) => r.id}
- loading={isLoading}
- empty={
- <EmptyState
- icon={History}
- title="No revisions yet"
- description="Editing the prompt or model, or deploying an agent directory, creates a revision."
- />
- }
- />
-
- <ConfirmDialog
- open={pending !== null}
- onOpenChange={(open) => !open && setPending(null)}
- title={`Activate revision #${pending?.number ?? ''}?`}
- description="New sessions will use this revision. In-flight sessions keep the revision they started with."
- confirmLabel="Activate"
- pending={activateMutation.isPending}
- onConfirm={() => pending && activateMutation.mutate(pending)}
- />
- </Panel>
- )
-}
diff --git a/web/src/components/agent-schedules.tsx b/web/src/components/agent-schedules.tsx
deleted file mode 100644
index 3c85303c..00000000
--- a/web/src/components/agent-schedules.tsx
+++ /dev/null
@@ -1,480 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link } from 'react-router-dom'
-import {
- AlertTriangle,
- CalendarClock,
- CheckCircle2,
- ChevronDown,
- ChevronRight,
- GitBranch,
- Pause,
- Pencil,
- Play,
- PlayCircle,
- Plus,
- Trash2,
-} from 'lucide-react'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import {
- ApiError,
- createSchedule,
- deleteSchedule,
- fireSchedule,
- getDeploymentSource,
- getScheduleRuns,
- getSchedules,
- updateSchedule,
- type Schedule,
- type ScheduleOverlap,
- type ScheduleRun,
-} from '@/api/client'
-import { Panel, PanelContent } from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { Field, Input, Select, Textarea } from '@/components/form'
-
-// ── helpers ────────────────────────────────────────────────────────────────────
-
-// Relative time ("in 3h" / "5m ago") — schedules are minute-resolution, so no dependency needed.
-function rel(iso: string | null): string {
- if (!iso) return '—'
- const delta = new Date(iso).getTime() - Date.now()
- const m = Math.max(1, Math.round(Math.abs(delta) / 60000))
- const unit = m < 60 ? `${m}m` : m < 1440 ? `${Math.round(m / 60)}h` : `${Math.round(m / 1440)}d`
- return delta >= 0 ? `in ${unit}` : `${unit} ago`
-}
-// Next-fire label: a due/overdue slot sits briefly in the past (until the tick catches up, < ~60s) —
-// read that as "due now", never "1m ago".
-function nextFireLabel(iso: string): string {
- return new Date(iso).getTime() <= Date.now() ? 'due now' : rel(iso)
-}
-
-// A friendly gloss for the common crons; unknown expressions just show the raw fields.
-const CRON_HINTS: Record<string, string> = {
- '0 9 * * 1-5': 'weekdays at 09:00',
- '0 9 * * *': 'every day at 09:00',
- '0 * * * *': 'every hour',
- '*/15 * * * *': 'every 15 minutes',
- '*/30 * * * *': 'every 30 minutes',
- '0 0 * * 0': 'Sundays at midnight',
- '0 0 1 * *': 'first of the month',
- '0 0 * * *': 'every day at midnight',
-}
-const CRON_PRESETS: { label: string; cron: string }[] = [
- { label: 'Weekdays 9am', cron: '0 9 * * 1-5' },
- { label: 'Daily 9am', cron: '0 9 * * *' },
- { label: 'Hourly', cron: '0 * * * *' },
- { label: 'Every 15m', cron: '*/15 * * * *' },
-]
-
-const prettyTz = (z: string) => z.replace(/_/g, ' ')
-// UTC-only in the UI for now (shown as a fixed label, no picker). A schedule pointed at another zone
-// via the API/CLI still renders correctly — the server's validateTz accepts any IANA zone.
-function tzDisplay(tz: string | null): string {
- return !tz || tz === 'UTC' ? 'UTC' : prettyTz(tz)
-}
-
-function StateBadge({ s }: { s: Schedule }) {
- const cls =
- s.state === 'active'
- ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400'
- : s.state === 'auto_paused'
- ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400'
- : 'bg-muted text-muted-foreground'
- return <span className={`rounded px-1.5 py-0.5 text-[10px] font-medium ${cls}`}>{s.state.replace('_', ' ')}</span>
-}
-
-// A run's outcome in plain language. "enacted" → a session was started (linked); "failed" → it
-// didn't start (with the error); "skipped" → the previous run was still going.
-function RunStatus({ run }: { run: ScheduleRun }) {
- if (run.outcome === 'enacted') {
- const inner = (
- <>
- <CheckCircle2 className="size-3.5 shrink-0 text-green-600 dark:text-green-500" />
- Session started
- </>
- )
- return run.session_id ? (
- <Link to={`/sessions/${run.session_id}`} className="text-foreground inline-flex items-center gap-1 hover:underline">
- {inner}
- </Link>
- ) : (
- <span className="inline-flex items-center gap-1">{inner}</span>
- )
- }
- if (run.outcome === 'skipped') {
- return <span className="text-muted-foreground">Skipped — previous run still running</span>
- }
- return (
- <span className="inline-flex min-w-0 items-center gap-1 text-red-600 dark:text-red-500" title={run.error ?? undefined}>
- <AlertTriangle className="size-3.5 shrink-0" />
- <span className="truncate">Didn’t start{run.error ? ` — ${run.error}` : ''}</span>
- </span>
- )
-}
-
-// Recent runs for a schedule — lazily fetched when a row is expanded.
-function ScheduleRuns({ agentId, scheduleId }: { agentId: string; scheduleId: string }) {
- const { data: runs, isLoading } = useQuery({
- queryKey: ['schedule-runs', agentId, scheduleId],
- queryFn: () => getScheduleRuns(agentId, scheduleId, 5),
- refetchInterval: 15_000, // schedules fire in the background — keep the runs list live while open
- })
- if (isLoading) return <p className="text-muted-foreground px-3 py-2 text-xs">Loading runs…</p>
- if (!runs || runs.length === 0) return <p className="text-muted-foreground px-3 py-2 text-xs">No runs yet.</p>
- return (
- <ul className="divide-border/60 divide-y text-xs">
- {runs.map((r) => (
- <li key={r.id} className="flex items-center gap-2 px-3 py-1.5">
- <div className="min-w-0 flex-1">
- <RunStatus run={r} />
- </div>
- <span className="text-muted-foreground shrink-0">{rel(r.fired_at)}</span>
- </li>
- ))}
- </ul>
- )
-}
-
-type FormState = { id?: string; name: string; cron: string; input: string; overlap: ScheduleOverlap }
-
-// ── the tab ─────────────────────────────────────────────────────────────────────
-
-export function AgentSchedulesTab({ agentId }: { agentId: string }) {
- const queryClient = useQueryClient()
- const [form, setForm] = useState<FormState | null>(null)
- const [expanded, setExpanded] = useState<string | null>(null)
- const [pendingDelete, setPendingDelete] = useState<Schedule | null>(null)
-
- const { data: repoManaged } = useQuery({
- queryKey: ['agent-deploy-source', agentId],
- queryFn: async () => {
- try {
- return (await getDeploymentSource(agentId)).source
- } catch (e) {
- if (e instanceof ApiError && e.status === 404) return null
- throw e
- }
- },
- select: (src) => !!src,
- })
-
- const {
- data: schedules,
- isLoading,
- isError,
- refetch,
- } = useQuery({
- queryKey: ['agent-schedules', agentId],
- queryFn: () => getSchedules(agentId),
- refetchInterval: 20_000, // schedules fire in the background — reflect next-fire / last-ran live
- })
-
- const invalidate = () => void queryClient.invalidateQueries({ queryKey: ['agent-schedules', agentId] })
-
- const openCreate = () => setForm({ name: '', cron: '0 9 * * 1-5', input: '', overlap: 'skip' })
- const openEdit = (s: Schedule) =>
- setForm({ id: s.id, name: s.name, cron: s.cron, input: s.input, overlap: s.overlap })
-
- const save = useMutation({
- mutationFn: () => {
- const f = form!
- const common = { cron: f.cron.trim(), input: f.input.trim(), overlap: f.overlap }
- // Create is UTC-only (tz: null). Edit omits tz entirely so it never clobbers a zone set via the API/CLI.
- return f.id
- ? updateSchedule(agentId, f.id, common)
- : createSchedule(agentId, { name: f.name.trim(), tz: null, ...common })
- },
- onSuccess: () => {
- const editing = !!form?.id
- invalidate()
- setForm(null)
- notifySuccess(editing ? 'Schedule updated.' : 'Schedule created.')
- },
- onError: (e) => notifyError("Couldn't save the schedule.", e),
- })
-
- const toggle = useMutation({
- mutationFn: (s: Schedule) => updateSchedule(agentId, s.id, { paused: s.state === 'active' }),
- onSuccess: () => invalidate(),
- onError: (e) => notifyError("Couldn't update the schedule.", e),
- })
- const fire = useMutation({
- mutationFn: (s: Schedule) => fireSchedule(agentId, s.id),
- onSuccess: (run, s) => {
- void queryClient.invalidateQueries({ queryKey: ['schedule-runs', agentId, s.id] })
- invalidate()
- if (run.outcome === 'enacted' && run.session_id) notifySuccess(`Fired — session ${run.session_id}`)
- else notifyError(`Fire ${run.outcome}`, new Error(run.error ?? run.outcome))
- },
- onError: (e) => notifyError("Couldn't fire the schedule.", e),
- })
- const remove = useMutation({
- mutationFn: (s: Schedule) => deleteSchedule(agentId, s.id),
- onSuccess: () => {
- invalidate()
- setPendingDelete(null)
- notifySuccess('Schedule deleted.')
- },
- onError: (e) => notifyError("Couldn't delete the schedule.", e),
- })
-
- const f = form
- const canSave = f && (f.id || f.name.trim()) && f.cron.trim() && f.input.trim()
- const cronGloss = f ? CRON_HINTS[f.cron.trim()] : undefined
-
- return (
- <div className="max-w-3xl space-y-5">
- <div className="flex items-start justify-between gap-4">
- <div>
- <h2 className="text-base font-medium">Schedules</h2>
- <p className="text-muted-foreground mt-0.5 text-sm">
- Run this agent on a cron — each firing starts a new session with a fixed message.
- </p>
- </div>
- {!repoManaged && !form ? (
- <Button size="sm" onClick={openCreate}>
- <Plus className="size-4" />
- New schedule
- </Button>
- ) : null}
- </div>
-
- {repoManaged ? (
- <div className="border-border bg-panel-2 flex items-start gap-2 rounded-md border px-3 py-2.5 text-xs">
- <GitBranch className="text-muted-foreground mt-0.5 size-3.5 shrink-0" />
- <p className="text-muted-foreground">
- Managed from the connected repo — edit the <span className="font-mono">[[schedules]]</span> table in{' '}
- <span className="font-mono">agent.toml</span> and push. You can still pause, resume, and test-fire here.
- </p>
- </div>
- ) : null}
-
- {/* Create / edit form */}
- {form ? (
- <Panel>
- <PanelContent className="space-y-4">
- <Field label="Name" htmlFor="sch-name">
- <Input
- id="sch-name"
- value={form.name}
- onChange={(e) => setForm({ ...form, name: e.target.value })}
- placeholder="morning-docs-sweep"
- disabled={!!form.id}
- />
- {form.id ? <p className="text-muted-foreground mt-1 text-xs">Name can’t be changed after creation.</p> : null}
- </Field>
-
- <Field label="Schedule" htmlFor="sch-cron">
- <div className="flex items-center gap-2">
- <Input
- id="sch-cron"
- value={form.cron}
- onChange={(e) => setForm({ ...form, cron: e.target.value })}
- placeholder="0 9 * * 1-5"
- className="font-mono"
- />
- <span
- className="border-border text-muted-foreground shrink-0 rounded-md border px-2.5 py-1 text-sm"
- title="Schedules run in UTC"
- >
- UTC
- </span>
- </div>
- <div className="mt-2 flex flex-wrap items-center gap-1.5">
- {CRON_PRESETS.map((p) => (
- <button
- key={p.cron}
- type="button"
- onClick={() => setForm({ ...form, cron: p.cron })}
- className={
- 'rounded-full border px-2 py-0.5 text-xs transition-colors ' +
- (form.cron.trim() === p.cron
- ? 'border-foreground text-foreground'
- : 'border-border text-muted-foreground hover:text-foreground')
- }
- >
- {p.label}
- </button>
- ))}
- <span className="text-muted-foreground ml-auto text-xs">
- {cronGloss ? cronGloss : '5-field cron'}
- </span>
- </div>
- </Field>
-
- <Field label="Message" htmlFor="sch-input">
- <Textarea
- id="sch-input"
- value={form.input}
- onChange={(e) => setForm({ ...form, input: e.target.value })}
- placeholder="Reconcile docs/ against changes since the last run; open a draft PR if anything drifted."
- className="min-h-32"
- />
- <p className="text-muted-foreground mt-1 text-xs">
- Sent as the first message on every run. Write it as a complete instruction — no human is in the loop to
- clarify.
- </p>
- </Field>
-
- <Field label="If the previous run is still going" htmlFor="sch-overlap">
- <Select
- id="sch-overlap"
- value={form.overlap}
- onValueChange={(v) => setForm({ ...form, overlap: v as ScheduleOverlap })}
- className="max-w-xs"
- options={[
- { value: 'skip', label: 'Skip this firing (default)' },
- { value: 'allow', label: 'Run them concurrently' },
- ]}
- />
- </Field>
-
- <div className="flex items-center gap-2">
- <Button size="sm" variant="outline" disabled={save.isPending || !canSave} onClick={() => save.mutate()}>
- {save.isPending ? 'Saving…' : form.id ? 'Save changes' : 'Create schedule'}
- </Button>
- <Button size="sm" variant="ghost" onClick={() => setForm(null)}>
- Cancel
- </Button>
- </div>
- </PanelContent>
- </Panel>
- ) : null}
-
- {/* List */}
- {isLoading ? (
- <p className="text-muted-foreground text-sm">Loading…</p>
- ) : isError ? (
- <div className="space-y-2">
- <p className="text-sm text-red-600 dark:text-red-500">Couldn’t load schedules.</p>
- <Button size="sm" variant="outline" onClick={() => void refetch()}>
- Retry
- </Button>
- </div>
- ) : schedules && schedules.length > 0 ? (
- <ul className="space-y-3">
- {schedules.map((s) => {
- const gloss = CRON_HINTS[s.cron]
- const open = expanded === s.id
- return (
- <li key={s.id}>
- <Panel>
- <PanelContent className="space-y-2.5">
- <div className="flex items-center gap-2">
- <span className="truncate font-medium">{s.name}</span>
- <StateBadge s={s} />
- <div className="ml-auto flex items-center gap-0.5">
- <Button
- size="sm"
- variant="ghost"
- title={s.state === 'active' ? 'Pause' : 'Resume'}
- disabled={toggle.isPending}
- onClick={() => toggle.mutate(s)}
- >
- {s.state === 'active' ? <Pause className="size-4" /> : <PlayCircle className="size-4" />}
- </Button>
- <Button
- size="sm"
- variant="ghost"
- title="Test-fire now"
- disabled={fire.isPending}
- onClick={() => fire.mutate(s)}
- >
- <Play className="size-4" />
- </Button>
- {!repoManaged ? (
- <>
- <Button size="sm" variant="ghost" title="Edit" onClick={() => openEdit(s)}>
- <Pencil className="size-4" />
- </Button>
- <Button
- size="sm"
- variant="ghost"
- className="text-muted-foreground hover:text-red-600"
- title="Delete"
- onClick={() => setPendingDelete(s)}
- >
- <Trash2 className="size-4" />
- </Button>
- </>
- ) : null}
- </div>
- </div>
-
- <div className="text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-xs">
- <code className="text-foreground font-mono">{s.cron}</code>
- {gloss ? <span>{gloss}</span> : null}
- <span className="text-border">·</span>
- <span>{tzDisplay(s.tz)}</span>
- <span className="text-border">·</span>
- <span className="inline-flex items-center gap-1">
- <CalendarClock className="size-3" />
- next {s.state === 'active' ? nextFireLabel(s.next_fire_at) : '—'}
- </span>
- {s.last_fired_at ? <span>· last ran {rel(s.last_fired_at)}</span> : null}
- </div>
-
- {s.state === 'auto_paused' && s.last_error ? (
- <div className="flex items-start gap-1.5 text-xs text-red-600 dark:text-red-500">
- <AlertTriangle className="mt-0.5 size-3.5 shrink-0" />
- <span className="min-w-0">
- Auto-paused after repeated failures — {s.last_error}. Resume once fixed.
- </span>
- </div>
- ) : null}
-
- <button
- type="button"
- onClick={() => setExpanded(open ? null : s.id)}
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs transition-colors"
- >
- {open ? <ChevronDown className="size-3.5" /> : <ChevronRight className="size-3.5" />}
- Recent runs
- </button>
- {open ? (
- <div className="bg-muted/40 -mx-1 rounded-md">
- <ScheduleRuns agentId={agentId} scheduleId={s.id} />
- </div>
- ) : null}
- </PanelContent>
- </Panel>
- </li>
- )
- })}
- </ul>
- ) : !form ? (
- <div className="border-border rounded-lg border border-dashed py-12 text-center">
- <CalendarClock className="text-muted-foreground mx-auto size-6" />
- <p className="mt-3 text-sm font-medium">No schedules yet</p>
- <p className="text-muted-foreground mx-auto mt-1 max-w-sm text-sm">
- Run this agent automatically — a draft PR every morning, a nightly audit, a periodic sweep.
- </p>
- {!repoManaged ? (
- <Button size="sm" className="mt-4" onClick={openCreate}>
- <Plus className="size-4" />
- Create a schedule
- </Button>
- ) : null}
- </div>
- ) : null}
-
- <p className="text-muted-foreground text-xs">
- Or from the CLI: <code className="font-mono">oc agent schedule create &lt;name&gt; --cron "0 9 * * 1-5" --input …</code>
- </p>
-
- <ConfirmDialog
- open={pendingDelete !== null}
- onOpenChange={(open) => !open && setPendingDelete(null)}
- title={`Delete "${pendingDelete?.name ?? ''}"?`}
- description="This schedule stops firing immediately. Run history is kept."
- confirmLabel="Delete"
- destructive
- pending={remove.isPending}
- onConfirm={() => pendingDelete && remove.mutate(pendingDelete)}
- />
- </div>
- )
-}
-
diff --git a/web/src/components/agent-security-alert.test.tsx b/web/src/components/agent-security-alert.test.tsx
deleted file mode 100644
index cbeb17d4..00000000
--- a/web/src/components/agent-security-alert.test.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter } from 'react-router-dom'
-import { describe, expect, it, vi } from 'vitest'
-import { AgentSecurityAlert } from './agent-security-alert'
-import type { AgentSecurityNotification } from '@/api/client'
-
-const alert: AgentSecurityNotification = {
- id: 'hse_aaaaaaaaaaaaaaaaaaaaaaaa',
- agentId: 'agt_bbbbbbbbbbbbbbbbbbbbbbbb',
- hookId: 'hk_cccccccccccccccccccccccc',
- kind: 'secret_exposure',
- occurredAt: '2026-07-08T00:00:00.000Z',
- acknowledgedAt: null,
- acknowledgedBy: null,
-}
-
-function render(
- alerts: AgentSecurityNotification[],
- options: { acknowledging?: boolean; acknowledgeFailed?: boolean } = {},
-) {
- return renderToStaticMarkup(
- <MemoryRouter>
- <AgentSecurityAlert
- alerts={alerts}
- onAcknowledge={vi.fn()}
- {...options}
- />
- </MemoryRouter>,
- )
-}
-
-describe('AgentSecurityAlert', () => {
- it('renders persistent server-owned copy, an Agent link, and a keyboard button', () => {
- const markup = render([alert])
-
- expect(markup).toContain('role="alert"')
- expect(markup).toContain('An Agent Hook URL was exposed and revoked.')
- expect(markup).toContain(
- `href="/agents/${alert.agentId}/settings?section=hooks"`,
- )
- expect(markup).toContain('>Acknowledge</button>')
- expect(markup).toContain('sm:flex-row')
- expect(markup).not.toContain(alert.hookId)
- expect(markup).not.toContain('GitHub')
- })
-
- it('keeps the alert visible during acknowledgement and after a failed attempt', () => {
- expect(render([alert], { acknowledging: true })).toContain('Acknowledging…')
- expect(render([alert], { acknowledging: true })).toContain('disabled=""')
- expect(render([alert], { acknowledgeFailed: true })).toContain(
- 'Could not acknowledge the alert. Try again.',
- )
- })
-
- it('summarizes multiple alerts and renders nothing once all are acknowledged', () => {
- expect(
- render([alert, { ...alert, id: 'hse_dddddddddddddddddddddddd' }]),
- ).toContain('2 Agent Hook URLs were exposed and revoked.')
- expect(render([])).toBe('')
- })
-})
diff --git a/web/src/components/agent-security-alert.tsx b/web/src/components/agent-security-alert.tsx
deleted file mode 100644
index 5e5f2763..00000000
--- a/web/src/components/agent-security-alert.tsx
+++ /dev/null
@@ -1,93 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { ShieldAlert } from 'lucide-react'
-import { Link } from 'react-router-dom'
-import {
- acknowledgeAgentSecurityNotification,
- listAgentSecurityNotifications,
- type AgentSecurityNotification,
-} from '@/api/client'
-import { Button } from '@/components/ui/button'
-
-export function AgentSecurityAlert({
- alerts,
- acknowledging = false,
- acknowledgeFailed = false,
- onAcknowledge,
-}: {
- alerts: AgentSecurityNotification[]
- acknowledging?: boolean
- acknowledgeFailed?: boolean
- onAcknowledge: (id: string) => void
-}) {
- const alert = alerts[0]
- if (!alert) return null
-
- return (
- <div
- className="border-destructive/40 bg-status-error-bg text-destructive flex flex-col gap-2 border-b px-4 py-3 sm:flex-row sm:items-center sm:justify-between sm:gap-4 sm:px-8"
- role="alert"
- >
- <div className="flex min-w-0 items-start gap-2.5">
- <ShieldAlert className="mt-0.5 size-4 shrink-0" aria-hidden />
- <div className="min-w-0 text-sm">
- <p className="font-semibold">
- {alerts.length === 1
- ? 'An Agent Hook URL was exposed and revoked.'
- : `${alerts.length} Agent Hook URLs were exposed and revoked.`}
- </p>
- <p className="text-destructive/80 mt-0.5">
- Review the affected Hook before reconnecting its sender.{' '}
- <Link
- to={`/agents/${encodeURIComponent(alert.agentId)}/settings?section=hooks`}
- className="font-medium underline underline-offset-2"
- >
- Review agent
- </Link>
- </p>
- {acknowledgeFailed ? (
- <p className="mt-1 font-medium">
- Could not acknowledge the alert. Try again.
- </p>
- ) : null}
- </div>
- </div>
- <Button
- type="button"
- variant="destructive"
- size="sm"
- className="self-start sm:self-center"
- disabled={acknowledging}
- onClick={() => onAcknowledge(alert.id)}
- >
- {acknowledging ? 'Acknowledging…' : 'Acknowledge'}
- </Button>
- </div>
- )
-}
-
-export function AgentSecurityAlertBanner() {
- const queryClient = useQueryClient()
- const { data } = useQuery({
- queryKey: ['agent-security-notifications'],
- queryFn: listAgentSecurityNotifications,
- retry: 2,
- refetchInterval: 30_000,
- })
- const acknowledge = useMutation({
- mutationFn: acknowledgeAgentSecurityNotification,
- onSuccess: () => {
- void queryClient.invalidateQueries({
- queryKey: ['agent-security-notifications'],
- })
- },
- })
-
- return (
- <AgentSecurityAlert
- alerts={data?.data ?? []}
- acknowledging={acknowledge.isPending}
- acknowledgeFailed={acknowledge.isError}
- onAcknowledge={(id) => acknowledge.mutate(id)}
- />
- )
-}
diff --git a/web/src/components/agent-skills.tsx b/web/src/components/agent-skills.tsx
deleted file mode 100644
index d054fdae..00000000
--- a/web/src/components/agent-skills.tsx
+++ /dev/null
@@ -1,128 +0,0 @@
-import { useRef } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Upload } from 'lucide-react'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import { getAgentSkills, putAgentSkills, deleteAgentSkills } from '@/api/client'
-import {
- Panel,
- PanelContent,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-
-const fmtBytes = (n: number) => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KiB`)
-
-/**
- * Skills panel — a thin consumer of the agent skills sub-resource (design 009 §8). The API owns
- * unzip + validate + canonicalize + bundle: we just GET the file list, PUT a raw .zip to deploy a
- * new revision (active behavior, skills replaced), or DELETE to clear. No client-side parsing.
- */
-export function AgentSkills({ agentId }: { agentId: string }) {
- const queryClient = useQueryClient()
- const inputRef = useRef<HTMLInputElement>(null)
-
- const { data, isLoading } = useQuery({
- queryKey: ['agent-skills', agentId],
- queryFn: () => getAgentSkills(agentId),
- })
- const skills = data?.skills ?? []
-
- // A skills change deploys a new active revision — refresh the dependent views.
- const invalidate = () => {
- void queryClient.invalidateQueries({ queryKey: ['agent-skills', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agent-revisions', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agent-deploys', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- }
- const upload = useMutation({
- mutationFn: (zip: File) => putAgentSkills(agentId, zip),
- onSuccess: (r) => {
- invalidate()
- notifySuccess(`Skills deployed${r.revision ? ` — revision #${r.revision.number} active` : ''}`)
- },
- onError: (e) => notifyError("Couldn't upload the skills.", e),
- })
- const remove = useMutation({
- mutationFn: () => deleteAgentSkills(agentId),
- onSuccess: (r) => {
- invalidate()
- // Removing skills deploys a new forward revision (no skills); name it for clear feedback.
- notifySuccess(`Skills removed${r.revision ? ` — revision #${r.revision.number} active` : ''}`)
- },
- onError: (e) => notifyError("Couldn't remove the skills.", e),
- })
- const busy = upload.isPending || remove.isPending
-
- return (
- <Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Skills</PanelTitle>
- </PanelHeader>
- <PanelContent className="space-y-3">
- {!isLoading && skills.length === 0 ? (
- <div className="flex items-center justify-between gap-6 rounded-md border border-dashed px-4 py-3">
- <p className="text-muted-foreground text-xs">
- No skills yet. A skill is a folder with a SKILL.md — upload a .zip
- like this:
- </p>
- <pre className="text-muted-foreground/70 shrink-0 text-left font-mono text-xs leading-snug">
-{`skills/
-├─ triage/
-│ └─ SKILL.md
-└─ pr-review/
- ├─ SKILL.md
- └─ run.sh`}
- </pre>
- </div>
- ) : (
- <ul className="divide-border divide-y">
- {skills.map((s) => (
- <li key={s.name} className="py-2 first:pt-0">
- <div className="flex items-baseline justify-between gap-3">
- <span className="text-foreground font-mono text-[13px]">{s.name}</span>
- <span className="text-muted-foreground shrink-0 text-xs">
- {s.files.length} file{s.files.length === 1 ? '' : 's'} ·{' '}
- {fmtBytes(s.files.reduce((n, f) => n + f.size, 0))}
- </span>
- </div>
- {s.description ? (
- <p className="text-muted-foreground mt-0.5 text-xs">{s.description}</p>
- ) : null}
- </li>
- ))}
- </ul>
- )}
-
- <div className="flex items-center gap-2">
- <input
- ref={inputRef}
- type="file"
- accept=".zip,application/zip"
- className="hidden"
- onChange={(e) => {
- const f = e.target.files?.[0]
- if (f) upload.mutate(f)
- e.target.value = '' // allow re-selecting the same file
- }}
- />
- {skills.length > 0 ? (
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground"
- disabled={busy}
- onClick={() => remove.mutate()}
- >
- {remove.isPending ? 'Removing…' : 'Remove all'}
- </Button>
- ) : null}
- <Button size="sm" variant="outline" className="ml-auto" disabled={busy} onClick={() => inputRef.current?.click()}>
- <Upload className="size-4" />
- {upload.isPending ? 'Uploading…' : skills.length ? 'Replace .zip' : 'Upload .zip'}
- </Button>
- </div>
- </PanelContent>
- </Panel>
- )
-}
diff --git a/web/src/components/app-shell-nav.ts b/web/src/components/app-shell-nav.ts
index 1a3b4895..621513a7 100644
--- a/web/src/components/app-shell-nav.ts
+++ b/web/src/components/app-shell-nav.ts
@@ -160,15 +160,8 @@ export function managedAgentsNav(options: {
groups.push({
label: 'Durable sessions',
collapsible: true,
- landingTo: '/agents',
+ landingTo: '/credentials',
items: [
- { to: '/agents', label: 'Agents', icon: Bot, preview: true },
- {
- to: '/sessions',
- label: 'Sessions',
- icon: MessagesSquare,
- preview: true,
- },
{
to: '/credentials',
label: 'Credentials',
diff --git a/web/src/components/app-shell.tsx b/web/src/components/app-shell.tsx
index 3c8f659f..6ffd3a56 100644
--- a/web/src/components/app-shell.tsx
+++ b/web/src/components/app-shell.tsx
@@ -10,8 +10,6 @@ import { useQuery } from '@tanstack/react-query'
import {
LayoutGrid,
Rocket,
- Bot,
- MessagesSquare,
Monitor,
Boxes,
Layers,
@@ -48,7 +46,6 @@ import {
} from '@/components/ui/dropdown-menu'
import { ErrorBoundary } from '@/components/error-boundary'
import { ThemeToggle } from '@/components/theme-toggle'
-import { AgentSecurityAlertBanner } from '@/components/agent-security-alert'
import { cn } from '@/lib/utils'
import { managedAgentsExperimentEnabled } from '@/managed-agents/feature'
import {
@@ -92,13 +89,6 @@ const LEGACY_NAV: LegacyNavGroup[] = [
{
label: 'Agents',
items: [
- { to: '/agents', label: 'Agents', icon: Bot, preview: true },
- {
- to: '/sessions',
- label: 'Sessions',
- icon: MessagesSquare,
- preview: true,
- },
{
to: '/credentials',
label: 'Credentials',
@@ -336,7 +326,10 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
const swarmResources = useQuery({
queryKey: ['managed-memory-resources', projectId],
queryFn: () =>
- getManagedMemoryResources({ projectId: projectId!, environment: 'default' }),
+ getManagedMemoryResources({
+ projectId: projectId!,
+ environment: 'default',
+ }),
enabled: Boolean(managedAgentsExperimentEnabled && projectId),
staleTime: 60_000,
})
@@ -443,7 +436,6 @@ function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
))}
</nav>
-
<div className="border-t p-3">
{managedAgentsExperimentEnabled ? (
<ManagedProfileMenu onNavigate={onNavigate} />
@@ -580,7 +572,6 @@ export default function AppShell() {
<div className="flex flex-1 flex-col md:pt-16 md:pl-60">
<div className="sticky top-14 z-20 md:top-16">
<BillingWarningBanner />
- <AgentSecurityAlertBanner />
</div>
<HaltModal />
<main
diff --git a/web/src/components/deployment-progress.tsx b/web/src/components/deployment-progress.tsx
deleted file mode 100644
index 902f5134..00000000
--- a/web/src/components/deployment-progress.tsx
+++ /dev/null
@@ -1,209 +0,0 @@
-import { Fragment } from 'react'
-import { Check, Circle, CircleAlert, Loader2 } from 'lucide-react'
-import type { AgentDeployment, AgentDeploymentLog } from '@/api/client'
-import { cn } from '@/lib/utils'
-
-const PHASES = [
- {
- label: 'Prepare',
- states: [
- 'accepted',
- 'queued',
- 'fetching',
- 'validating',
- 'installing',
- 'source',
- 'install',
- ],
- },
- { label: 'Build', states: ['building', 'uploading', 'build', 'artifact'] },
- { label: 'Deploy', states: ['deploying', 'verifying', 'deploy', 'verify'] },
-] as const
-
-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),
- )
-}
-
-export function DeploymentPhases({
- deployment,
- align = 'end',
-}: {
- deployment: AgentDeployment
- align?: 'start' | 'end'
-}) {
- const current = phaseIndex(deployment)
- const failed = deployment.state === 'failed'
- const terminalWithoutPhase = failed && current < 0
- const allDone = deployment.state === 'ready'
- const activeLabel = PHASES[current]?.label
- const liveAnnouncement = allDone
- ? 'All deployment phases complete.'
- : terminalWithoutPhase
- ? 'The deployment failed before a phase was recorded.'
- : activeLabel
- ? `${activeLabel} ${failed ? 'failed' : deployment.terminal ? 'ended' : 'in progress'}.`
- : 'Waiting for deployment to start.'
-
- return (
- <div className="shrink-0">
- <span className="sr-only" aria-live="polite" aria-atomic="true">
- {liveAnnouncement}
- </span>
- <ol
- className={cn(
- 'flex flex-wrap items-center gap-y-1.5',
- align === 'end' && 'sm:justify-end',
- )}
- aria-label="Deployment phases"
- >
- {PHASES.map((phase, index) => {
- const done = allDone || (current >= 0 && index < current)
- const active = !allDone && !deployment.terminal && index === current
- const terminalPhase =
- !allDone && deployment.terminal && index === current
- const phaseFailed = terminalPhase && failed
- const Icon = phaseFailed
- ? CircleAlert
- : done
- ? Check
- : active
- ? Loader2
- : Circle
- return (
- <li
- key={phase.label}
- className="flex items-center"
- aria-current={active ? 'step' : undefined}
- >
- <span
- className={cn(
- 'flex items-center gap-1 text-[11px] font-medium',
- phaseFailed
- ? 'text-status-error'
- : done || active
- ? 'text-foreground'
- : 'text-muted-foreground',
- )}
- >
- <Icon
- className={cn(
- 'size-3',
- phaseFailed && 'text-status-error',
- done && 'text-status-running',
- active && 'text-status-pending',
- active &&
- !failed &&
- 'animate-spin motion-reduce:animate-none',
- )}
- aria-hidden
- />
- {phase.label}
- {phaseFailed ? (
- <span className="sr-only">, failed</span>
- ) : active ? (
- <span className="sr-only">, in progress</span>
- ) : done ? (
- <span className="sr-only">, complete</span>
- ) : terminalPhase ? (
- <span className="sr-only">, ended here</span>
- ) : (
- <span className="sr-only">, pending</span>
- )}
- </span>
- {index < PHASES.length - 1 ? (
- <span className="bg-border mx-2 h-px w-3" aria-hidden="true" />
- ) : null}
- </li>
- )
- })}
- </ol>
- {terminalWithoutPhase ? (
- <p
- className={cn(
- 'text-status-error mt-1.5 flex items-center gap-1 text-[11px]',
- align === 'end' && 'sm:justify-end',
- )}
- >
- <CircleAlert className="size-3.5" aria-hidden />
- Phase unavailable
- </p>
- ) : null}
- </div>
- )
-}
-
-export 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>
- )
-}
diff --git a/web/src/components/managed-slack-workspace-claims.tsx b/web/src/components/managed-slack-workspace-claims.tsx
deleted file mode 100644
index 1318e2c8..00000000
--- a/web/src/components/managed-slack-workspace-claims.tsx
+++ /dev/null
@@ -1,192 +0,0 @@
-import { useState } from 'react'
-import {
- useMutation,
- useQueryClient,
- type UseQueryResult,
-} from '@tanstack/react-query'
-import { Link } from 'react-router-dom'
-import { ArrowRightLeft, Unplug } from 'lucide-react'
-import {
- disconnectManagedSlack,
- type ManagedSlackWorkspaceConnection,
-} from '@/api/client'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import {
- managedSlackConnectionsQueryKey,
- managedSlackDisconnectCopy,
-} from '@/lib/managed-slack-connections'
-import { cn } from '@/lib/utils'
-
-type ClaimsQuery = Pick<
- UseQueryResult<ManagedSlackWorkspaceConnection[]>,
- 'data' | 'isLoading' | 'isError' | 'refetch'
->
-
-export function ManagedSlackWorkspaceClaims({
- currentAgentId,
- currentAgentName,
- query,
- className,
- onMoveHere,
-}: {
- currentAgentId: string
- currentAgentName: string
- query: ClaimsQuery
- className?: string
- onMoveHere?: () => void
-}) {
- const queryClient = useQueryClient()
- const [disconnecting, setDisconnecting] =
- useState<ManagedSlackWorkspaceConnection | null>(null)
- const connections = (query.data ?? []).filter(
- (connection) => connection.agent.id !== currentAgentId,
- )
- const disconnectMutation = useMutation({
- mutationFn: (connection: ManagedSlackWorkspaceConnection) =>
- disconnectManagedSlack(connection.agent.id),
- onSuccess: (_result, connection) => {
- queryClient.setQueryData<ManagedSlackWorkspaceConnection[]>(
- managedSlackConnectionsQueryKey,
- (current) =>
- current?.filter(
- (candidate) => candidate.agent.id !== connection.agent.id,
- ) ?? [],
- )
- void queryClient.invalidateQueries({
- queryKey: managedSlackConnectionsQueryKey,
- })
- void queryClient.invalidateQueries({
- queryKey: ['slack', 'managed', connection.agent.id],
- })
- setDisconnecting(null)
- const workspace =
- connection.workspace?.name ||
- connection.workspace?.id ||
- 'Slack workspace'
- notifySuccess(
- onMoveHere
- ? `${workspace} is ready to move from ${connection.agent.name}.`
- : `${workspace} disconnected from ${connection.agent.name}.`,
- onMoveHere
- ? `Finish authorizing it for ${currentAgentName} in Slack.`
- : `Connect Slack again to select it for ${currentAgentName}.`,
- )
- onMoveHere?.()
- },
- onError: (error) =>
- notifyError("Couldn't disconnect the Slack workspace.", error),
- })
-
- if (!query.isLoading && !query.isError && connections.length === 0) {
- return null
- }
-
- const copy = disconnecting
- ? managedSlackDisconnectCopy(disconnecting, currentAgentName, !!onMoveHere)
- : null
- const heading = query.isLoading
- ? 'Checking existing Slack workspaces'
- : query.isError
- ? 'Existing Slack connections are unavailable'
- : 'Slack workspaces already in use'
- const description = query.isLoading
- ? `Checking whether a workspace already sends messages to another agent before connecting ${currentAgentName}.`
- : query.isError
- ? 'You can retry this check or continue. Slack will verify the workspace claim again before connecting.'
- : onMoveHere
- ? `Move a workspace here, or connect a different workspace without changing these.`
- : `Disconnect a workspace before selecting it for ${currentAgentName}. You can connect a different workspace without changing these.`
-
- return (
- <>
- <section className={cn('border-t pt-4', className)} aria-label={heading}>
- <div>
- <p className="text-sm font-medium">{heading}</p>
- <p className="text-muted-foreground mt-0.5 max-w-xl text-xs leading-relaxed">
- {description}
- </p>
- </div>
-
- {query.isLoading ? (
- <div
- className="mt-3 space-y-2"
- aria-label="Checking Slack workspaces"
- >
- <Skeleton className="h-4 w-52" />
- <Skeleton className="h-8 w-full" />
- </div>
- ) : query.isError ? (
- <div className="mt-3 flex flex-wrap items-center gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => void query.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : (
- <div className="mt-3 divide-y">
- {connections.map((connection) => {
- const workspace =
- connection.workspace?.name ||
- connection.workspace?.id ||
- 'Slack workspace'
- return (
- <div
- key={`${connection.workspace?.id ?? connection.agent.id}:${connection.agent.id}`}
- className="flex flex-col gap-2 py-2.5 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between"
- >
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">{workspace}</p>
- <p className="text-muted-foreground mt-0.5 truncate text-xs">
- Sends messages to {connection.agent.name}
- </p>
- </div>
- <div className="flex shrink-0 flex-wrap items-center gap-1">
- <Button variant="outline" size="sm" asChild>
- <Link to={`/agents/${connection.agent.id}`}>
- Open agent
- </Link>
- </Button>
- <Button
- variant={onMoveHere ? 'outline' : 'ghost'}
- size="sm"
- disabled={disconnectMutation.isPending}
- onClick={() => setDisconnecting(connection)}
- >
- {onMoveHere ? (
- <ArrowRightLeft className="size-4" aria-hidden />
- ) : (
- <Unplug className="size-4" aria-hidden />
- )}
- {onMoveHere ? 'Move here' : 'Disconnect'}
- </Button>
- </div>
- </div>
- )
- })}
- </div>
- )}
- </section>
-
- <ConfirmDialog
- open={disconnecting != null}
- onOpenChange={(open) => {
- if (!open) setDisconnecting(null)
- }}
- title={copy?.title ?? 'Disconnect Slack workspace?'}
- description={copy?.description}
- confirmLabel={onMoveHere ? 'Continue in Slack' : 'Disconnect workspace'}
- destructive={!onMoveHere}
- pending={disconnectMutation.isPending}
- onConfirm={() => {
- if (disconnecting) disconnectMutation.mutate(disconnecting)
- }}
- />
- </>
- )
-}
diff --git a/web/src/components/manual-agent-form.tsx b/web/src/components/manual-agent-form.tsx
deleted file mode 100644
index 6310ba5f..00000000
--- a/web/src/components/manual-agent-form.tsx
+++ /dev/null
@@ -1,345 +0,0 @@
-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'
-import { cn } from '@/lib/utils'
-
-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.'
-
-function FormSectionHeading({
- title,
- description,
-}: {
- title: string
- description: string
-}) {
- return (
- <div className="space-y-1">
- <h3 className="text-sm font-semibold">{title}</h3>
- <p className="text-muted-foreground text-sm leading-5">{description}</p>
- </div>
- )
-}
-
-export function ManualAgentForm({
- onCancel,
- layout = 'stacked',
-}: {
- onCancel: () => void
- layout?: 'stacked' | 'wide'
-}) {
- 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}/setup`)
- },
- 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)
- const wide = layout === 'wide'
-
- return (
- <form
- className="space-y-6"
- onSubmit={(event) => {
- event.preventDefault()
- if (canCreate) createMutation.mutate()
- }}
- >
- <div
- className={cn(
- 'grid gap-6',
- wide && 'lg:grid-cols-[minmax(0,1.2fr)_minmax(20rem,0.8fr)] lg:gap-0',
- )}
- >
- <div className={cn('space-y-5', wide && 'lg:pr-8')}>
- <FormSectionHeading
- title="Instructions"
- description="Name the agent and describe how it should behave."
- />
- <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="System prompt"
- htmlFor="agent-prompt"
- description="The instructions applied to every session."
- >
- <Textarea
- id="agent-prompt"
- value={prompt}
- onChange={(event) => setPrompt(event.target.value)}
- placeholder="You are a meticulous code reviewer…"
- className={cn(wide ? 'min-h-44' : 'min-h-28')}
- />
- </Field>
- </div>
-
- <div
- className={cn(
- 'space-y-5 border-t pt-6',
- wide && 'lg:border-t-0 lg:border-l lg:pt-0 lg:pl-8',
- )}
- >
- <FormSectionHeading
- title="Runtime"
- description="Choose how the agent runs and which model it uses."
- />
- <div
- className={cn('grid grid-cols-1 gap-4', !wide && '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={cn(
- 'border-border bg-panel-2 grid grid-cols-1 gap-4 rounded-md border p-3',
- !wide && '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>
- </div>
- <div className="flex flex-col-reverse justify-end gap-2 border-t pt-4 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/repository-access-agent-switch.test.tsx b/web/src/components/repository-access-agent-switch.test.tsx
deleted file mode 100644
index ddfc4c2c..00000000
--- a/web/src/components/repository-access-agent-switch.test.tsx
+++ /dev/null
@@ -1,140 +0,0 @@
-// @vitest-environment happy-dom
-
-import { act } from 'react'
-import { createRoot, type Root } from 'react-dom/client'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { afterEach, beforeEach, describe, expect, it } from 'vitest'
-import type { RepositoryAccess } from '@/api/client'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-import { RepositoryAccessPanel } from './repository-access'
-
-const agentA = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const agentB = 'agt_bbbbbbbbbbbbbbbbbbbbbbbb'
-
-const repository = {
- id: 'repo_1',
- full_name: 'acme/support-agent',
- default_branch: 'main',
- private: true,
-}
-
-function access(policy: RepositoryAccess['policy']): RepositoryAccess {
- return {
- policy,
- grant: {
- status: 'active',
- account: 'acme',
- repository_selection: 'all',
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- truncated: false,
- },
- effective_repositories: policy.mode === 'all' ? [repository] : [],
- unavailable_selected_repositories: [],
- }
-}
-
-function button(container: ParentNode, label: string): HTMLButtonElement {
- const match = [...container.querySelectorAll('button')].find((element) =>
- element.textContent?.includes(label),
- )
- if (!(match instanceof HTMLButtonElement))
- throw new Error(`Button not found: ${label}`)
- return match
-}
-
-function radio(container: ParentNode, label: string): HTMLInputElement {
- const match = [
- ...container.querySelectorAll<HTMLInputElement>('input[type="radio"]'),
- ].find((element) => element.closest('label')?.textContent?.includes(label))
- if (!match) throw new Error(`Radio not found: ${label}`)
- return match
-}
-
-describe('RepositoryAccessPanel agent scoping', () => {
- let container: HTMLDivElement
- let root: Root
- let client: QueryClient
-
- beforeEach(() => {
- ;(
- globalThis as typeof globalThis & {
- IS_REACT_ACT_ENVIRONMENT: boolean
- }
- ).IS_REACT_ACT_ENVIRONMENT = true
- container = document.createElement('div')
- document.body.append(container)
- root = createRoot(container)
- client = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- client.setQueryData(
- repositoryAccessQueryKey(agentA),
- access({ mode: 'all' }),
- )
- client.setQueryData(
- repositoryAccessQueryKey(agentB),
- access({ mode: 'selected', repository_ids: [] }),
- )
- client.setQueryData(['deploy-app'], {
- installed: true,
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- account: 'acme',
- repository_selection: 'all',
- repositories: [repository],
- })
- })
-
- afterEach(() => {
- act(() => root.unmount())
- client.clear()
- container.remove()
- document.body.replaceChildren()
- })
-
- function renderAgent(agentId: string) {
- act(() => {
- root.render(
- <QueryClientProvider client={client}>
- <RepositoryAccessPanel agentId={agentId} />
- </QueryClientProvider>,
- )
- })
- }
-
- it('discards Agent A draft, search, and confirmation when rerendered for Agent B', () => {
- renderAgent(agentA)
-
- const allPolicy = radio(container, 'All granted repositories')
- const selectedPolicyA = radio(container, 'Only selected repositories')
- expect(allPolicy.name).toBe(selectedPolicyA.name)
- expect(allPolicy.checked).toBe(true)
- act(() => selectedPolicyA.click())
- expect(selectedPolicyA.checked).toBe(true)
- const search = container.querySelector<HTMLInputElement>(
- 'input[aria-label="Find a repository"]',
- )
- expect(search).not.toBeNull()
- act(() => {
- search!.value = 'support'
- search!.dispatchEvent(new Event('input', { bubbles: true }))
- })
- expect(search!.value).toBe('support')
-
- act(() => button(container, 'Save access').click())
- expect(document.body.textContent).toContain('Narrow repository access?')
-
- renderAgent(agentB)
-
- const selectedPolicy = radio(container, 'Only selected repositories')
- expect(selectedPolicy.checked).toBe(true)
- expect(button(container, 'Save access').disabled).toBe(true)
- expect(
- container.querySelector<HTMLInputElement>(
- 'input[aria-label="Find a repository"]',
- )?.value,
- ).toBe('')
- expect(document.body.textContent).not.toContain('Narrow repository access?')
- })
-})
diff --git a/web/src/components/repository-access.test.tsx b/web/src/components/repository-access.test.tsx
deleted file mode 100644
index 6989b5f8..00000000
--- a/web/src/components/repository-access.test.tsx
+++ /dev/null
@@ -1,164 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { describe, expect, it } from 'vitest'
-import type { RepositoryAccess } from '@/api/client'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-import {
- RepositoryAccessPanel,
- RepositoryAccessSummary,
-} from './repository-access'
-
-const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-
-function renderAccess(access: RepositoryAccess, summary = false) {
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- client.setQueryData(repositoryAccessQueryKey(agentId), access)
- client.setQueryData(['deploy-app'], {
- installed: true,
- install_url: access.grant.install_url,
- configure_url: access.grant.configure_url,
- account: access.grant.account,
- repository_selection: access.grant.repository_selection,
- repositories: access.effective_repositories ?? [],
- })
- return renderToStaticMarkup(
- <QueryClientProvider client={client}>
- {summary ? (
- <RepositoryAccessSummary agentId={agentId} onOpenSettings={() => {}} />
- ) : (
- <RepositoryAccessPanel agentId={agentId} />
- )}
- </QueryClientProvider>,
- )
-}
-
-const selected: RepositoryAccess = {
- policy: { mode: 'selected', repository_ids: ['repo_1'] },
- grant: {
- status: 'active',
- account: 'acme',
- repository_selection: 'selected',
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- truncated: false,
- },
- effective_repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/a-very-long-repository-name',
- default_branch: 'main',
- private: true,
- },
- ],
- unavailable_selected_repositories: [],
-}
-
-describe('repository access UI', () => {
- it('renders the default all-granted policy without requiring a save', () => {
- const html = renderAccess({ ...selected, policy: { mode: 'all' } })
- expect(html).toContain('All granted repositories')
- expect(html).toContain('Includes repositories added')
- expect(html).toContain('Save access')
- expect(html).toContain('disabled=""')
- })
-
- it('renders a selected policy, current repository and settings action', () => {
- const html = renderAccess(selected)
- expect(html).toContain('Only selected repositories')
- expect(html).toContain('acme/a-very-long-repository-name')
- expect(html).toContain('Configure GitHub app')
- expect(html).toContain('Save access')
- })
-
- it('renders selected-empty as disabled repository work', () => {
- const html = renderAccess({
- ...selected,
- policy: { mode: 'selected', repository_ids: [] },
- effective_repositories: [],
- })
- expect(html).toContain('Repository work is disabled')
- expect(html).toContain('This agent can still chat')
- })
-
- it('warns on a partial catalog and keeps unavailable selections visible', () => {
- const html = renderAccess({
- ...selected,
- grant: { ...selected.grant, truncated: true },
- policy: {
- mode: 'selected',
- repository_ids: ['repo_1', 'repo_hidden'],
- },
- unavailable_selected_repositories: [
- { id: 'repo_hidden', full_name: 'acme/removed' },
- ],
- })
- expect(html).toContain('partial repository list')
- expect(html).toContain('Hidden existing selections are preserved')
- expect(html).toContain('acme/removed')
- expect(html).toContain('Unavailable')
- })
-
- it('explains that switching from a truncated all grant is intentionally narrowing', () => {
- const html = renderAccess({
- ...selected,
- grant: { ...selected.grant, truncated: true },
- policy: { mode: 'all' },
- })
- expect(html).toContain(
- 'Switching to selected access limits the agent to repositories you choose from this partial list.',
- )
- expect(html).not.toContain('Hidden existing selections are preserved')
- })
-
- it('distinguishes an unavailable grant from a valid empty grant', () => {
- const html = renderAccess({
- ...selected,
- grant: { ...selected.grant, status: 'unavailable' },
- effective_repositories: null,
- })
- expect(html).toContain('GitHub access is temporarily unavailable')
- expect(html).toContain('Nothing changed')
- expect(html).toContain('>Retry<')
- expect(html).not.toContain('Reconnect GitHub')
- expect(html).not.toContain('No repositories are available')
- })
-
- it('offers GitHub installation without making chat unavailable', () => {
- const html = renderAccess({
- ...selected,
- grant: {
- ...selected.grant,
- status: 'not_installed',
- account: null,
- repository_selection: null,
- configure_url: null,
- },
- effective_repositories: [],
- })
- expect(html).toContain('Connect GitHub to work in repositories')
- expect(html).toContain('Chat still works without GitHub')
- expect(html).toContain('>Connect GitHub<')
- })
-
- it('summarizes access without duplicating the full editor', () => {
- const html = renderAccess(selected, true)
- expect(html).toContain('1 selected repository')
- expect(html).toContain('Manage GitHub')
- expect(html).not.toContain('Find a repository')
- })
-
- it('distinguishes an unavailable summary from a missing installation', () => {
- const html = renderAccess(
- {
- ...selected,
- grant: { ...selected.grant, status: 'unavailable' },
- effective_repositories: null,
- },
- true,
- )
- expect(html).toContain('GitHub access is unavailable')
- expect(html).not.toContain('GitHub is not connected')
- })
-})
diff --git a/web/src/components/repository-access.tsx b/web/src/components/repository-access.tsx
deleted file mode 100644
index acbb23bb..00000000
--- a/web/src/components/repository-access.tsx
+++ /dev/null
@@ -1,619 +0,0 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import {
- ArrowUpRight,
- Check,
- ChevronRight,
- GitPullRequest,
- LoaderCircle,
- Search,
- ShieldCheck,
-} from 'lucide-react'
-import {
- getDeployApp,
- updateRepositoryAccess,
- type RepositoryAccess,
- type RepositoryAccessPolicy,
-} from '@/api/client'
-import { GithubMark } from '@/components/github-mark'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelFooter,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from '@/components/ui/alert-dialog'
-import { Button } from '@/components/ui/button'
-import { Checkbox } from '@/components/ui/checkbox'
-import { Input } from '@/components/ui/input'
-import { Skeleton } from '@/components/ui/skeleton'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import { useRepositoryAccess } from '@/hooks/use-repository-access'
-import {
- isNarrowingRepositoryAccess,
- repositoryAccessCandidates,
- repositoryAccessQueryKey,
- sameRepositoryAccessPolicy,
- selectedRepositoryIds,
- toggleSelectedRepository,
-} from '@/lib/repository-access'
-import { cn } from '@/lib/utils'
-
-function ExternalAction({
- href,
- children,
-}: {
- href: string
- children: string
-}) {
- return (
- <Button asChild size="sm" variant="outline">
- <a href={href} target="_blank" rel="noreferrer">
- {children}
- <ArrowUpRight />
- </a>
- </Button>
- )
-}
-
-function AccessUnavailable({
- access,
- onRetry,
-}: {
- access: RepositoryAccess
- onRetry: () => void
-}) {
- if (access.grant.status === 'not_installed') {
- return (
- <div className="flex flex-col items-start gap-3 py-1">
- <div>
- <p className="text-sm font-medium">
- Connect GitHub to work in repositories
- </p>
- <p className="text-muted-foreground mt-1 text-sm">
- Chat still works without GitHub. Connect the OpenComputer app when
- this agent needs to read code or open pull requests.
- </p>
- </div>
- <ExternalAction href={access.grant.install_url}>
- Connect GitHub
- </ExternalAction>
- </div>
- )
- }
-
- return (
- <div className="flex flex-col items-start gap-3 py-1">
- <div>
- <p className="text-sm font-medium">
- GitHub access is temporarily unavailable
- </p>
- <p className="text-muted-foreground mt-1 text-sm">
- Nothing changed. Try loading the installation again.
- </p>
- </div>
- <Button size="sm" variant="outline" onClick={onRetry}>
- Retry
- </Button>
- </div>
- )
-}
-
-interface RepositoryAccessPanelProps {
- agentId: string
- context?: 'setup' | 'settings'
-}
-
-export function RepositoryAccessPanel({
- agentId,
- context = 'settings',
-}: RepositoryAccessPanelProps) {
- return (
- <RepositoryAccessPanelForAgent
- key={agentId}
- agentId={agentId}
- context={context}
- />
- )
-}
-
-function RepositoryAccessPanelForAgent({
- agentId,
- context = 'settings',
-}: RepositoryAccessPanelProps) {
- const queryClient = useQueryClient()
- const accessQuery = useRepositoryAccess(agentId)
- const deployAppQuery = useQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- enabled:
- accessQuery.data?.grant.status === 'active' &&
- accessQuery.data.policy.mode === 'selected',
- staleTime: 30_000,
- refetchOnWindowFocus: 'always',
- })
- const [draft, setDraft] = useState<RepositoryAccessPolicy | null>(
- () => accessQuery.data?.policy ?? null,
- )
- const baselinePolicy = useRef<RepositoryAccessPolicy | null>(null)
- const [search, setSearch] = useState('')
- const [confirming, setConfirming] = useState(false)
-
- const access = accessQuery.data
- useEffect(() => {
- if (!access) return
- setDraft((current) => {
- const clean =
- current === null ||
- baselinePolicy.current === null ||
- sameRepositoryAccessPolicy(current, baselinePolicy.current)
- baselinePolicy.current = access.policy
- return clean ? access.policy : current
- })
- }, [access])
-
- const candidates = useMemo(
- () =>
- access ? repositoryAccessCandidates(access, deployAppQuery.data) : [],
- [access, deployAppQuery.data],
- )
- const visibleCandidates = useMemo(() => {
- const term = search.trim().toLocaleLowerCase()
- return term
- ? candidates.filter((repo) =>
- repo.full_name.toLocaleLowerCase().includes(term),
- )
- : candidates
- }, [candidates, search])
-
- const saveMutation = useMutation({
- mutationFn: (policy: RepositoryAccessPolicy) =>
- updateRepositoryAccess(agentId, policy),
- onMutate: async (policy) => {
- const key = repositoryAccessQueryKey(agentId)
- await queryClient.cancelQueries({ queryKey: key })
- const previous = queryClient.getQueryData<RepositoryAccess>(key)
- if (previous) queryClient.setQueryData(key, { ...previous, policy })
- return { previous }
- },
- onError: (error, _policy, contextValue) => {
- if (contextValue?.previous) {
- queryClient.setQueryData(
- repositoryAccessQueryKey(agentId),
- contextValue.previous,
- )
- setDraft(contextValue.previous.policy)
- baselinePolicy.current = contextValue.previous.policy
- }
- notifyError("Couldn't save repository access.", error)
- },
- onSuccess: (next) => {
- queryClient.setQueryData(repositoryAccessQueryKey(agentId), next)
- setDraft(next.policy)
- baselinePolicy.current = next.policy
- notifySuccess('Repository access saved.')
- },
- onSettled: () =>
- queryClient.invalidateQueries({
- queryKey: repositoryAccessQueryKey(agentId),
- }),
- })
-
- const save = () => {
- if (!access || !draft) return
- if (isNarrowingRepositoryAccess(access.policy, draft)) {
- setConfirming(true)
- return
- }
- saveMutation.mutate(draft)
- }
-
- const title =
- context === 'setup' ? 'Choose working repositories' : 'Repository access'
- const description =
- context === 'setup'
- ? 'Optional. Let this agent check out code and open pull requests.'
- : 'Choose where this agent can check out code and open pull requests.'
-
- return (
- <Panel className="min-w-0 overflow-hidden">
- <PanelHeader className="flex-wrap">
- <div className="min-w-0">
- <PanelTitle className="flex items-center gap-2">
- <GithubMark className="size-4" />
- {title}
- </PanelTitle>
- <PanelDescription className="mt-1">{description}</PanelDescription>
- </div>
- {access?.grant.status === 'active' && access.grant.account ? (
- <span className="text-muted-foreground max-w-40 truncate text-xs">
- {access.grant.account}
- </span>
- ) : null}
- </PanelHeader>
- <PanelContent>
- {accessQuery.isLoading ? (
- <div className="space-y-3" aria-label="Loading repository access">
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-24 w-full" />
- </div>
- ) : accessQuery.isError ? (
- <div className="flex flex-col items-start gap-3 py-1">
- <div>
- <p className="text-sm font-medium">
- Couldn’t load repository access
- </p>
- <p className="text-muted-foreground mt-1 text-sm">
- Nothing changed. Try loading it again.
- </p>
- </div>
- <Button
- size="sm"
- variant="outline"
- onClick={() => void accessQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : access && access.grant.status !== 'active' ? (
- <AccessUnavailable
- access={access}
- onRetry={() => void accessQuery.refetch()}
- />
- ) : access && draft ? (
- <div className="space-y-4">
- <fieldset className="grid gap-2 sm:grid-cols-2">
- <legend className="sr-only">Repository policy</legend>
- <label
- className={cn(
- 'hover:border-foreground/20 focus-within:ring-foreground/20 flex min-h-16 min-w-0 cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors focus-within:ring-2 focus-within:ring-offset-2',
- draft.mode === 'all' && 'border-foreground/30 bg-muted/50',
- )}
- >
- <input
- type="radio"
- name={`repository-policy-${agentId}`}
- value="all"
- checked={draft.mode === 'all'}
- onChange={() => setDraft({ mode: 'all' })}
- className="sr-only"
- />
- <span
- aria-hidden
- className={cn(
- 'mt-0.5 grid size-4 place-items-center rounded-full border',
- draft.mode === 'all' &&
- 'border-foreground bg-foreground text-background',
- )}
- >
- {draft.mode === 'all' ? <Check className="size-3" /> : null}
- </span>
- <span className="min-w-0">
- <span className="block text-sm font-medium">
- All granted repositories
- </span>
- <span className="text-muted-foreground mt-0.5 block text-xs">
- Includes repositories added to the installation later.
- </span>
- </span>
- </label>
- <label
- className={cn(
- 'hover:border-foreground/20 focus-within:ring-foreground/20 flex min-h-16 min-w-0 cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors focus-within:ring-2 focus-within:ring-offset-2',
- draft.mode === 'selected' &&
- 'border-foreground/30 bg-muted/50',
- )}
- >
- <input
- type="radio"
- name={`repository-policy-${agentId}`}
- value="selected"
- checked={draft.mode === 'selected'}
- onChange={() =>
- setDraft({
- mode: 'selected',
- repository_ids:
- access.policy.mode === 'selected'
- ? selectedRepositoryIds(access.policy)
- : (access.effective_repositories ?? []).map(
- (repo) => repo.id,
- ),
- })
- }
- className="sr-only"
- />
- <span
- aria-hidden
- className={cn(
- 'mt-0.5 grid size-4 place-items-center rounded-full border',
- draft.mode === 'selected' &&
- 'border-foreground bg-foreground text-background',
- )}
- >
- {draft.mode === 'selected' ? (
- <Check className="size-3" />
- ) : null}
- </span>
- <span className="min-w-0">
- <span className="block text-sm font-medium">
- Only selected repositories
- </span>
- <span className="text-muted-foreground mt-0.5 block text-xs">
- An empty selection disables repository work.
- </span>
- </span>
- </label>
- </fieldset>
-
- {access.grant.truncated ? (
- <div className="border-border bg-muted/40 rounded-md border px-3 py-2 text-xs">
- <p className="font-medium">
- GitHub returned a partial repository list
- </p>
- <p className="text-muted-foreground mt-0.5">
- {access.policy.mode === 'selected'
- ? 'Hidden existing selections are preserved when you save.'
- : 'Switching to selected access limits the agent to repositories you choose from this partial list.'}{' '}
- Configure the GitHub app to see the full grant.
- </p>
- </div>
- ) : null}
-
- {draft.mode === 'selected' ? (
- <div className="space-y-2">
- <div className="relative">
- <Search className="text-muted-foreground pointer-events-none absolute top-1/2 left-2.5 size-3.5 -translate-y-1/2" />
- <Input
- value={search}
- onChange={(event) => setSearch(event.target.value)}
- placeholder="Find a repository"
- aria-label="Find a repository"
- className="h-8 pl-8"
- />
- </div>
- {deployAppQuery.isLoading ? (
- <div
- className="space-y-2"
- aria-label="Loading repository catalog"
- >
- <Skeleton className="h-10 w-full" />
- <Skeleton className="h-10 w-full" />
- </div>
- ) : null}
- {deployAppQuery.isError ? (
- <div className="flex items-center justify-between gap-3 rounded-md border px-3 py-2 text-xs">
- <span className="text-muted-foreground">
- Couldn’t load the full repository list.
- </span>
- <Button
- size="xs"
- variant="ghost"
- onClick={() => void deployAppQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : null}
- {!deployAppQuery.isLoading ? (
- <div className="max-h-64 overflow-y-auto rounded-lg border">
- {visibleCandidates.length ? (
- visibleCandidates.map((repo) => {
- const checked = draft.repository_ids.includes(repo.id)
- const unavailable =
- access.unavailable_selected_repositories.some(
- (item) => item.id === repo.id,
- )
- return (
- <label
- key={repo.id}
- className="hover:bg-muted/40 flex min-w-0 cursor-pointer items-center gap-3 overflow-hidden border-b px-3 py-2.5 last:border-b-0"
- >
- <Checkbox
- checked={checked}
- onCheckedChange={(next) =>
- setDraft(
- toggleSelectedRepository(
- draft,
- repo.id,
- next === true,
- ),
- )
- }
- />
- <GithubMark className="text-muted-foreground size-3.5 shrink-0" />
- <span
- className="min-w-0 flex-1 truncate text-sm"
- title={repo.full_name}
- >
- {repo.full_name}
- </span>
- {unavailable ? (
- <span className="text-muted-foreground shrink-0 text-xs">
- Unavailable
- </span>
- ) : repo.private ? (
- <span className="text-muted-foreground shrink-0 text-xs">
- Private
- </span>
- ) : null}
- </label>
- )
- })
- ) : (
- <p className="text-muted-foreground px-3 py-5 text-center text-sm">
- {candidates.length
- ? 'No repositories match.'
- : deployAppQuery.isError
- ? 'Current selections are unavailable until the repository list reloads.'
- : 'No repositories are available.'}
- </p>
- )}
- </div>
- ) : null}
- {draft.repository_ids.length === 0 ? (
- <p className="text-muted-foreground text-xs">
- Repository work is disabled. This agent can still chat.
- </p>
- ) : null}
- </div>
- ) : null}
- </div>
- ) : null}
- </PanelContent>
- {access?.grant.status === 'active' && draft ? (
- <PanelFooter className="flex-wrap justify-between">
- <div className="min-w-0">
- {access.grant.configure_url ? (
- <a
- href={access.grant.configure_url}
- target="_blank"
- rel="noreferrer"
- className="text-muted-foreground hover:text-foreground inline-flex items-center gap-1 text-xs underline underline-offset-4"
- >
- Configure GitHub app <ArrowUpRight className="size-3" />
- </a>
- ) : null}
- </div>
- <Button
- size="sm"
- className="ml-auto"
- onClick={save}
- disabled={
- saveMutation.isPending ||
- sameRepositoryAccessPolicy(access.policy, draft)
- }
- >
- {saveMutation.isPending ? (
- <LoaderCircle className="animate-spin" />
- ) : null}
- Save access
- </Button>
- </PanelFooter>
- ) : null}
-
- <AlertDialog open={confirming} onOpenChange={setConfirming}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Narrow repository access?</AlertDialogTitle>
- <AlertDialogDescription>
- New checkouts and publishes to removed repositories will be
- blocked. Files already copied into an active session remain in its
- sandbox until that session is archived.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Keep current access</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- setConfirming(false)
- if (draft) saveMutation.mutate(draft)
- }}
- >
- Save narrower access
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </Panel>
- )
-}
-
-export function RepositoryAccessSummary({
- agentId,
- onOpenSettings,
-}: {
- agentId: string
- onOpenSettings: () => void
-}) {
- const accessQuery = useRepositoryAccess(agentId)
- const access = accessQuery.data
- const effective = access?.effective_repositories ?? []
- const selected =
- access?.policy.mode === 'selected'
- ? access.policy.repository_ids.length
- : null
-
- return (
- <Panel>
- <PanelHeader className="border-b-0 pb-2">
- <PanelTitle className="flex items-center gap-2">
- <GithubMark className="size-4" /> GitHub
- </PanelTitle>
- </PanelHeader>
- <PanelContent className="pt-1">
- {accessQuery.isLoading ? (
- <Skeleton className="h-10 w-full" />
- ) : accessQuery.isError ? (
- <button
- className="text-muted-foreground hover:text-foreground text-sm underline"
- onClick={() => void accessQuery.refetch()}
- >
- Couldn’t load access — retry
- </button>
- ) : access?.grant.status !== 'active' ? (
- <p className="text-sm">
- {access?.grant.status === 'unavailable'
- ? 'GitHub access is unavailable.'
- : 'GitHub is not connected.'}
- </p>
- ) : (
- <div className="flex items-start gap-2.5">
- <ShieldCheck className="text-status-running mt-0.5 size-4 shrink-0" />
- <div className="min-w-0">
- <p className="text-sm font-medium">
- {access.policy.mode === 'all'
- ? 'All granted repositories'
- : selected === 0
- ? 'Repository work disabled'
- : `${selected} selected ${selected === 1 ? 'repository' : 'repositories'}`}
- </p>
- {effective[0] ? (
- <p className="text-muted-foreground mt-0.5 truncate text-xs">
- {effective[0].full_name}
- {effective.length > 1 ? ` +${effective.length - 1}` : ''}
- </p>
- ) : null}
- </div>
- </div>
- )}
- <button
- type="button"
- onClick={onOpenSettings}
- className="text-muted-foreground hover:text-foreground mt-3 inline-flex items-center gap-1 text-xs font-medium"
- >
- Manage GitHub <ChevronRight className="size-3" />
- </button>
- </PanelContent>
- </Panel>
- )
-}
-
-export function RepositoryTaskSuggestion({ agentId }: { agentId: string }) {
- const { data } = useRepositoryAccess(agentId)
- const repo = data?.effective_repositories?.[0]
- if (!repo) return null
- return (
- <div className="border-border bg-muted/30 flex items-start gap-3 rounded-lg border px-3 py-2.5">
- <GitPullRequest className="text-muted-foreground mt-0.5 size-4 shrink-0" />
- <div>
- <p className="text-xs font-medium">Try a repository task</p>
- <p className="text-muted-foreground mt-0.5 text-xs">
- In{' '}
- <span className="text-foreground font-mono">{repo.full_name},</span>{' '}
- add a setup note and open a pull request.
- </p>
- </div>
- </div>
- )
-}
diff --git a/web/src/components/runtime-badge.tsx b/web/src/components/runtime-badge.tsx
deleted file mode 100644
index 82dc764b..00000000
--- a/web/src/components/runtime-badge.tsx
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Bot, Cloud, type LucideIcon } from 'lucide-react'
-import { runtimeLabel } from '@/lib/runtimes'
-import { cn } from '@/lib/utils'
-
-// Runtime is a category, not a health state — so it gets a quiet, neutral pill (not a
-// status tone). `flue` (the CF-native durable path) carries a subtle accent + a distinct
-// icon so it reads apart from the brain-box runtimes (claude/codex/pi) at a glance.
-const ICON: Record<string, LucideIcon> = {
- flue: Cloud,
-}
-
-export function RuntimeBadge({
- runtime,
- className,
-}: {
- runtime: string | null | undefined
- className?: string
-}) {
- if (!runtime) return <span className="text-muted-foreground text-sm">—</span>
- const Icon = ICON[runtime] ?? Bot
- const isFlue = runtime === 'flue'
- return (
- <span
- className={cn(
- 'inline-flex items-center gap-1.5 rounded-md px-2 py-0.5 text-xs font-medium',
- isFlue
- ? 'bg-status-running-bg text-status-running'
- : 'bg-secondary text-secondary-foreground',
- className,
- )}
- >
- <Icon className="size-3.5" aria-hidden />
- {runtimeLabel(runtime)}
- </span>
- )
-}
diff --git a/web/src/components/session-conversation.test.tsx b/web/src/components/session-conversation.test.tsx
deleted file mode 100644
index c302de2a..00000000
--- a/web/src/components/session-conversation.test.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import type { SessionEvent } from '@/api/client'
-import { HttpRequestCard, MessageBubble } from './session-conversation'
-
-describe('HttpRequestCard', () => {
- it('renders the attributed payload as structured, escaped JSON', () => {
- const event: SessionEvent = {
- id: 'evt_http',
- seq: 1,
- type: 'http.request',
- level: 'user',
- source: 'http',
- actor: {
- id: 'hk_0123456789abcdef01234567',
- type: 'trigger',
- display: 'grafana-prod',
- },
- body: { payload: { title: '<script>alert(1)</script>', count: 2 } },
- }
-
- const markup = renderToStaticMarkup(
- <HttpRequestCard event={event} seq={event.seq} />,
- )
-
- expect(markup).toContain('grafana-prod')
- expect(markup).toContain('HTTP input')
- expect(markup).toContain('&lt;script&gt;alert(1)&lt;/script&gt;')
- expect(markup).not.toContain('<script>')
- expect(markup).toContain('&quot;count&quot;: 2')
- })
-})
-
-describe('MessageBubble', () => {
- it('sends an out-of-credits agent to the plan picker', () => {
- const markup = renderToStaticMarkup(
- <MemoryRouter>
- <MessageBubble label="Agent" text="Out of credits" outOfCredits />
- </MemoryRouter>,
- )
-
- expect(markup).toContain('href="/billing#plans"')
- expect(markup).toContain('Choose a plan')
- })
-})
diff --git a/web/src/components/session-conversation.tsx b/web/src/components/session-conversation.tsx
deleted file mode 100644
index b121fdc6..00000000
--- a/web/src/components/session-conversation.tsx
+++ /dev/null
@@ -1,230 +0,0 @@
-import type { ReactNode } from 'react'
-import { Link } from 'react-router-dom'
-import { Hourglass } from 'lucide-react'
-import type { SessionEvent } from '@/api/client'
-import { Button } from '@/components/ui/button'
-import { CHOOSE_PLAN_LABEL, upgradeHref } from '@/lib/billing-onramp'
-import {
- bodyText,
- httpRequestPayloadText,
- isOutOfCredits,
- isTerminalSessionStatus,
- isTurnInput,
- type GroupedTimeline,
- type TurnState,
-} from '@/lib/session-turns'
-
-export function HttpRequestCard({
- event,
- seq,
- meta,
-}: {
- event: SessionEvent
- seq?: number
- meta?: ReactNode
-}) {
- return (
- <div>
- <div className="mb-1 flex items-center gap-2">
- <span className="text-foreground text-xs font-semibold">
- {event.actor?.display ?? 'HTTP'}
- </span>
- {seq != null ? (
- <span className="text-muted-foreground/70 font-mono text-[10px]">
- #{seq}
- </span>
- ) : null}
- <span className="text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-[10px] font-medium">
- HTTP input
- </span>
- {meta}
- </div>
- <pre className="bg-panel-2 text-foreground/90 overflow-x-auto rounded-md border p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap">
- {httpRequestPayloadText(event) ?? 'Payload unavailable'}
- </pre>
- </div>
- )
-}
-
-// A single chat bubble (You / Agent). Shared between the grouped Conversation
-// view and the flat All log so both render identical message markup.
-export function MessageBubble({
- label,
- text,
- seq,
- meta,
- outOfCredits,
-}: {
- label: string
- text: string | null
- seq?: number // shown as #seq in the All log; omitted in the chat view
- meta?: ReactNode // trailing tag next to the header (e.g. queued chip)
- outOfCredits?: boolean
-}) {
- return (
- <div>
- <div className="mb-1 flex items-center gap-2">
- <span className="text-foreground text-xs font-semibold">{label}</span>
- {seq != null ? (
- <span className="text-muted-foreground/70 font-mono text-[10px]">
- #{seq}
- </span>
- ) : null}
- {meta}
- </div>
- <p className="text-foreground/90 text-sm whitespace-pre-wrap">{text}</p>
- {outOfCredits ? (
- <Button asChild size="sm" className="mt-2">
- <Link to={upgradeHref()}>{CHOOSE_PLAN_LABEL}</Link>
- </Button>
- ) : null}
- </div>
- )
-}
-
-function TurnStateChip({
- state,
-}: {
- state: Extract<TurnState, 'queued' | 'running'>
-}) {
- return (
- <span className="text-muted-foreground bg-muted inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-[10px] font-medium">
- {state === 'queued' ? (
- <Hourglass className="size-2.5" aria-hidden="true" />
- ) : (
- <span
- className="bg-status-running size-1.5 rounded-full"
- aria-hidden="true"
- />
- )}
- {state === 'queued' ? 'Queued' : 'Working'}
- </span>
- )
-}
-
-// A static operational state, not a theatrical typing animation. It appears
-// only after the durable turn.started boundary and disappears on completion.
-function ReplyIndicator() {
- return (
- <div
- className="flex items-center gap-2 pt-1"
- role="status"
- aria-live="polite"
- >
- <span className="text-foreground/70 text-xs font-semibold">Agent</span>
- <TurnStateChip state="running" />
- </div>
- )
-}
-
-// Grouped chat view: one block per turn (its inputs as "You", its agent.message
-// outputs as "Agent"), an error affordance on failure, and one static working
-// state while the agent still owes a response. Lifecycle
-// chrome (turn.started/turn.completed/agent.result/tool.call) is hidden here.
-// Queued input — typed while a turn was running and not yet claimed by a
-// follow-up turn — trails the groups.
-export function TurnConversation({
- grouped,
- halted = false,
- sessionStatus,
-}: {
- grouped: GroupedTimeline
- halted?: boolean
- sessionStatus?: string
-}) {
- const sessionTerminal = isTerminalSessionStatus(sessionStatus)
-
- return (
- <ul className="divide-y">
- {grouped.groups.map((group) => {
- const errorEv = group.events.find((e) => e.type.startsWith('error'))
- const groupInputs = group.events.filter(isTurnInput)
- const activeInputId = groupInputs[groupInputs.length - 1]?.id
- const runningNoAnswer =
- group.state === 'running' &&
- !group.events.some((event) => event.type === 'agent.message')
- const showActiveState = !halted && !sessionTerminal
- return (
- <li key={group.turnId} className="space-y-3 px-4 py-3">
- {group.events.map((ev) => {
- if (ev.type === 'http.request') {
- return (
- <HttpRequestCard
- key={ev.id}
- event={ev}
- meta={
- showActiveState &&
- ev.id === activeInputId &&
- group.state === 'queued' ? (
- <TurnStateChip state="queued" />
- ) : undefined
- }
- />
- )
- }
- if (ev.type === 'user.message') {
- return (
- <MessageBubble
- key={ev.id}
- label={ev.actor?.display ?? 'You'}
- text={bodyText(ev)}
- meta={
- showActiveState &&
- ev.id === activeInputId &&
- group.state === 'queued' ? (
- <TurnStateChip state="queued" />
- ) : undefined
- }
- />
- )
- }
- if (ev.type === 'agent.message') {
- return (
- <MessageBubble
- key={ev.id}
- label={ev.actor?.display ?? 'Agent'}
- text={bodyText(ev)}
- outOfCredits={isOutOfCredits(ev)}
- />
- )
- }
- return null // hide agent.result / tool.call / error chrome
- })}
- {showActiveState && runningNoAnswer ? <ReplyIndicator /> : null}
- {group.state === 'error' ? (
- <div className="bg-status-error-bg/40 text-status-error rounded-sm px-3 py-2 text-xs">
- {group.errorMessage ??
- (errorEv && bodyText(errorEv)) ??
- 'The agent hit an error on this turn.'}
- </div>
- ) : null}
- </li>
- )
- })}
- {grouped.pending.map((ev) => (
- <li key={ev.id} className="px-4 py-3">
- {ev.type === 'http.request' ? (
- <HttpRequestCard
- event={ev}
- meta={
- !halted && !sessionTerminal ? (
- <TurnStateChip state="queued" />
- ) : undefined
- }
- />
- ) : (
- <MessageBubble
- label={ev.actor?.display ?? 'You'}
- text={bodyText(ev)}
- meta={
- !halted && !sessionTerminal ? (
- <TurnStateChip state="queued" />
- ) : undefined
- }
- />
- )}
- </li>
- ))}
- </ul>
- )
-}
diff --git a/web/src/components/session-turns.tsx b/web/src/components/session-turns.tsx
deleted file mode 100644
index e802957c..00000000
--- a/web/src/components/session-turns.tsx
+++ /dev/null
@@ -1,127 +0,0 @@
-import { useQuery } from '@tanstack/react-query'
-import { getSessionTurns, type Turn } from '@/api/client'
-import { Panel } from '@/components/panel'
-import { StatusBadge } from '@/components/status-badge'
-import { ApiHint } from '@/components/api-hint'
-import {
- formatUsageCost,
- formatUsageTokens,
- usageAttribution,
-} from '@/lib/usage'
-
-// A turn's `error` is an opaque object (or a string); pull a one-line message defensively.
-function errorMessage(error: unknown): string | null {
- if (error == null) return null
- if (typeof error === 'string') return error
- if (typeof error === 'number' || typeof error === 'boolean') {
- return String(error)
- }
- if (typeof error === 'object') {
- const e = error as Record<string, unknown>
- const msg = e.message ?? e.error ?? e.detail
- const code = typeof e.code === 'string' ? e.code : null
- if (typeof msg === 'string') return code ? `${code}: ${msg}` : msg
- if (code) return code
- try {
- return JSON.stringify(error)
- } catch {
- return 'error'
- }
- }
- return 'error'
-}
-
-// Wall-clock duration of a turn: prefer active_seconds (billed compute), else derive
-// from started/completed timestamps. Returns a compact label like "4.2s" / "1m 03s".
-function duration(turn: Turn): string | null {
- let secs: number | null =
- typeof turn.active_seconds === 'number' ? turn.active_seconds : null
- if (secs == null && turn.started_at && turn.completed_at) {
- const ms = Date.parse(turn.completed_at) - Date.parse(turn.started_at)
- if (Number.isFinite(ms) && ms >= 0) secs = ms / 1000
- }
- if (secs == null) return null
- if (secs < 60) return `${secs.toFixed(1)}s`
- const m = Math.floor(secs / 60)
- const s = Math.round(secs % 60)
- return `${m}m ${String(s).padStart(2, '0')}s`
-}
-
-export function SessionTurns({
- sessionId,
- active,
-}: {
- sessionId: string
- active: boolean
-}) {
- const { data: turns, isLoading } = useQuery({
- queryKey: ['session-turns', sessionId],
- queryFn: () => getSessionTurns(sessionId),
- // Keep the health view current while the session is doing work; idle when settled.
- refetchInterval: active ? 5000 : false,
- })
-
- if (!isLoading && (turns?.length ?? 0) === 0) return null // nothing to show for a session with no turns yet
-
- return (
- <Panel className="mt-4 overflow-hidden">
- <div className="flex items-center justify-between border-b px-4 py-2.5">
- <h2 className="text-sm font-semibold">Submission health</h2>
- <ApiHint
- method="GET"
- path="/v3/sessions/:id/turns"
- sdk="oc.sessions.turns()"
- docs="https://docs.opencomputer.dev/agent-sessions/sessions"
- />
- </div>
-
- {isLoading ? (
- <div className="text-muted-foreground px-4 py-3 text-xs">Loading…</div>
- ) : (
- <ul className="divide-y">
- {(turns ?? []).map((t) => {
- const err = t.state === 'error' ? errorMessage(t.error) : null
- const dur = duration(t)
- const tokens = formatUsageTokens(t.usage)
- const cost = formatUsageCost(t.usage)
- const usage =
- tokens === 'Unknown'
- ? 'Usage unknown'
- : `${tokens} tok · ${cost === 'Unknown' ? 'cost unknown' : cost}${
- usageAttribution(t.usage) === 'best_effort'
- ? ' · best-effort'
- : ''
- }`
- return (
- <li key={t.id} className="px-4 py-2.5">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
- <StatusBadge
- status={t.state === 'ok' ? 'success' : t.state}
- label={t.state === 'ok' ? 'OK' : undefined}
- />
- <code className="text-muted-foreground/80 font-mono text-[11px]">
- {t.id}
- </code>
- {t.yield_reason ? (
- <span className="text-muted-foreground text-xs">
- {t.yield_reason.replace(/_/g, ' ')}
- </span>
- ) : null}
- <span className="text-muted-foreground/70 ml-auto flex items-center gap-3 font-mono text-[11px] tabular-nums">
- {dur ? <span title="active compute">{dur}</span> : null}
- <span title="turn usage">{usage}</span>
- </span>
- </div>
- {err ? (
- <p className="text-status-error mt-1 font-mono text-[11px] break-words">
- {err}
- </p>
- ) : null}
- </li>
- )
- })}
- </ul>
- )}
- </Panel>
- )
-}
diff --git a/web/src/components/session-webhooks.tsx b/web/src/components/session-webhooks.tsx
deleted file mode 100644
index 998378d8..00000000
--- a/web/src/components/session-webhooks.tsx
+++ /dev/null
@@ -1,332 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { ChevronRight, Plus, RotateCw, Webhook, X } from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import {
- getDestinations,
- createDestination,
- deleteDestination,
- getDeliveries,
- redeliver,
- type Destination,
- type Delivery,
-} from '@/api/client'
-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, Label } from '@/components/form'
-import { Checkbox } from '@/components/ui/checkbox'
-import { StatusBadge } from '@/components/status-badge'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { cn } from '@/lib/utils'
-
-// Predefined event types a destination can subscribe to (exact + the error.*
-// prefix), from the event taxonomy. Empty selection = deliver every event.
-const EVENT_TYPES = [
- { value: 'turn.completed', label: 'Turn completed' },
- { value: 'turn.started', label: 'Turn started' },
- { value: 'agent.message', label: 'Agent message' },
- { value: 'user.message', label: 'User message' },
- { value: 'tool.call', label: 'Tool call' },
- { value: 'exec.completed', label: 'Command finished' },
- { value: 'error.*', label: 'Errors' },
-]
-
-// Webhooks are session-scoped (a destination is created per session), so
-// they live on the session detail rather than a global page.
-export function SessionWebhooks({ sessionId }: { sessionId: string }) {
- const queryClient = useQueryClient()
- const [showAdd, setShowAdd] = useState(false)
- const [url, setUrl] = useState('')
- const [selectedTypes, setSelectedTypes] = useState<Set<string>>(new Set())
- const [secret, setSecret] = useState('')
- const [toDelete, setToDelete] = useState<Destination | null>(null)
-
- const [expanded, setExpanded] = useState<Set<string>>(new Set())
-
- const toggleType = (v: string) =>
- setSelectedTypes((prev) => {
- const next = new Set(prev)
- if (next.has(v)) next.delete(v)
- else next.add(v)
- return next
- })
- const toggleExpand = (id: string) =>
- setExpanded((prev) => {
- const next = new Set(prev)
- if (next.has(id)) next.delete(id)
- else next.add(id)
- return next
- })
-
- const { data: destinations } = useQuery({
- queryKey: ['destinations', sessionId],
- queryFn: () => getDestinations(sessionId),
- })
- const { data: deliveries } = useQuery({
- queryKey: ['deliveries', sessionId],
- queryFn: () => getDeliveries(sessionId),
- })
-
- const invalidate = () => {
- void queryClient.invalidateQueries({
- queryKey: ['destinations', sessionId],
- })
- void queryClient.invalidateQueries({ queryKey: ['deliveries', sessionId] })
- }
-
- const addMutation = useMutation({
- mutationFn: () =>
- createDestination(sessionId, {
- url: url.trim(),
- types: selectedTypes.size ? Array.from(selectedTypes) : undefined,
- secret: secret.trim() || undefined,
- }),
- onSuccess: () => {
- setShowAdd(false)
- setUrl('')
- setSelectedTypes(new Set())
- setSecret('')
- invalidate()
- },
- onError: (e) => notifyError("Couldn't add the destination.", e),
- })
- const deleteMutation = useMutation({
- mutationFn: (id: string) => deleteDestination(sessionId, id),
- onSettled: invalidate,
- onError: (e) => notifyError("Couldn't delete the destination.", e),
- })
- const redeliverMutation = useMutation({
- mutationFn: (deliveryId: string) => redeliver(sessionId, deliveryId),
- onSettled: () =>
- void queryClient.invalidateQueries({
- queryKey: ['deliveries', sessionId],
- }),
- onError: (e) => notifyError("Couldn't redeliver.", e),
- })
-
- // Deliveries grouped by destination — folded under each so the panel stays
- // clean (delivery.destination is the destination id).
- const byDest = new Map<string, Delivery[]>()
- for (const dl of deliveries ?? []) {
- const k = dl.destination ?? ''
- const list = byDest.get(k) ?? []
- list.push(dl)
- byDest.set(k, list)
- }
-
- return (
- <Panel className="mt-4 overflow-hidden">
- <div className="flex items-center justify-between border-b px-4 py-2.5">
- <h2 className="text-sm font-semibold">Webhooks</h2>
- <Button size="sm" variant="outline" onClick={() => setShowAdd(true)}>
- <Plus className="size-4" />
- Add destination
- </Button>
- </div>
-
- {/* Destinations — each expands to its own deliveries */}
- {(destinations?.length ?? 0) === 0 ? (
- <div className="text-muted-foreground flex items-center gap-2 px-4 py-4 text-sm">
- <Webhook className="size-4 opacity-60" />
- No destinations — add one to deliver this session&apos;s events to
- your endpoint.
- </div>
- ) : (
- <ul className="divide-y">
- {destinations?.map((d) => {
- const dels = byDest.get(d.id) ?? []
- const isOpen = expanded.has(d.id)
- return (
- <li key={d.id}>
- <div className="flex items-center gap-3 px-4 py-2.5">
- <button
- type="button"
- onClick={() => toggleExpand(d.id)}
- aria-expanded={isOpen}
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- >
- <ChevronRight
- className={cn(
- 'size-3.5 shrink-0 opacity-60 transition-transform',
- isOpen && 'rotate-90',
- )}
- />
- <code className="text-foreground min-w-0 flex-1 truncate font-mono text-xs">
- {d.url}
- </code>
- </button>
- <span className="text-muted-foreground hidden text-xs sm:inline">
- {dels.length} sent
- </span>
- <StatusBadge
- status={d.enabled ? 'active' : 'paused'}
- label={d.enabled ? 'Enabled' : 'Paused'}
- />
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label="Delete destination"
- className="text-muted-foreground hover:text-status-error"
- onClick={() => setToDelete(d)}
- >
- <X className="size-4" />
- </Button>
- </div>
-
- {isOpen ? (
- <div className="bg-panel-2/40 border-t px-4 py-2 pl-9">
- {d.types?.length ? (
- <p className="text-muted-foreground mb-1.5 font-mono text-[11px]">
- {d.types.join(', ')}
- </p>
- ) : null}
- {dels.length === 0 ? (
- <p className="text-muted-foreground py-1 text-xs">
- No deliveries yet.
- </p>
- ) : (
- <ul className="divide-border/50 divide-y">
- {dels.map((dl) => (
- <li
- key={dl.id}
- className="flex items-center gap-3 py-1.5 text-xs"
- >
- <span className="text-muted-foreground w-10 shrink-0 font-mono">
- #{dl.event_seq ?? '—'}
- </span>
- <StatusBadge status={dl.status} />
- <span className="text-muted-foreground font-mono">
- {dl.attempts ?? 0}×
- </span>
- <span className="text-muted-foreground font-mono">
- {dl.response_code ?? (dl.error ? 'err' : '—')}
- </span>
- <span className="flex-1" />
- {dl.status === 'failed' ||
- dl.status === 'dead_letter' ? (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => redeliverMutation.mutate(dl.id)}
- disabled={redeliverMutation.isPending}
- >
- <RotateCw className="size-3.5" />
- Redeliver
- </Button>
- ) : null}
- </li>
- ))}
- </ul>
- )}
- </div>
- ) : null}
- </li>
- )
- })}
- </ul>
- )}
-
- {/* Add dialog */}
- <Dialog open={showAdd} onOpenChange={setShowAdd}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Add destination</DialogTitle>
- <DialogDescription>
- Deliver this session&apos;s events to an HTTPS endpoint, signed
- with your secret.
- </DialogDescription>
- </DialogHeader>
- <form
- className="space-y-4"
- onSubmit={(e) => {
- e.preventDefault()
- if (url.trim()) addMutation.mutate()
- }}
- >
- <Field label="Endpoint URL" htmlFor="dst-url">
- <Input
- id="dst-url"
- value={url}
- onChange={(e) => setUrl(e.target.value)}
- placeholder="https://example.com/hooks/oc"
- />
- </Field>
- <div className="space-y-2">
- <Label>Event types</Label>
- <p className="text-muted-foreground text-xs">
- Leave all unchecked to deliver every event.
- </p>
- <div className="grid grid-cols-2 gap-2 pt-0.5">
- {EVENT_TYPES.map((t) => (
- <label
- key={t.value}
- htmlFor={`et-${t.value}`}
- className="flex cursor-pointer items-center gap-2 text-sm"
- >
- <Checkbox
- id={`et-${t.value}`}
- checked={selectedTypes.has(t.value)}
- onCheckedChange={() => toggleType(t.value)}
- />
- {t.label}
- </label>
- ))}
- </div>
- </div>
- <Field
- label="Signing secret"
- htmlFor="dst-secret"
- description="Optional. Write-only — it is never shown again."
- >
- <Input
- id="dst-secret"
- value={secret}
- onChange={(e) => setSecret(e.target.value)}
- placeholder="whsec_…"
- />
- </Field>
- <DialogFooter className="mt-2">
- <Button
- type="button"
- variant="ghost"
- onClick={() => setShowAdd(false)}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={addMutation.isPending || !url.trim()}
- >
- {addMutation.isPending ? 'Adding…' : 'Add destination'}
- </Button>
- </DialogFooter>
- </form>
- </DialogContent>
- </Dialog>
-
- <ConfirmDialog
- open={toDelete !== null}
- onOpenChange={(open) => !open && setToDelete(null)}
- title="Delete this destination?"
- description="Events will stop being delivered to it. This can't be undone."
- confirmLabel="Delete destination"
- destructive
- pending={deleteMutation.isPending}
- onConfirm={() => {
- if (!toDelete) return
- deleteMutation.mutate(toDelete.id, {
- onSuccess: () => setToDelete(null),
- })
- }}
- />
- </Panel>
- )
-}
diff --git a/web/src/components/slack-connect.render.test.tsx b/web/src/components/slack-connect.render.test.tsx
deleted file mode 100644
index 9e053cbf..00000000
--- a/web/src/components/slack-connect.render.test.tsx
+++ /dev/null
@@ -1,158 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import { SlackConnect, SlackConnectionSummary } from './slack-connect'
-import { managedSlackConnectionsQueryKey } from '@/lib/managed-slack-connections'
-
-const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const connectedAgentId = 'agt_bbbbbbbbbbbbbbbbbbbbbbbb'
-
-function renderSlackConnect(
- managed: Record<string, unknown> | null | undefined,
- url = `/agents/${agentId}`,
- connectedAgentName?: string,
- managedConnections: Array<Record<string, unknown>> = [],
-) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- if (managed !== undefined) {
- queryClient.setQueryData(['slack', 'managed', agentId], managed)
- }
- queryClient.setQueryData(['slack', 'byo', agentId], null)
- queryClient.setQueryData(managedSlackConnectionsQueryKey, managedConnections)
- if (connectedAgentName) {
- queryClient.setQueryData(['agent', connectedAgentId], {
- id: connectedAgentId,
- name: connectedAgentName,
- })
- }
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter initialEntries={[url]}>
- <SlackConnect agentId={agentId} agentName="Support triage" />
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-describe('SlackConnect managed states', () => {
- it('waits for authoritative connection state before showing OAuth success', () => {
- const loadingMarkup = renderSlackConnect(
- undefined,
- `/agents/${agentId}?slack=connected`,
- )
- expect(loadingMarkup).not.toContain('Slack connected')
-
- const connectedMarkup = renderSlackConnect(
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- },
- `/agents/${agentId}?slack=connected`,
- )
- expect(connectedMarkup).toContain('Slack connected')
- expect(connectedMarkup).toContain(
- 'OpenComputer will send messages in Acme to Support triage.',
- )
- })
-
- it('preserves disconnected lifecycle truth and offers reconnection', () => {
- const markup = renderSlackConnect({
- mode: 'managed',
- status: 'disconnected',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- })
-
- expect(markup).toContain('no longer receives messages')
- expect(markup).toContain('Connect Slack again')
- })
-
- it('names and links a same-owner workspace conflict', () => {
- const markup = renderSlackConnect(
- null,
- `/agents/${agentId}?slack=workspace_already_connected&connected_agent=${connectedAgentId}`,
- 'Docs writer',
- )
-
- expect(markup).toContain('This workspace sends messages to Docs writer.')
- expect(markup).toContain(`href="/agents/${connectedAgentId}"`)
- expect(markup).toContain('Open connected agent')
- })
-
- it('keeps a cross-owner workspace conflict anonymous', () => {
- const markup = renderSlackConnect(
- null,
- `/agents/${agentId}?slack=workspace_already_connected`,
- )
-
- expect(markup).toContain(
- 'Connect a different workspace or use your own Slack app for this agent.',
- )
- expect(markup).not.toContain('Open connected agent')
- })
-
- it('shows and links an existing workspace claim before OAuth', () => {
- const markup = renderSlackConnect(null, `/agents/${agentId}`, undefined, [
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- agent: { id: connectedAgentId, name: 'Docs writer' },
- },
- ])
-
- expect(markup).toContain('Slack workspaces already in use')
- expect(markup).toContain('Sends messages to Docs writer')
- expect(markup).toContain(`href="/agents/${connectedAgentId}"`)
- expect(markup).toContain('Move here')
- expect(markup).toContain('Connect another workspace')
- })
-})
-
-describe('SlackConnectionSummary', () => {
- it('keeps Overview compact for connected and disconnected agents', () => {
- const renderSummary = (managed: Record<string, unknown> | null) => {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(['slack', 'managed', agentId], managed)
- queryClient.setQueryData(['slack', 'byo', agentId], null)
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter>
- <SlackConnectionSummary
- agentId={agentId}
- onOpenSettings={() => undefined}
- />
- </MemoryRouter>
- </QueryClientProvider>,
- )
- }
-
- const disconnected = renderSummary(null)
- expect(disconnected).toContain('Not connected')
- expect(disconnected).toContain('Connect Slack')
- expect(disconnected).not.toContain('Use your own Slack app')
-
- const connected = renderSummary({
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- })
- expect(connected).toContain('OpenComputer app')
- expect(connected).toContain('Acme')
- expect(connected).toContain('Manage Slack')
- })
-})
diff --git a/web/src/components/slack-connect.test.ts b/web/src/components/slack-connect.test.ts
deleted file mode 100644
index 0cf3b02d..00000000
--- a/web/src/components/slack-connect.test.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { managedSlackNotice } from '@/lib/managed-slack-notice'
-import { managedSlackDisconnectCopy } from '@/lib/managed-slack-connections'
-
-describe('managed Slack OAuth notices', () => {
- it('uses the active connection data for a successful return', () => {
- expect(managedSlackNotice('connected', 'Acme', 'Support triage')).toEqual({
- title: 'Slack connected',
- description: 'OpenComputer will send messages in Acme to Support triage.',
- })
- })
-
- it('keeps provider failures actionable without exposing provider detail', () => {
- expect(
- managedSlackNotice('slack_upstream_unavailable', null, 'Support triage'),
- ).toEqual({
- title: "Slack couldn't complete the connection",
- description: 'Try again in a moment.',
- destructive: true,
- })
- })
-
- it('ignores unknown query values', () => {
- expect(
- managedSlackNotice('provider_message_here', null, 'Agent'),
- ).toBeNull()
- })
-
- it('names a same-owner agent in a workspace conflict', () => {
- expect(
- managedSlackNotice(
- 'workspace_already_connected',
- null,
- 'Support triage',
- 'Docs writer',
- ),
- ).toMatchObject({
- description:
- 'This workspace sends messages to Docs writer. Move it below to connect it to Support triage.',
- })
- })
-
- it('does not suggest an inaccessible agent for a cross-owner conflict', () => {
- expect(
- managedSlackNotice('workspace_already_connected', null, 'Support triage'),
- ).toMatchObject({
- description:
- 'Connect a different workspace or use your own Slack app for this agent.',
- })
- })
-
- it('states the impact before moving a workspace between agents', () => {
- expect(
- managedSlackDisconnectCopy(
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- agent: {
- id: 'agt_bbbbbbbbbbbbbbbbbbbbbbbb',
- name: 'Docs writer',
- },
- },
- 'Support triage',
- ),
- ).toEqual({
- title: 'Disconnect Acme from Docs writer?',
- description:
- 'New Slack messages from Acme will stop going to Docs writer. The agent and its existing sessions stay available, and the OpenComputer app stays installed. After disconnecting, connect Slack again and select this workspace for Support triage.',
- })
- })
-
- it('states the temporary unassigned state for a guided move', () => {
- expect(
- managedSlackDisconnectCopy(
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- agent: {
- id: 'agt_bbbbbbbbbbbbbbbbbbbbbbbb',
- name: 'Docs writer',
- },
- },
- 'Support triage',
- true,
- ),
- ).toEqual({
- title: 'Move Acme to Support triage?',
- description:
- 'OpenComputer will disconnect Acme from Docs writer, then open Slack so you can authorize it for Support triage. If you stop before authorization completes, the app stays installed but does not send messages to an agent.',
- })
- })
-})
diff --git a/web/src/components/slack-connect.tsx b/web/src/components/slack-connect.tsx
deleted file mode 100644
index 17c689c3..00000000
--- a/web/src/components/slack-connect.tsx
+++ /dev/null
@@ -1,886 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useSearchParams } from 'react-router-dom'
-import { Check, Copy, ExternalLink, MessageSquare, X } from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import {
- authorizeManagedSlack,
- disconnectManagedSlack,
- getAgent,
- getManagedSlackConnection,
- getSlackConnection,
- startSlackConnect,
- completeSlackConnect,
- disconnectSlack,
-} from '@/api/client'
-import type { SlackManifestResponse } from '@/api/schemas'
-import {
- Panel,
- PanelContent,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
-import {
- Alert,
- AlertAction,
- AlertDescription,
- AlertTitle,
-} from '@/components/ui/alert'
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogFooter,
- DialogHeader,
- DialogTitle,
-} from '@/components/ui/dialog'
-import { Field, Input } from '@/components/form'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { ManagedSlackWorkspaceClaims } from '@/components/managed-slack-workspace-claims'
-import { useTransientFlag } from '@/lib/use-transient-flag'
-import { cn } from '@/lib/utils'
-import {
- managedSlackNotice,
- managedSlackOAuthPending,
-} from '@/lib/managed-slack-notice'
-import { useManagedSlackConnections } from '@/lib/managed-slack-connections'
-
-// An agent connects its OWN Slack app (BYO, 1:1:1). Connect is a two-step,
-// manifest-route wizard (oc-bg-agents/.agents/design/008-slack-presence.md §2):
-// START returns a manifest the user pastes into Slack's "From a manifest"
-// flow; COMPLETE takes the three values Slack then hands back. No OAuth, no
-// secrets in responses.
-type Step = 'create' | 'details' | 'install' | 'done'
-
-const WIZARD_STEPS = ['Create app', 'Details', 'Install', 'Done']
-
-// Horizontal progress indicator — shows which step we're on; detail for each
-// step is only shown when it's reached (in the body below).
-function WizardSteps({ current }: { current: number }) {
- return (
- <ol className="flex items-center gap-2 pt-2">
- {WIZARD_STEPS.map((label, i) => {
- const done = i < current
- const active = i === current
- return (
- <li
- key={label}
- className="flex min-w-0 items-center gap-2"
- aria-current={active ? 'step' : undefined}
- >
- <span
- className={cn(
- 'flex size-5 shrink-0 items-center justify-center rounded-full text-[11px] font-semibold',
- done || active
- ? 'bg-foreground text-background'
- : 'bg-secondary text-muted-foreground',
- )}
- >
- {done ? <Check className="size-3" aria-hidden /> : i + 1}
- </span>
- <span
- className={cn(
- 'truncate text-xs',
- active
- ? 'text-foreground font-medium'
- : 'text-muted-foreground',
- )}
- >
- {done ? <span className="sr-only">Completed: </span> : null}
- {label}
- </span>
- {i < WIZARD_STEPS.length - 1 ? (
- <span className="bg-border h-px w-4 shrink-0" />
- ) : null}
- </li>
- )
- })}
- </ol>
- )
-}
-
-// Compact one-line progress for the card view (closed wizard): "Step N of 4 · label".
-function CompactSteps({ current }: { current: number }) {
- const n = Math.min(current + 1, WIZARD_STEPS.length)
- return (
- <p className="text-muted-foreground text-xs">
- Step {n} of {WIZARD_STEPS.length} · {WIZARD_STEPS[current] ?? 'Done'}
- </p>
- )
-}
-
-export function SlackConnectionSummary({
- agentId,
- onOpenSettings,
-}: {
- agentId: string
- onOpenSettings: () => void
-}) {
- const managedQuery = useQuery({
- queryKey: ['slack', 'managed', agentId],
- queryFn: () => getManagedSlackConnection(agentId),
- })
- const byoQuery = useQuery({
- queryKey: ['slack', 'byo', agentId],
- queryFn: () => getSlackConnection(agentId),
- })
- const managed = managedQuery.data
- const byo = byoQuery.data
- const managedActive = managed?.status === 'active'
- const byoActive = byo?.status === 'active'
- const loading = managedQuery.isLoading || byoQuery.isLoading
- const unavailable = managedQuery.isError && byoQuery.isError
- const managedWorkspace = managed?.workspace?.name || managed?.workspace?.id
- const byoWorkspace = byo?.account_login || byo?.team_id
-
- let title = 'Not connected'
- let detail = 'Connect the OpenComputer app or use your own Slack app.'
- if (managedActive && byoActive) {
- title = 'Two Slack apps connected'
- detail = [managedWorkspace, byo?.handle ? `@${byo.handle}` : byoWorkspace]
- .filter(Boolean)
- .join(' · ')
- } else if (managedActive) {
- title = 'OpenComputer app'
- detail = managedWorkspace || 'Connected workspace'
- } else if (byoActive) {
- title = byo?.handle ? `@${byo.handle}` : 'Your Slack app'
- detail = byoWorkspace || 'Connected workspace'
- } else if (managed?.status === 'error' || managed?.status === 'revoked') {
- title = 'Authorization required'
- detail = 'Reconnect the OpenComputer app in Settings.'
- }
-
- return (
- <Panel>
- <PanelHeader className="border-b-0 pb-2">
- <PanelTitle className="flex items-center gap-2">
- <MessageSquare className="size-4" /> Slack
- </PanelTitle>
- </PanelHeader>
- <PanelContent className="pt-1">
- {loading ? (
- <Skeleton className="h-10 w-full" />
- ) : unavailable ? (
- <p className="text-muted-foreground text-sm">
- Slack status is unavailable.
- </p>
- ) : (
- <div className="min-w-0">
- <p className="truncate text-sm font-medium">{title}</p>
- <p className="text-muted-foreground mt-0.5 text-xs leading-relaxed">
- {detail}
- </p>
- </div>
- )}
- <Button
- type="button"
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground mt-2 -ml-3"
- onClick={onOpenSettings}
- >
- {managedActive || byoActive ? 'Manage Slack' : 'Connect Slack'}
- </Button>
- </PanelContent>
- </Panel>
- )
-}
-
-export function SlackConnect({
- agentId,
- agentName,
- canOpenSlack = true,
-}: {
- agentId: string
- agentName: string
- canOpenSlack?: boolean
-}) {
- const queryClient = useQueryClient()
- const [searchParams, setSearchParams] = useSearchParams()
- const oauthResult = searchParams.get('slack')
- const invalidateByo = () =>
- queryClient.invalidateQueries({ queryKey: ['slack', 'byo', agentId] })
- const invalidateManaged = () =>
- queryClient.invalidateQueries({ queryKey: ['slack', 'managed', agentId] })
-
- const {
- data: conn,
- isLoading,
- isError,
- } = useQuery({
- queryKey: ['slack', 'byo', agentId],
- queryFn: () => getSlackConnection(agentId),
- })
- const managedQuery = useQuery({
- queryKey: ['slack', 'managed', agentId],
- queryFn: () => getManagedSlackConnection(agentId),
- refetchInterval: (query) =>
- managedSlackOAuthPending(
- oauthResult,
- query.state.data?.status,
- query.state.data?.connected_at,
- )
- ? 1000
- : false,
- })
- const managedConnectionsQuery = useManagedSlackConnections(!!agentId)
-
- // Wizard state.
- const [open, setOpen] = useState(false)
- const [step, setStep] = useState<Step>('create')
- const [manifest, setManifest] = useState<SlackManifestResponse | null>(null)
- const [appId, setAppId] = useState('')
- const [botToken, setBotToken] = useState('')
- const [signingSecret, setSigningSecret] = useState('')
- const [confirmDisconnect, setConfirmDisconnect] = useState(false)
- const [confirmManagedDisconnect, setConfirmManagedDisconnect] =
- useState(false)
- const [copied, markCopied] = useTransientFlag(1500)
-
- const resetWizard = () => {
- setStep('create')
- setManifest(null)
- setAppId('')
- setBotToken('')
- setSigningSecret('')
- }
-
- const startMutation = useMutation({
- mutationFn: (reconnect: boolean) => startSlackConnect(agentId, reconnect),
- onSuccess: (m) => {
- setManifest(m)
- setStep('create')
- void invalidateByo() // the row is now pending
- },
- onError: (e) => notifyError("Couldn't start the Slack connection.", e),
- })
-
- const completeMutation = useMutation({
- mutationFn: () =>
- completeSlackConnect(agentId, {
- app_id: appId.trim(),
- bot_token: botToken.trim(),
- signing_secret: signingSecret.trim(),
- }),
- onSuccess: () => {
- void invalidateByo()
- setStep('done')
- setAppId('')
- setBotToken('')
- setSigningSecret('') // don't keep secrets in state past a successful connect
- },
- onError: (e) =>
- notifyError('Slack rejected those values. Double-check them.', e),
- })
-
- const disconnectMutation = useMutation({
- mutationFn: () => disconnectSlack(agentId),
- onSuccess: () => {
- void invalidateByo()
- setConfirmDisconnect(false)
- },
- onError: (e) => notifyError("Couldn't disconnect Slack.", e),
- })
-
- const authorizeManagedMutation = useMutation({
- mutationFn: () => authorizeManagedSlack(agentId),
- onSuccess: (result) => {
- if ('authorize_url' in result) {
- window.location.assign(result.authorize_url)
- return
- }
- void invalidateManaged()
- },
- onError: (error) =>
- notifyError("Couldn't start the Slack connection.", error),
- })
-
- const disconnectManagedMutation = useMutation({
- mutationFn: () => disconnectManagedSlack(agentId),
- onSuccess: () => {
- void invalidateManaged()
- setConfirmManagedDisconnect(false)
- },
- onError: (error) =>
- notifyError("Couldn't disconnect OpenComputer Slack.", error),
- })
-
- const beginConnect = (reconnect = false) => {
- resetWizard()
- setOpen(true)
- startMutation.mutate(reconnect)
- }
-
- const copyManifest = () => {
- if (!manifest) return
- void navigator.clipboard
- .writeText(JSON.stringify(manifest.manifest, null, 2))
- .then(
- () => markCopied(),
- (e: unknown) => notifyError("Couldn't copy the manifest.", e),
- )
- }
-
- const status = conn?.status
- const isActive = status === 'active'
- const isPending = status === 'pending'
- const isErrorStatus = status === 'error'
- const workspace = conn?.account_login || conn?.team_id || null
- const managed = managedQuery.data
- const managedActive = managed?.status === 'active'
- const managedNeedsReconnect =
- managed?.status === 'error' || managed?.status === 'revoked'
- const managedDisconnected = managed?.status === 'disconnected'
- const managedWorkspace = managed?.workspace?.name || managed?.workspace?.id
- const hasOtherManagedConnections =
- managedConnectionsQuery.data?.some(
- (connection) => connection.agent.id !== agentId,
- ) ?? false
- const checkingManagedConnections =
- !managedActive &&
- !managedNeedsReconnect &&
- !managedDisconnected &&
- managedConnectionsQuery.isLoading
- const connectedAgentId = searchParams.get('connected_agent')
- const sameOwnerConnectedAgentId =
- oauthResult === 'workspace_already_connected' &&
- connectedAgentId &&
- /^agt_[0-9a-f]{24}$/.test(connectedAgentId)
- ? connectedAgentId
- : null
- const connectedAgentQuery = useQuery({
- queryKey: ['agent', sameOwnerConnectedAgentId],
- queryFn: () => getAgent(sameOwnerConnectedAgentId!),
- enabled: !!sameOwnerConnectedAgentId,
- })
- const connectedAgentName = connectedAgentQuery.data?.name ?? null
- const waitingForConnectedState = managedSlackOAuthPending(
- oauthResult,
- managed?.status,
- managed?.connected_at,
- )
- const notice =
- (sameOwnerConnectedAgentId && connectedAgentQuery.isLoading) ||
- waitingForConnectedState
- ? null
- : managedSlackNotice(
- oauthResult,
- managedWorkspace,
- agentName,
- connectedAgentName,
- managed?.status,
- )
- const connectedAgentHref =
- connectedAgentQuery.data && sameOwnerConnectedAgentId
- ? `/agents/${encodeURIComponent(sameOwnerConnectedAgentId)}`
- : null
- const dismissNotice = () => {
- const next = new URLSearchParams(searchParams)
- next.delete('slack')
- next.delete('connected_agent')
- setSearchParams(next, { replace: true })
- }
- const stepIndex =
- step === 'create' ? 0 : step === 'details' ? 1 : step === 'install' ? 2 : 3
-
- return (
- <Panel className="overflow-hidden">
- <PanelContent className="space-y-4">
- <div className="text-muted-foreground text-xs font-medium">Slack</div>
-
- {notice ? (
- <Alert variant={notice.destructive ? 'destructive' : 'default'}>
- <AlertTitle>{notice.title}</AlertTitle>
- {notice.description || connectedAgentHref ? (
- <AlertDescription>
- {notice.description}{' '}
- {connectedAgentHref ? (
- <Link to={connectedAgentHref}>Open connected agent</Link>
- ) : null}
- </AlertDescription>
- ) : null}
- <AlertAction>
- <Button
- variant="ghost"
- size="icon-sm"
- aria-label="Dismiss Slack notice"
- onClick={dismissNotice}
- >
- <X aria-hidden />
- </Button>
- </AlertAction>
- </Alert>
- ) : null}
-
- <section className="space-y-3" aria-labelledby="managed-slack-title">
- <div className="space-y-1">
- <h3 id="managed-slack-title" className="text-sm font-medium">
- OpenComputer app
- </h3>
- {!managedActive && !managedDisconnected ? (
- <p className="text-muted-foreground text-xs leading-relaxed">
- Connect the shared app to try this agent in Slack.
- </p>
- ) : null}
- </div>
-
- {managedQuery.isLoading ? (
- <div className="space-y-2" aria-label="Checking Slack connection">
- <Skeleton className="h-4 w-40" />
- <Skeleton className="h-7 w-32" />
- </div>
- ) : managedQuery.isError ? (
- <div className="flex flex-wrap items-center justify-between gap-2">
- <p className="text-muted-foreground text-xs">
- Managed Slack status is unavailable.
- </p>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => void managedQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : managedActive ? (
- <div className="space-y-2">
- <div className="flex min-w-0 items-center gap-2 text-sm">
- <span
- className="bg-status-running size-2 shrink-0 rounded-full"
- aria-hidden
- />
- <span className="sr-only">Connected.</span>
- <span className="truncate">
- OpenComputer
- {managedWorkspace ? (
- <span className="text-muted-foreground">
- {' '}
- · {managedWorkspace}
- </span>
- ) : null}
- </span>
- </div>
- {!canOpenSlack ? (
- <p className="text-muted-foreground text-xs">
- Connected. Deploy this agent before opening Slack.
- </p>
- ) : null}
- <div className="flex flex-wrap items-center gap-2">
- {canOpenSlack && managed?.open_url ? (
- <Button asChild size="sm">
- <a href={managed.open_url} target="_blank" rel="noreferrer">
- Open Slack
- <ExternalLink aria-hidden />
- </a>
- </Button>
- ) : null}
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground"
- onClick={() => setConfirmManagedDisconnect(true)}
- >
- Disconnect
- </Button>
- </div>
- </div>
- ) : managedNeedsReconnect ? (
- <div className="space-y-2">
- <p className="text-status-error text-sm">
- The OpenComputer app needs authorization.
- </p>
- <Button
- size="sm"
- onClick={() => authorizeManagedMutation.mutate()}
- disabled={authorizeManagedMutation.isPending}
- >
- {authorizeManagedMutation.isPending
- ? 'Connecting…'
- : 'Reconnect Slack'}
- </Button>
- </div>
- ) : managedDisconnected ? (
- <div className="space-y-3">
- <p className="text-muted-foreground text-xs leading-relaxed">
- Disconnected. This agent no longer receives messages from the
- OpenComputer app.
- </p>
- <p className="text-muted-foreground text-xs leading-relaxed">
- Anyone in this Slack workspace who can message the app can use
- this agent after you reconnect it.
- </p>
- <Button
- size="sm"
- onClick={() => authorizeManagedMutation.mutate()}
- disabled={authorizeManagedMutation.isPending}
- >
- {authorizeManagedMutation.isPending
- ? 'Connecting…'
- : 'Connect Slack again'}
- </Button>
- </div>
- ) : (
- <div className="space-y-3">
- <p className="text-muted-foreground text-xs leading-relaxed">
- Anyone in this Slack workspace who can message the app can use
- this agent.
- </p>
- <ManagedSlackWorkspaceClaims
- currentAgentId={agentId}
- currentAgentName={agentName}
- query={managedConnectionsQuery}
- onMoveHere={() => authorizeManagedMutation.mutate()}
- />
- <Button
- size="sm"
- onClick={() => authorizeManagedMutation.mutate()}
- disabled={
- authorizeManagedMutation.isPending ||
- checkingManagedConnections
- }
- >
- {checkingManagedConnections
- ? 'Checking Slack…'
- : authorizeManagedMutation.isPending
- ? 'Connecting…'
- : hasOtherManagedConnections
- ? 'Connect another workspace'
- : 'Connect OpenComputer Slack'}
- </Button>
- </div>
- )}
- </section>
-
- <section
- className="space-y-2 border-t pt-3"
- aria-labelledby="byo-slack-title"
- >
- <h3 id="byo-slack-title" className="text-sm font-medium">
- Your app
- </h3>
- {managedActive && isActive ? (
- <p className="text-muted-foreground text-xs leading-relaxed">
- Your app is active. Disconnect the OpenComputer app when the
- handoff is complete.
- </p>
- ) : null}
- {isLoading ? (
- <Skeleton
- className="h-7 w-28"
- aria-label="Checking your Slack app"
- />
- ) : isError ? (
- <p className="text-muted-foreground text-xs">
- Your Slack app status is unavailable.
- </p>
- ) : isActive ? (
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span className="min-w-0 truncate text-sm">
- <span className="text-status-running" aria-hidden>
- ●
- </span>{' '}
- <span className="sr-only">Connected.</span>
- <span className="text-foreground font-medium">
- @{conn?.handle}
- </span>
- {workspace ? (
- <span className="text-muted-foreground"> · {workspace}</span>
- ) : null}
- </span>
- <div className="flex items-center gap-1">
- {canOpenSlack && conn?.open_url ? (
- <Button asChild variant="outline" size="sm">
- <a href={conn.open_url} target="_blank" rel="noreferrer">
- Open Slack
- <ExternalLink aria-hidden />
- </a>
- </Button>
- ) : null}
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-foreground"
- onClick={() => setConfirmDisconnect(true)}
- >
- Disconnect
- </Button>
- </div>
- </div>
- ) : isErrorStatus ? (
- <div className="flex flex-wrap items-center justify-between gap-2">
- <span className="text-status-error text-sm">
- Connection error
- </span>
- <Button
- variant="outline"
- size="sm"
- onClick={() => beginConnect()}
- >
- Reconnect your app
- </Button>
- </div>
- ) : isPending ? (
- <div className="space-y-2">
- <CompactSteps current={stepIndex} />
- <Button
- variant="outline"
- size="sm"
- onClick={() => beginConnect()}
- >
- Continue app setup
- </Button>
- </div>
- ) : (
- <Button
- variant="link"
- size="sm"
- className="h-auto px-0"
- onClick={() => beginConnect()}
- >
- Use your own Slack app
- </Button>
- )}
- </section>
- </PanelContent>
-
- {/* Connect wizard */}
- <Dialog
- open={open}
- onOpenChange={(o) => {
- setOpen(o)
- if (!o) resetWizard()
- }}
- >
- <DialogContent className="sm:max-w-2xl">
- <DialogHeader>
- <DialogTitle>
- {step === 'done'
- ? 'Your Slack app is connected'
- : 'Connect your own Slack app'}
- </DialogTitle>
- <DialogDescription className="sr-only">
- Connect a Slack app you operate so members can message this agent.
- </DialogDescription>
- <WizardSteps current={stepIndex} />
- </DialogHeader>
-
- {step === 'create' ? (
- <div className="min-w-0 space-y-4">
- {startMutation.isPending || !manifest ? (
- <p className="text-muted-foreground text-sm">
- Preparing the manifest…
- </p>
- ) : (
- <>
- {/* Linear flow: read → Copy → Open Slack. The action row sits
- right under the explainer (Copy before the link), with the
- manifest below as reference. */}
- <p className="text-muted-foreground text-sm">
- Copy this manifest, then create the app from it in Slack.
- </p>
- <div className="flex flex-wrap items-center gap-3">
- <Button variant="outline" size="sm" onClick={copyManifest}>
- {copied ? (
- <Check className="size-3.5" />
- ) : (
- <Copy className="size-3.5" />
- )}
- {/* Reserve the wider label's width (stacked grid) so the
- button — and the link beside it — don't shift when it
- flips to "Copied". */}
- <span className="grid">
- <span className="invisible col-start-1 row-start-1">
- Copy manifest
- </span>
- <span className="col-start-1 row-start-1 text-left">
- {copied ? 'Copied' : 'Copy manifest'}
- </span>
- </span>
- </Button>
- <a
- href={manifest.create_url}
- target="_blank"
- rel="noreferrer"
- className="text-foreground inline-flex items-center gap-1.5 text-sm underline underline-offset-4"
- >
- Open Slack apps
- <ExternalLink className="size-3.5" />
- </a>
- </div>
- <pre className="bg-panel-2 max-h-60 min-w-0 overflow-y-auto rounded-md border p-3 font-mono text-xs [overflow-wrap:anywhere] whitespace-pre-wrap">
- {JSON.stringify(manifest.manifest, null, 2)}
- </pre>
- </>
- )}
- <DialogFooter>
- <Button
- variant="ghost"
- onClick={() => {
- setOpen(false)
- resetWizard()
- }}
- >
- Cancel
- </Button>
- <Button
- onClick={() => setStep('details')}
- disabled={!manifest || startMutation.isPending}
- >
- Next: app details
- </Button>
- </DialogFooter>
- </div>
- ) : step === 'details' ? (
- <form
- className="min-w-0 space-y-4"
- onSubmit={(e) => {
- e.preventDefault()
- if (appId.trim() && signingSecret.trim()) setStep('install')
- }}
- >
- <p className="text-muted-foreground text-sm">
- From Basic Information → App Credentials, copy these two.
- </p>
- <Field
- label="App ID"
- htmlFor="slack-app-id"
- description="Top of the App Credentials section."
- >
- <Input
- id="slack-app-id"
- value={appId}
- onChange={(e) => setAppId(e.target.value)}
- placeholder="A01234ABCDE"
- />
- </Field>
- <Field
- label="Signing Secret"
- htmlFor="slack-signing-secret"
- description="Same section, under Client Secret."
- >
- <Input
- id="slack-signing-secret"
- type="password"
- value={signingSecret}
- onChange={(e) => setSigningSecret(e.target.value)}
- placeholder="••••••••"
- />
- </Field>
- <DialogFooter>
- <Button
- type="button"
- variant="ghost"
- onClick={() => setStep('create')}
- >
- Back
- </Button>
- <Button
- type="submit"
- disabled={!appId.trim() || !signingSecret.trim()}
- >
- Next: install
- </Button>
- </DialogFooter>
- </form>
- ) : step === 'install' ? (
- <form
- className="min-w-0 space-y-4"
- onSubmit={(e) => {
- e.preventDefault()
- completeMutation.mutate()
- }}
- >
- <p className="text-muted-foreground text-sm">
- In the sidebar, open Install App → Install to Workspace to get
- the token.
- </p>
- <Field
- label="Bot User OAuth Token"
- htmlFor="slack-bot-token"
- description="Install App → Bot User OAuth Token (starts with xoxb-)."
- >
- <Input
- id="slack-bot-token"
- type="password"
- value={botToken}
- onChange={(e) => setBotToken(e.target.value)}
- placeholder="xoxb-…"
- />
- </Field>
- <DialogFooter>
- <Button
- type="button"
- variant="ghost"
- onClick={() => setStep('details')}
- >
- Back
- </Button>
- <Button
- type="submit"
- disabled={
- completeMutation.isPending ||
- !appId.trim() ||
- !signingSecret.trim() ||
- !botToken.trim()
- }
- >
- {completeMutation.isPending ? 'Connecting…' : 'Connect'}
- </Button>
- </DialogFooter>
- </form>
- ) : (
- <div className="min-w-0 space-y-4">
- <div className="space-y-2 text-sm">
- <p>
- <span className="text-foreground font-medium">
- @{conn?.handle ?? agentName}
- </span>{' '}
- is connected{workspace ? ` to ${workspace}` : ''}.
- </p>
- <p className="text-muted-foreground">
- Invite the bot to a channel, then @-mention it to start a
- session.
- </p>
- </div>
- <DialogFooter>
- <Button
- onClick={() => {
- setOpen(false)
- resetWizard()
- }}
- >
- Done
- </Button>
- </DialogFooter>
- </div>
- )}
- </DialogContent>
- </Dialog>
-
- <ConfirmDialog
- open={confirmDisconnect}
- onOpenChange={setConfirmDisconnect}
- title="Disconnect Slack?"
- description="The agent’s Slack app stops working until reconnected. Its bot token and signing secret are purged."
- confirmLabel="Disconnect"
- destructive
- pending={disconnectMutation.isPending}
- onConfirm={() => disconnectMutation.mutate()}
- />
-
- <ConfirmDialog
- open={confirmManagedDisconnect}
- onOpenChange={setConfirmManagedDisconnect}
- title="Disconnect OpenComputer Slack?"
- description="This agent will stop receiving messages from the OpenComputer app. The app stays installed in the workspace."
- confirmLabel="Disconnect"
- destructive
- pending={disconnectManagedMutation.isPending}
- onConfirm={() => disconnectManagedMutation.mutate()}
- />
- </Panel>
- )
-}
diff --git a/web/src/components/source-profile-changed-recovery.test.ts b/web/src/components/source-profile-changed-recovery.test.ts
deleted file mode 100644
index 3f61cb35..00000000
--- a/web/src/components/source-profile-changed-recovery.test.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { createElement } from 'react'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { describe, expect, it } from 'vitest'
-import { SourceProfileChangedRecovery } from '@/components/source-profile-changed-recovery'
-import { sourceChangesUrl } from '@/lib/source-profile-recovery'
-
-describe('source profile change recovery', () => {
- it('links only a bounded GitHub repository and exact commit', () => {
- expect(
- sourceChangesUrl({
- full_name: 'example/support agent',
- latest_seen_sha: 'a'.repeat(40),
- }),
- ).toBe(
- `https://github.com/example/support%20agent/commit/${'a'.repeat(40)}`,
- )
- expect(
- sourceChangesUrl({
- full_name: 'not/a/repository',
- latest_seen_sha: 'a'.repeat(40),
- }),
- ).toBeUndefined()
- expect(
- sourceChangesUrl({
- full_name: 'example/support',
- latest_seen_sha: 'branch-name',
- }),
- ).toBe('https://github.com/example/support')
- })
-
- it('renders the durable restore-or-unlink contract', () => {
- const html = renderToStaticMarkup(
- createElement(SourceProfileChangedRecovery, {
- source: {
- agent_id: 'agt_test',
- repo_id: 'repo_0123456789abcdef01234567',
- path: 'agents/support',
- production_ref: 'main',
- status: 'source_profile_changed',
- latest_seen_sha: 'a'.repeat(40),
- active_deployed_sha: 'b'.repeat(40),
- full_name: 'example/support',
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- review_fingerprint: `sha256:${'c'.repeat(64)}`,
- },
- pending: false,
- onUnlink: () => {},
- }),
- )
-
- expect(html).toContain(
- 'This repository no longer matches the agent type it was imported as',
- )
- expect(html).toContain(
- 'its current active revision and sessions remain available.',
- )
- expect(html).toContain('View source changes')
- expect(html).toContain('Unlink source')
- })
-})
diff --git a/web/src/components/source-profile-changed-recovery.tsx b/web/src/components/source-profile-changed-recovery.tsx
deleted file mode 100644
index bbeb4522..00000000
--- a/web/src/components/source-profile-changed-recovery.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { useState } from 'react'
-import { ExternalLink, Unplug } from 'lucide-react'
-import type { DeploymentSource } from '@/api/schemas'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
-import { Button } from '@/components/ui/button'
-import { sourceChangesUrl } from '@/lib/source-profile-recovery'
-
-/**
- * Recovery for a pinned repository whose current source is no longer the
- * profile it was imported as. Unlinking stops push-to-deploy; it does not
- * convert or delete the agent, its active revision, or its sessions.
- */
-export function SourceProfileChangedRecovery({
- source,
- pending,
- onUnlink,
-}: {
- source: DeploymentSource
- pending: boolean
- onUnlink: () => void
-}) {
- const [confirming, setConfirming] = useState(false)
- const changesUrl = sourceChangesUrl(source)
-
- return (
- <>
- <Alert variant="destructive">
- <AlertTitle>
- This repository no longer matches the agent type it was imported as
- </AlertTitle>
- <AlertDescription>
- Restore the Flue agent definition, or unlink this source and import
- the repository as a new agent. Unlinking does not convert or delete
- this agent; its current active revision and sessions remain available.
- </AlertDescription>
- <div className="mt-3 flex flex-wrap gap-2">
- {changesUrl ? (
- <Button size="sm" variant="outline" asChild>
- <a href={changesUrl} target="_blank" rel="noreferrer">
- View source changes
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- ) : null}
- <Button
- size="sm"
- variant="outline"
- disabled={pending}
- onClick={() => setConfirming(true)}
- >
- <Unplug className="size-4" />
- Unlink source
- </Button>
- </div>
- </Alert>
- <ConfirmDialog
- open={confirming}
- onOpenChange={setConfirming}
- title="Unlink this repository?"
- description="Push-to-deploy will stop. The existing agent, its active revision, and its sessions will remain available."
- confirmLabel="Unlink source"
- destructive
- pending={pending}
- onConfirm={onUnlink}
- />
- </>
- )
-}
diff --git a/web/src/components/working-repo-field-state.test.tsx b/web/src/components/working-repo-field-state.test.tsx
deleted file mode 100644
index 4330550a..00000000
--- a/web/src/components/working-repo-field-state.test.tsx
+++ /dev/null
@@ -1,134 +0,0 @@
-// @vitest-environment happy-dom
-
-import { act } from 'react'
-import { createRoot, type Root } from 'react-dom/client'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import type { RepositoryAccess } from '@/api/client'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-import { WorkingRepoField, type WorkingRepo } from './working-repo-field'
-
-const agentA = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const agentB = 'agt_bbbbbbbbbbbbbbbbbbbbbbbb'
-const value: WorkingRepo = {
- repo: 'repo_1',
- fullName: 'acme/app',
- ref: 'main',
-}
-
-function access(
- repositories: RepositoryAccess['effective_repositories'],
- truncated = false,
-): RepositoryAccess {
- return {
- policy: { mode: 'all' },
- grant: {
- status: repositories === null ? 'unavailable' : 'active',
- account: 'acme',
- repository_selection: 'all',
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- truncated,
- },
- effective_repositories: repositories,
- unavailable_selected_repositories: [],
- }
-}
-
-const repository = {
- id: 'repo_1',
- full_name: 'acme/app',
- default_branch: 'main',
- private: true,
-}
-
-describe('WorkingRepoField selection validity', () => {
- let container: HTMLDivElement
- let root: Root
- let client: QueryClient
-
- beforeEach(() => {
- ;(
- globalThis as typeof globalThis & {
- IS_REACT_ACT_ENVIRONMENT: boolean
- }
- ).IS_REACT_ACT_ENVIRONMENT = true
- container = document.createElement('div')
- document.body.append(container)
- root = createRoot(container)
- client = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- client.setQueryData(repositoryAccessQueryKey(agentA), access([repository]))
- client.setQueryData(repositoryAccessQueryKey(agentB), access([repository]))
- })
-
- afterEach(() => {
- act(() => root.unmount())
- client.clear()
- container.remove()
- })
-
- function renderField(
- agentId: string,
- onChange: (next: WorkingRepo | null) => void,
- ) {
- act(() => {
- root.render(
- <QueryClientProvider client={client}>
- <WorkingRepoField
- agentId={agentId}
- runtime="flue"
- value={value}
- onChange={onChange}
- />
- </QueryClientProvider>,
- )
- })
- }
-
- it('clears a selection immediately when the agent scope changes', () => {
- const onChange = vi.fn()
- renderField(agentA, onChange)
- expect(onChange).not.toHaveBeenCalled()
-
- renderField(agentB, onChange)
- expect(onChange).toHaveBeenCalledWith(null)
- })
-
- it('clears a selection removed from the loaded effective policy', () => {
- const onChange = vi.fn()
- renderField(agentA, onChange)
-
- act(() => {
- client.setQueryData(repositoryAccessQueryKey(agentA), access([]))
- })
- renderField(agentA, onChange)
-
- expect(onChange).toHaveBeenCalledWith(null)
- })
-
- it('keeps the selection when an unavailable grant makes the set unknown', () => {
- const onChange = vi.fn()
- renderField(agentA, onChange)
-
- act(() => {
- client.setQueryData(repositoryAccessQueryKey(agentA), access(null))
- })
- renderField(agentA, onChange)
-
- expect(onChange).not.toHaveBeenCalled()
- })
-
- it('keeps the selection when a truncated grant makes absence ambiguous', () => {
- const onChange = vi.fn()
- renderField(agentA, onChange)
-
- act(() => {
- client.setQueryData(repositoryAccessQueryKey(agentA), access([], true))
- })
- renderField(agentA, onChange)
-
- expect(onChange).not.toHaveBeenCalled()
- })
-})
diff --git a/web/src/components/working-repo-field.test.ts b/web/src/components/working-repo-field.test.ts
deleted file mode 100644
index ba2afc67..00000000
--- a/web/src/components/working-repo-field.test.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { selectedWorkingRepo } from '@/lib/working-repo'
-
-describe('working repository selection', () => {
- const repo = {
- id: 'repo_123',
- full_name: 'acme/renamed-app',
- default_branch: 'trunk',
- }
-
- it('submits stable repository identity for Flue and keeps the slug for display', () => {
- expect(selectedWorkingRepo(repo, true, null)).toEqual({
- repo: 'repo_123',
- fullName: 'acme/renamed-app',
- ref: 'trunk',
- })
- })
-
- it('preserves legacy slug behavior for non-Flue agents', () => {
- expect(selectedWorkingRepo(repo, false, null)).toEqual({
- repo: 'acme/renamed-app',
- ref: 'trunk',
- })
- })
-
- it('keeps an explicitly edited branch when the same repository is reselected', () => {
- expect(
- selectedWorkingRepo(repo, true, {
- repo: 'repo_123',
- fullName: 'acme/renamed-app',
- ref: 'feature/test',
- }),
- ).toMatchObject({ ref: 'feature/test' })
- })
-})
diff --git a/web/src/components/working-repo-field.tsx b/web/src/components/working-repo-field.tsx
deleted file mode 100644
index 2209406d..00000000
--- a/web/src/components/working-repo-field.tsx
+++ /dev/null
@@ -1,261 +0,0 @@
-import { useEffect, useMemo, useRef } from 'react'
-import { useQuery } from '@tanstack/react-query'
-import { Select as SelectPrimitive } from 'radix-ui'
-import { Check, ChevronDown, GitBranch, X } from 'lucide-react'
-import { getDeployApp, getRepositoryAccess } from '@/api/client'
-import { GithubMark } from '@/components/github-mark'
-import { markFloatingLayerPointerDismiss } from '@/components/ui/floating-layer'
-import { cn } from '@/lib/utils'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-import {
- selectedWorkingRepo,
- workingRepoValue,
- type WorkingRepoValue,
-} from '@/lib/working-repo'
-
-// The WORKING repo a session checks out and opens PRs from (design 010 §2). Deliberately SEPARATE
-// from the agent's config/"connected" repo (prompt + skills) — an agent is typically configured
-// from one repo and works across others, so this never defaults to the connected repo. Optional:
-// a session starts fine with none; when set, the agent can publish PRs.
-
-export interface WorkingRepo extends WorkingRepoValue {
- repo: string // stable repo_ id for Flue; "owner/repo" for legacy runtimes
- fullName?: string // display coordinate when repo is a stable id
- ref: string // branch
-}
-
-function splitRepo(full: string): [owner: string, name: string] {
- const i = full.indexOf('/')
- return i === -1 ? ['', full] : [full.slice(0, i), full.slice(i + 1)]
-}
-
-/**
- * Inline, secondary working-repo control for the session composer. A compact, GitHub-marked
- * dropdown — unselected by default (short "Working repo" placeholder); starting a session works
- * empty. Selecting a repo reveals a branch pill (prefilled with the repo's default branch) and a
- * clear (✕). Flue reads the agent's effective repository policy; legacy runtimes retain the
- * installation-wide getDeployApp list. Custom-styled on the Radix primitive (no new dependency)
- * so it reads as a deliberate control, not stock.
- */
-export function WorkingRepoField({
- agentId,
- runtime,
- value,
- onChange,
-}: {
- agentId?: string
- runtime?: string | null
- value: WorkingRepo | null
- onChange: (v: WorkingRepo | null) => void
-}) {
- const useFluePolicy = runtime === 'flue' && Boolean(agentId)
- const {
- data: app,
- isLoading: appLoading,
- isError: appError,
- isSuccess: appSuccess,
- refetch: refetchApp,
- } = useQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- enabled: !useFluePolicy,
- staleTime: 30_000,
- })
- const {
- data: access,
- isLoading: accessLoading,
- isError: accessError,
- isSuccess: accessSuccess,
- refetch: refetchAccess,
- } = useQuery({
- queryKey: repositoryAccessQueryKey(agentId ?? ''),
- queryFn: () => getRepositoryAccess(agentId!),
- enabled: useFluePolicy,
- staleTime: 15_000,
- refetchOnWindowFocus: 'always',
- })
- const repoOptions = useMemo(
- () =>
- useFluePolicy
- ? (access?.effective_repositories ?? [])
- : (app?.repositories ?? []),
- [access, app, useFluePolicy],
- )
- const isLoading = useFluePolicy ? accessLoading : appLoading
- const isError = useFluePolicy ? accessError : appError
- const refetch = useFluePolicy ? refetchAccess : refetchApp
- const installed = useFluePolicy
- ? access?.grant.status === 'active'
- : app?.installed !== false // treat "still loading" as installed
- const installUrl = useFluePolicy
- ? access?.grant.install_url
- : app?.install_url
- const policyDisabled =
- useFluePolicy &&
- access?.policy.mode === 'selected' &&
- access.policy.repository_ids.length === 0
- const disabled = !installed || repoOptions.length === 0
- const scope = `${runtime ?? ''}:${agentId ?? ''}`
- const previousScope = useRef(scope)
-
- useEffect(() => {
- if (previousScope.current === scope) return
- previousScope.current = scope
- if (value) onChange(null)
- }, [onChange, scope, value])
-
- const optionsAreAuthoritative = useFluePolicy
- ? accessSuccess &&
- access?.effective_repositories !== null &&
- !access?.grant.truncated
- : appSuccess
- useEffect(() => {
- if (!value || !optionsAreAuthoritative) return
- const stillAvailable = repoOptions.some(
- (repo) => workingRepoValue(repo, useFluePolicy) === value.repo,
- )
- if (!stillAvailable) onChange(null)
- }, [onChange, optionsAreAuthoritative, repoOptions, useFluePolicy, value])
-
- const pickRepo = (repoValue: string) => {
- const r = repoOptions.find((x) =>
- useFluePolicy ? x.id === repoValue : x.full_name === repoValue,
- )
- if (!r) return
- // Keep the current branch when re-picking the same repo; else the repo's default.
- onChange(selectedWorkingRepo(r, useFluePolicy, value))
- }
-
- // Load failed → an explicit retry, not a silent "No repos available" dead-end.
- if (isError) {
- return (
- <button
- type="button"
- onClick={() => void refetch()}
- className="border-border inline-flex h-8 items-center gap-2 rounded-md border border-dashed px-2.5 text-sm text-red-600 transition-colors hover:border-red-400 dark:text-red-500"
- title="Couldn't load your repos — click to retry"
- >
- <GithubMark className="size-3.5" />
- Couldn’t load repos — retry
- </button>
- )
- }
-
- // Not installed → a quiet connect affordance instead of a dead control.
- if (installed === false && installUrl) {
- const unavailable = useFluePolicy && access?.grant.status === 'unavailable'
- return (
- <a
- href={installUrl}
- target="_blank"
- rel="noreferrer"
- className="border-border text-muted-foreground hover:text-foreground hover:border-foreground/25 inline-flex h-8 items-center gap-2 rounded-md border border-dashed px-2.5 text-sm transition-colors"
- title={
- unavailable
- ? 'The GitHub installation is unavailable — reconnect it to work in a repo'
- : 'Connect the OpenComputer GitHub App to work in a repo'
- }
- >
- <GithubMark className="size-3.5" />
- {unavailable ? 'GitHub unavailable' : 'Connect GitHub'}
- </a>
- )
- }
-
- const displayRepo = value?.fullName ?? value?.repo ?? ''
- const [owner, name] = value ? splitRepo(displayRepo) : ['', '']
-
- return (
- <div className="flex flex-wrap items-center gap-1.5">
- <SelectPrimitive.Root
- value={value?.repo ?? ''}
- onValueChange={pickRepo}
- disabled={disabled}
- >
- <SelectPrimitive.Trigger
- aria-label="Working repo"
- title="Optional — the repo the agent works in and opens PRs from"
- className={cn(
- 'border-border bg-panel-2 hover:border-foreground/25 focus-visible:border-foreground/40 data-[state=open]:border-foreground/35 group inline-flex h-8 max-w-64 min-w-40 items-center gap-2 rounded-md border px-2.5 text-sm transition-colors outline-none disabled:cursor-not-allowed disabled:opacity-60',
- )}
- >
- <GithubMark className="text-muted-foreground group-hover:text-foreground/70 size-3.5 shrink-0 transition-colors" />
- <span className="min-w-0 flex-1 truncate text-left">
- {value ? (
- <span className="font-medium">
- <span className="text-muted-foreground">{owner}/</span>
- {name}
- </span>
- ) : (
- <span className="text-muted-foreground">
- {disabled
- ? isLoading
- ? 'Loading repos…'
- : policyDisabled
- ? 'Repository access disabled'
- : 'No repos available'
- : 'Working repo'}
- </span>
- )}
- </span>
- <ChevronDown className="text-muted-foreground/50 size-3.5 shrink-0" />
- </SelectPrimitive.Trigger>
- <SelectPrimitive.Portal>
- <SelectPrimitive.Content
- position="popper"
- sideOffset={5}
- onPointerDownOutside={markFloatingLayerPointerDismiss}
- className="bg-popover text-popover-foreground ring-foreground/10 shadow-overlay data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 z-50 max-h-(--radix-select-content-available-height) min-w-(--radix-select-trigger-width) origin-(--radix-select-content-transform-origin) overflow-hidden rounded-lg p-1 ring-1 duration-100"
- >
- <SelectPrimitive.Viewport>
- {repoOptions.map((r) => {
- const [o, n] = splitRepo(r.full_name)
- const repoValue = workingRepoValue(r, useFluePolicy)
- return (
- <SelectPrimitive.Item
- key={repoValue}
- value={repoValue}
- className="focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-md py-1.5 pr-8 pl-2 text-sm outline-hidden select-none"
- >
- <GithubMark className="text-muted-foreground size-3.5 shrink-0" />
- <SelectPrimitive.ItemText>
- <span className="text-muted-foreground">{o}/</span>
- {n}
- </SelectPrimitive.ItemText>
- <span className="absolute right-2 flex items-center">
- <SelectPrimitive.ItemIndicator>
- <Check className="size-4" />
- </SelectPrimitive.ItemIndicator>
- </span>
- </SelectPrimitive.Item>
- )
- })}
- </SelectPrimitive.Viewport>
- </SelectPrimitive.Content>
- </SelectPrimitive.Portal>
- </SelectPrimitive.Root>
-
- {value ? (
- <span className="border-border bg-panel-2 focus-within:border-foreground/40 inline-flex h-8 items-center gap-1 rounded-md border pr-1 pl-2 transition-colors">
- <GitBranch className="text-muted-foreground size-3.5 shrink-0" />
- <input
- value={value.ref}
- onChange={(e) => onChange({ ...value, ref: e.target.value })}
- placeholder="main"
- aria-label="Branch"
- spellCheck={false}
- className="w-24 bg-transparent font-mono text-xs outline-none"
- />
- <button
- type="button"
- title="Clear working repo"
- className="text-muted-foreground hover:text-foreground hover:bg-accent rounded p-0.5"
- onClick={() => onChange(null)}
- >
- <X className="size-3.5" />
- </button>
- </span>
- ) : null}
- </div>
- )
-}
diff --git a/web/src/hooks/use-agent-deployment-logs.ts b/web/src/hooks/use-agent-deployment-logs.ts
deleted file mode 100644
index df6b5f67..00000000
--- a/web/src/hooks/use-agent-deployment-logs.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { useEffect } from 'react'
-import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { getAgentDeploymentLogs, type AgentDeploymentLog } from '@/api/client'
-
-export function useAgentDeploymentLogs(input: {
- agentId: string
- deploymentId: string
- enabled: boolean
- terminal: boolean
-}) {
- const queryClient = useQueryClient()
- const queryKey = [
- 'agent-deployment-logs',
- input.agentId,
- input.deploymentId,
- ] as const
- const query = useQuery({
- queryKey,
- queryFn: async () => {
- const previous = queryClient.getQueryData<{
- data: AgentDeploymentLog[]
- cursor: string | null
- }>(queryKey)
- 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(
- input.agentId,
- input.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: input.enabled && !!input.agentId && !!input.deploymentId,
- refetchInterval: input.terminal ? false : 1500,
- })
-
- const refetch = query.refetch
- useEffect(() => {
- if (input.enabled && input.terminal) void refetch()
- // One final durable read when an open log terminalizes.
- }, [input.enabled, input.terminal, refetch])
-
- return query
-}
diff --git a/web/src/hooks/use-repository-access.ts b/web/src/hooks/use-repository-access.ts
deleted file mode 100644
index 7fe103e9..00000000
--- a/web/src/hooks/use-repository-access.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { useQuery } from '@tanstack/react-query'
-import { getRepositoryAccess } from '@/api/client'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-
-export function useRepositoryAccess(agentId: string, enabled = true) {
- return useQuery({
- queryKey: repositoryAccessQueryKey(agentId),
- queryFn: () => getRepositoryAccess(agentId),
- enabled: enabled && Boolean(agentId),
- staleTime: 15_000,
- refetchOnWindowFocus: 'always',
- })
-}
diff --git a/web/src/hooks/useHalted.ts b/web/src/hooks/useHalted.ts
deleted file mode 100644
index 867c9996..00000000
--- a/web/src/hooks/useHalted.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { useQuery } from '@tanstack/react-query'
-import { getAutumnBilling } from '@/api/client'
-import { haltBlocksAgents } from '@/lib/billing-onramp'
-
-// Halted state for the credit-gated agent controls (composer, new-session),
-// sharing the app shell's 30s poll. Every work-minute halt blocks them; a paid
-// org halted by the old credit rule keeps the fallback model (haltBlocksAgents).
-// Autumn orgs only; legacy orgs 404 on /billing/autumn → error → treated as not halted.
-export function useHalted(): boolean {
- const { data } = useQuery({
- queryKey: ['autumn-billing'],
- queryFn: getAutumnBilling,
- retry: false,
- refetchInterval: (q) => (q.state.error ? false : 30_000),
- })
- return haltBlocksAgents(data)
-}
diff --git a/web/src/lib/agent-creation-mode.test.ts b/web/src/lib/agent-creation-mode.test.ts
deleted file mode 100644
index 893cd014..00000000
--- a/web/src/lib/agent-creation-mode.test.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { resolveAgentCreationMode } from './agent-creation-mode'
-
-describe('agent creation mode', () => {
- it('defaults to repository import and preserves an explicit manual choice', () => {
- expect(resolveAgentCreationMode(null)).toBe('github')
- expect(resolveAgentCreationMode('github')).toBe('github')
- expect(resolveAgentCreationMode('manual')).toBe('manual')
- })
-})
diff --git a/web/src/lib/agent-creation-mode.ts b/web/src/lib/agent-creation-mode.ts
deleted file mode 100644
index d1ee1eb8..00000000
--- a/web/src/lib/agent-creation-mode.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-export type AgentCreationMode = 'github' | 'manual'
-
-export function resolveAgentCreationMode(
- requestedMode: string | null,
-): AgentCreationMode {
- return requestedMode === 'manual' ? 'manual' : 'github'
-}
diff --git a/web/src/lib/agent-deployment-outcome.test.ts b/web/src/lib/agent-deployment-outcome.test.ts
deleted file mode 100644
index bfb4334e..00000000
--- a/web/src/lib/agent-deployment-outcome.test.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { AgentDeployment } from '@/api/client'
-import { agentDeploymentOutcome } from './agent-deployment-outcome'
-
-function deployment(patch: Partial<AgentDeployment> = {}): AgentDeployment {
- return {
- id: 'dep_old',
- state: 'failed',
- phase: 'Deploy',
- terminal: true,
- result: 'failed',
- input_type: 'github',
- revision_id: null,
- revision: null,
- source: null,
- source_relation: null,
- actor: null,
- ref: 'main',
- sha: 'a'.repeat(40),
- error: null,
- error_class: 'deploy_failed',
- build: null,
- configuration: null,
- log_bytes: 0,
- log_truncated: false,
- live_touched: true,
- agent_live: null,
- restore_eligibility: 'none',
- redeploy_of: null,
- allowed_actions: [],
- active: false,
- timing: {
- accepted_at: null,
- started_at: null,
- finished_at: null,
- cancel_requested_at: null,
- queue_ms: null,
- run_ms: null,
- total_ms: null,
- },
- created_at: '2026-07-14T00:00:00Z',
- updated_at: '2026-07-14T00:00:00Z',
- started_at: null,
- finished_at: null,
- ...patch,
- }
-}
-
-describe('agentDeploymentOutcome', () => {
- it('does not call a recovered historical failure currently unverified', () => {
- const result = agentDeploymentOutcome(
- deployment({
- agent_live: {
- deployment_id: 'dep_new',
- status: 'verified',
- },
- }),
- )
- expect(result.title).toBe('Deployment failed')
- expect(result.description).toContain('later verified deployment')
- })
-
- it('does not call an inactive historical success ready to run', () => {
- const result = agentDeploymentOutcome(
- deployment({
- state: 'ready',
- result: 'ready',
- revision: {
- id: 'rev_old',
- number: 1,
- digest: 'sha256:old',
- created_at: '2026-07-14T00:00:00Z',
- },
- agent_live: {
- deployment_id: 'dep_new',
- status: 'verified',
- },
- }),
- )
- expect(result.title).toBe('Deployment succeeded')
- expect(result.description).toContain('another revision is active')
- })
-
- it('calls only an active, startable revision ready', () => {
- const result = agentDeploymentOutcome(
- deployment({
- state: 'ready',
- result: 'ready',
- active: true,
- allowed_actions: ['start_session'],
- agent_live: {
- deployment_id: 'dep_old',
- status: 'verified',
- },
- }),
- )
- expect(result.kind).toBe('success')
- expect(result.title).toBe('Deployment ready')
- })
-})
diff --git a/web/src/lib/agent-deployment-outcome.ts b/web/src/lib/agent-deployment-outcome.ts
deleted file mode 100644
index bd0872af..00000000
--- a/web/src/lib/agent-deployment-outcome.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import type { AgentDeployment } from '@/api/client'
-
-export type AgentDeploymentOutcome = {
- kind: 'success' | 'error' | 'info' | 'progress'
- title: string
- description: string
-}
-
-function revisionLabel(deployment: AgentDeployment): string {
- return deployment.revision?.number
- ? `Revision #${deployment.revision.number}`
- : 'The built revision'
-}
-
-function failureMessage(deployment: AgentDeployment): string | undefined {
- return deployment.error?.message
-}
-
-/**
- * Describe this immutable attempt against the agent's current live pointer.
- * Historical rows must not claim that they are still active or unverified after
- * a later deployment changed the live truth.
- */
-export function agentDeploymentOutcome(
- deployment: AgentDeployment,
-): AgentDeploymentOutcome {
- const live = deployment.agent_live
- const liveBelongsToAttempt = live?.deployment_id === deployment.id
- const canStart = deployment.allowed_actions.includes('start_session')
-
- if (deployment.state === 'ready') {
- if (deployment.active && canStart) {
- return {
- kind: 'success',
- title: 'Deployment ready',
- description: `${revisionLabel(deployment)} is active and ready to run.`,
- }
- }
- if (!deployment.active) {
- return {
- kind: 'info',
- title: 'Deployment succeeded',
- description: `${revisionLabel(deployment)} was created, but another revision is active.`,
- }
- }
- return {
- kind: 'error',
- title: 'Active deployment is not verified',
- description:
- liveBelongsToAttempt && live?.status === 'updating'
- ? 'The live Worker is still updating. New sessions remain paused until verification finishes.'
- : 'The revision is active, but the current live Worker is not verified for new sessions.',
- }
- }
-
- if (deployment.state === 'failed') {
- const message = failureMessage(deployment)
- if (
- deployment.live_touched &&
- (liveBelongsToAttempt || !live) &&
- live?.status !== 'verified'
- ) {
- return {
- kind: 'error',
- title: 'Live deployment could not be verified',
- description:
- message ??
- 'The live Worker may have changed. Check the persisted log before starting new work.',
- }
- }
-
- const currentTruth =
- live?.status === 'verified'
- ? ' A later verified deployment is now live.'
- : live && !liveBelongsToAttempt
- ? ' A later deployment currently requires attention before new sessions can start.'
- : ''
- return {
- kind: 'error',
- title: 'Deployment failed',
- description:
- (message ??
- (deployment.live_touched
- ? 'This attempt changed the live Worker before it failed.'
- : 'The live agent was not changed. Fix the repository before deploying again.')) +
- currentTruth,
- }
- }
-
- if (
- deployment.state === 'canceled' ||
- deployment.state === 'superseded' ||
- deployment.state === 'skipped'
- ) {
- return {
- kind: 'info',
- title:
- deployment.state === 'skipped'
- ? 'No changes to deploy'
- : deployment.state === 'canceled'
- ? 'Deployment canceled'
- : 'Deployment superseded',
- description:
- 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.',
- }
- }
-
- return {
- kind: 'progress',
- title: 'Deployment in progress',
- description: 'This page polls the durable deployment record and build log.',
- }
-}
diff --git a/web/src/lib/agent-deployment-status.test.ts b/web/src/lib/agent-deployment-status.test.ts
deleted file mode 100644
index e216dfca..00000000
--- a/web/src/lib/agent-deployment-status.test.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- agentCanStartNewSession,
- agentDeploymentDisplayStatus,
-} from './agent-deployment-status'
-
-const baseAgent = {
- runtime: 'flue',
- revision: 2,
- active_revision_id: 'rev_123',
- flue: {
- agent_name: 'support',
- live: {
- status: 'verified',
- },
- },
-}
-
-describe('agent deployment display status', () => {
- it('does not present a live-touching unverified deployment as ready', () => {
- expect(
- agentDeploymentDisplayStatus({
- ...baseAgent,
- deployment_status: {
- deployment_id: 'dep_123',
- state: 'ready',
- result: 'created',
- error_class: null,
- live_touched: true,
- live_status: 'unverified',
- updated_at: '2026-07-14T20:00:00.000Z',
- },
- }),
- ).toBe('unverified')
- })
-
- it('uses the live updating state rather than the artifact-uploading phase', () => {
- expect(
- agentDeploymentDisplayStatus({
- ...baseAgent,
- deployment_status: {
- deployment_id: 'dep_123',
- state: 'ready',
- result: 'created',
- error_class: null,
- live_touched: true,
- live_status: 'updating',
- updated_at: '2026-07-14T20:00:00.000Z',
- },
- }),
- ).toBe('updating')
- })
-
- it('keeps a terminal failure visible even when an older live revision exists', () => {
- expect(
- agentDeploymentDisplayStatus({
- ...baseAgent,
- deployment_status: {
- deployment_id: 'dep_124',
- state: 'failed',
- result: 'failed',
- error_class: 'build_failed',
- live_touched: false,
- live_status: 'verified',
- updated_at: '2026-07-14T20:00:00.000Z',
- },
- }),
- ).toBe('failed')
- })
-
- it('uses the live pointer when deployment status is unavailable', () => {
- expect(
- agentDeploymentDisplayStatus({
- ...baseAgent,
- deployment_status: undefined,
- flue: {
- agent_name: 'support',
- live: { status: 'unverified' },
- },
- }),
- ).toBe('unverified')
- })
-
- it('labels an agent without a deployment or revision explicitly', () => {
- expect(
- agentDeploymentDisplayStatus({
- runtime: 'flue',
- revision: 0,
- active_revision_id: null,
- deployment_status: undefined,
- flue: { agent_name: 'support', live: null },
- }),
- ).toBe('not_deployed')
- })
-})
-
-describe('agent session admission', () => {
- it('admits an active legacy Flue agent only from the server proof', () => {
- const legacy = {
- ...baseAgent,
- flue: { agent_name: 'support', live: null },
- deployment_status: {
- deployment_id: 'dep_legacy',
- state: 'ready',
- result: 'created',
- error_class: null,
- live_touched: false,
- live_status: null,
- legacy_live_compatible: true,
- updated_at: '2026-07-14T20:00:00.000Z',
- },
- }
-
- expect(agentCanStartNewSession(legacy)).toBe(true)
- expect(agentDeploymentDisplayStatus(legacy)).not.toBe('verified')
- })
-
- it('does not let the compatibility proof replace an active revision', () => {
- expect(
- agentCanStartNewSession({
- runtime: 'flue',
- revision: 0,
- active_revision_id: null,
- deployment_status: {
- deployment_id: null,
- state: 'not_deployed',
- result: null,
- error_class: null,
- live_touched: false,
- live_status: null,
- legacy_live_compatible: true,
- updated_at: null,
- },
- flue: { agent_name: 'support', live: null },
- }),
- ).toBe(false)
- })
-
- it('keeps verified Flue and active built-in agents startable', () => {
- expect(agentCanStartNewSession(baseAgent)).toBe(true)
- expect(
- agentCanStartNewSession({
- runtime: 'claude',
- revision: 1,
- active_revision_id: 'rev_builtin',
- deployment_status: undefined,
- flue: null,
- }),
- ).toBe(true)
- })
-})
diff --git a/web/src/lib/agent-deployment-status.ts b/web/src/lib/agent-deployment-status.ts
deleted file mode 100644
index 590b4a25..00000000
--- a/web/src/lib/agent-deployment-status.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import type { Agent } from '@/api/client'
-
-type AgentDeploymentHealth = Pick<
- Agent,
- 'runtime' | 'revision' | 'active_revision_id' | 'deployment_status' | 'flue'
->
-
-/**
- * The latest deployment is the primary status. A successful row is only
- * healthy when a live-touching Flue deploy also left the live pointer verified.
- */
-export function agentDeploymentDisplayStatus(
- agent: AgentDeploymentHealth,
-): string {
- const deployment = agent.deployment_status
- const liveStatus = deployment?.live_status ?? agent.flue?.live?.status ?? null
- const hasActiveRevision =
- !!agent.active_revision_id || (agent.revision ?? 0) > 0
- const status =
- deployment?.state ?? (hasActiveRevision ? 'ready' : 'not_deployed')
- const liveWasTouched = deployment?.live_touched ?? agent.flue?.live != null
-
- if (status === 'ready' && liveWasTouched && liveStatus !== 'verified') {
- return liveStatus === 'updating' ? 'updating' : 'unverified'
- }
-
- return status
-}
-
-/**
- * Session admission is stricter than the display status. New Flue deployments
- * require a verified live pointer. Existing CLI-created Flue agents can carry
- * a server-computed compatibility proof while their physical live status is
- * intentionally unknown; that proof enables admission only and must never be
- * projected as a live/verified label.
- */
-export function agentCanStartNewSession(agent: AgentDeploymentHealth): boolean {
- const hasActiveRevision =
- !!agent.active_revision_id || (agent.revision ?? 0) > 0
- if (!hasActiveRevision) return false
- if (agent.runtime !== 'flue') return true
-
- const liveStatus =
- agent.deployment_status?.live_status ?? agent.flue?.live?.status ?? null
- return (
- liveStatus === 'verified' ||
- agent.deployment_status?.legacy_live_compatible === true
- )
-}
diff --git a/web/src/lib/agent-setup-presentation.test.ts b/web/src/lib/agent-setup-presentation.test.ts
deleted file mode 100644
index 8f2e7155..00000000
--- a/web/src/lib/agent-setup-presentation.test.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- agentSetupPresentation,
- agentSetupStage,
-} from './agent-setup-presentation'
-
-describe('agentSetupPresentation', () => {
- it('keeps a fetch error distinct from a failed deployment', () => {
- expect(
- agentSetupStage({
- hasDeployment: true,
- loadFailed: true,
- canStartSession: false,
- agentReady: true,
- }),
- ).toBe('preparing')
- })
-
- it('requires session admission before treating ready as usable', () => {
- const base = {
- hasDeployment: true,
- state: 'ready',
- terminal: true,
- loadFailed: false,
- agentReady: true,
- }
-
- expect(agentSetupStage({ ...base, canStartSession: false })).toBe(
- 'preparing',
- )
- expect(agentSetupStage({ ...base, canStartSession: true })).toBe('ready')
- })
-
- it('makes Slack the next action while deployment continues', () => {
- const view = agentSetupPresentation({
- agentName: 'Support triage',
- stage: 'preparing',
- managedStatus: null,
- connecting: false,
- })
-
- expect(view.title).toBe('Connect Slack while we prepare Support triage')
- expect(view.action).toBe('connect')
- expect(view.label).toBe('Connect Slack')
- })
-
- it('waits for readiness after Slack connects', () => {
- const view = agentSetupPresentation({
- agentName: 'Support triage',
- stage: 'preparing',
- managedStatus: 'active',
- openUrl: 'https://slack.com/app_redirect?app=A1&team=T1',
- connecting: false,
- })
-
- expect(view.title).toBe('Slack is connected')
- expect(view.action).toBeNull()
- expect(view.description).toContain('Open Slack will appear')
- })
-
- it('promotes the first message only when both resources are ready', () => {
- const view = agentSetupPresentation({
- agentName: 'Support triage',
- stage: 'ready',
- managedStatus: 'active',
- openUrl: 'https://slack.com/app_redirect?app=A1&team=T1',
- connecting: false,
- })
-
- expect(view.title).toBe('Send your first message')
- expect(view.action).toBe('open')
- expect(view.label).toBe('Open Slack')
- })
-
- it('hands a real first Slack session into continued conversation', () => {
- const view = agentSetupPresentation({
- agentName: 'Support triage',
- stage: 'ready',
- managedStatus: 'active',
- openUrl: 'https://slack.com/app_redirect?app=A1&team=T1',
- connecting: false,
- activated: true,
- })
-
- expect(view.title).toBe('Support triage is live in Slack')
- expect(view.action).toBe('open')
- expect(view.label).toBe('Continue in Slack')
- })
-
- it('makes deployment recovery primary after a failure', () => {
- const view = agentSetupPresentation({
- agentName: 'Support triage',
- stage: 'failed',
- managedStatus: 'active',
- connecting: false,
- })
-
- expect(view.title).toBe('The deployment needs attention')
- expect(view.action).toBeNull()
- expect(view.description).toContain('Review the failed deployment')
- })
-})
diff --git a/web/src/lib/agent-setup-presentation.ts b/web/src/lib/agent-setup-presentation.ts
deleted file mode 100644
index 3f4f868f..00000000
--- a/web/src/lib/agent-setup-presentation.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-import {
- deploymentSlackPresentation,
- deploymentStage,
- type DeploymentSlackPresentation,
- type ManagedSlackStatus,
-} from '@/lib/deployment-slack-cta'
-
-export type AgentSetupStage = 'preparing' | 'ready' | 'failed'
-
-export function agentSetupStage(input: {
- hasDeployment: boolean
- state?: string
- terminal?: boolean
- loadFailed: boolean
- canStartSession: boolean
- agentReady: boolean
- agentDeploymentState?: string
-}): AgentSetupStage {
- if (!input.hasDeployment) {
- if (input.agentReady) return 'ready'
- if (
- [
- 'failed',
- 'canceled',
- 'superseded',
- 'skipped',
- 'unverified',
- 'not_deployed',
- ].includes(input.agentDeploymentState ?? '')
- ) {
- return 'failed'
- }
- return 'preparing'
- }
-
- // A status-read failure is not a deployment failure, but it also cannot
- // prove the deployment's authoritative start_session action. Preserve
- // independent Slack setup without promoting chat until the read recovers.
- if (input.loadFailed) return 'preparing'
- if (!input.state) return 'preparing'
- const stage = deploymentStage(input.state, input.terminal ?? false)
- if (stage === 'ready' && !input.canStartSession) return 'preparing'
- return stage === 'running' ? 'preparing' : stage
-}
-
-export interface AgentSetupPresentation extends DeploymentSlackPresentation {
- title: string
- description: string
-}
-
-export function agentSetupPresentation(input: {
- agentName: string
- stage: AgentSetupStage
- managedStatus: ManagedSlackStatus
- openUrl?: string | null
- connecting: boolean
- activated?: boolean
-}): AgentSetupPresentation {
- const slack = deploymentSlackPresentation({
- deploymentState: input.stage === 'ready' ? 'ready' : input.stage,
- deploymentTerminal: input.stage !== 'preparing',
- canStartSession: input.stage === 'ready',
- managedStatus: input.managedStatus,
- openUrl: input.openUrl,
- connecting: input.connecting,
- })
-
- if (input.stage === 'failed') {
- return {
- ...slack,
- title: 'The deployment needs attention',
- description:
- input.managedStatus === 'active'
- ? 'Slack is connected. Review the failed deployment, then return here to start chatting.'
- : 'Review the failure and deploy again. You can finish Slack setup after the agent is ready.',
- }
- }
-
- if (input.managedStatus === 'active') {
- if (input.stage === 'ready' && input.openUrl) {
- if (input.activated) {
- return {
- ...slack,
- label: 'Continue in Slack',
- announcement:
- 'Your first Slack message created an OpenComputer session.',
- title: `${input.agentName} is live in Slack`,
- description:
- 'Your first message created a durable session. Keep chatting in Slack or open the full conversation in OpenComputer.',
- }
- }
- return {
- ...slack,
- title: 'Send your first message',
- description: `Open Slack, find OpenComputer, and say hello to ${input.agentName}.`,
- }
- }
- if (input.stage === 'ready') {
- return {
- ...slack,
- title: 'Slack is connected',
- description: `Open Slack, find OpenComputer, and say hello to ${input.agentName}.`,
- }
- }
- return {
- ...slack,
- title: 'Slack is connected',
- description: `We’re finishing ${input.agentName}’s deployment. Open Slack will appear here as soon as the agent is ready.`,
- }
- }
-
- if (input.stage === 'ready') {
- return {
- ...slack,
- title: `${input.agentName} is ready`,
- description:
- 'Connect Slack to start chatting with your agent. OpenComputer’s app is the quickest way to try it.',
- }
- }
-
- return {
- ...slack,
- title: `Connect Slack while we prepare ${input.agentName}`,
- description:
- 'Authorize the OpenComputer app now. The deployment will keep running in the background.',
- }
-}
diff --git a/web/src/lib/deferred-actions.ts b/web/src/lib/deferred-actions.ts
index a36fd389..f5ef7590 100644
--- a/web/src/lib/deferred-actions.ts
+++ b/web/src/lib/deferred-actions.ts
@@ -8,8 +8,6 @@
//
// Design + rationale: opencomputer .agents/work/deferred-actions.md
import { z } from 'zod'
-import { createAgent } from '@/api/client'
-import { DEFAULT_RUNTIME, defaultModelFor } from '@/lib/runtimes'
export const ActionEnvelopeSchema = z.object({
v: z.literal(1),
@@ -56,51 +54,7 @@ export type ActionResult = {
}
export type ActionHandler = (params: unknown) => Promise<ActionResult>
-// Cap kept in sync with the edge safeReturnTo length limit — a longer prompt
-// would make the /do?action= URL exceed what round-trips through WorkOS `state`
-// on the anonymous signup path (see cloudflare-workers/api-edge/src/index.ts).
-export const AgentPrefillParamsSchema = z.object({
- prompt: z.string().trim().min(1).max(1000),
-})
-
-// Deterministic agent name from the prompt so a retry — or the same link
-// clicked twice — resolves to the SAME (owner, name) and the create-or-get
-// endpoint returns the existing agent instead of spawning a duplicate.
-// /v3/agents dedupes on (owner, name); it has no idempotency-key path.
-function deriveAgentName(prompt: string): string {
- const slug = prompt
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .slice(0, 32)
- .replace(/-+$/g, '')
- let h = 0
- for (let i = 0; i < prompt.length; i++) h = (Math.imul(h, 31) + prompt.charCodeAt(i)) | 0
- const suffix = (h >>> 0).toString(36)
- return `${slug || 'agent'}-${suffix}`
-}
-
-// agent_prefill: create the agent (managed billing — free, zero-config for a
-// fresh org) and land on its sessions tab with the composer prefilled. It does
-// NOT start a session — the first turn spends credits, so it waits for an
-// explicit keypress. This also makes drive-by links harmless (a hostile link
-// can create a free agent at worst, never spend money).
-const agentPrefill: ActionHandler = async (params) => {
- const { prompt } = AgentPrefillParamsSchema.parse(params)
- const agent = await createAgent({
- name: deriveAgentName(prompt),
- prompt,
- model: defaultModelFor(DEFAULT_RUNTIME),
- runtime: DEFAULT_RUNTIME,
- credential: 'managed',
- })
- return {
- navigateTo: `/agents/${agent.id}/sessions`,
- navigateState: { composerPrefill: prompt },
- analytics: { agent_id: agent.id },
- }
-}
-
-export const actionHandlers: Record<string, ActionHandler> = {
- agent_prefill: agentPrefill,
-}
+// No action types are registered: the only one (agent_prefill) created a
+// Durable Agent Sessions agent, which has been removed. Unknown types render the
+// neutral "unsupported link" state.
+export const actionHandlers: Record<string, ActionHandler> = {}
diff --git a/web/src/lib/deployment-slack-cta.test.ts b/web/src/lib/deployment-slack-cta.test.ts
deleted file mode 100644
index 3cd65fce..00000000
--- a/web/src/lib/deployment-slack-cta.test.ts
+++ /dev/null
@@ -1,126 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- deploymentSlackPresentation,
- deploymentStage,
-} from '@/lib/deployment-slack-cta'
-
-function presentation(
- patch: Partial<Parameters<typeof deploymentSlackPresentation>[0]> = {},
-) {
- return deploymentSlackPresentation({
- deploymentState: 'building',
- deploymentTerminal: false,
- canStartSession: false,
- managedStatus: null,
- openUrl: null,
- connecting: false,
- ...patch,
- })
-}
-
-describe('deployment and managed Slack composition', () => {
- it('derives running, ready, and failed from deployment truth', () => {
- expect(deploymentStage('building', false)).toBe('running')
- expect(deploymentStage('ready', true)).toBe('ready')
- expect(deploymentStage('failed', true)).toBe('failed')
- })
-
- it('offers Slack setup immediately while a deployment runs', () => {
- expect(presentation()).toMatchObject({
- action: 'connect',
- label: 'Connect Slack',
- disclosure: true,
- })
- expect(presentation({ connecting: true })).toMatchObject({
- action: 'connecting',
- label: 'Connecting…',
- })
- })
-
- it('keeps an active connection quiet until the deployment is ready', () => {
- expect(presentation({ managedStatus: 'active' })).toMatchObject({
- action: null,
- status: 'Slack connected. Open Slack when this deployment is ready.',
- })
- })
-
- it('promotes Open Slack only when ready and active', () => {
- expect(
- presentation({
- deploymentState: 'ready',
- deploymentTerminal: true,
- canStartSession: true,
- managedStatus: 'active',
- openUrl: 'https://slack.com/app_redirect?app=A123',
- }),
- ).toMatchObject({
- action: 'open',
- label: 'Open Slack',
- announcement: 'Deployment ready. Open Slack is now available.',
- })
- })
-
- it('offers setup from ready and keeps dashboard chat secondary', () => {
- expect(
- presentation({
- deploymentState: 'ready',
- deploymentTerminal: true,
- canStartSession: true,
- }),
- ).toMatchObject({
- action: 'connect',
- label: 'Connect Slack',
- announcement: 'Connect Slack to use this ready agent.',
- })
- })
-
- it('does not promote Slack from a ready-but-unadmitted deployment', () => {
- expect(
- presentation({
- deploymentState: 'ready',
- deploymentTerminal: true,
- canStartSession: false,
- managedStatus: 'active',
- openUrl: 'https://slack.com/app_redirect?app=A123',
- }),
- ).toMatchObject({
- action: null,
- status: 'Slack connected. Open Slack when this deployment is ready.',
- })
- })
-
- it('makes deployment recovery primary after failure', () => {
- expect(
- presentation({
- deploymentState: 'failed',
- deploymentTerminal: true,
- }),
- ).toMatchObject({ action: null, status: null })
- expect(
- presentation({
- deploymentState: 'failed',
- deploymentTerminal: true,
- managedStatus: 'active',
- }),
- ).toMatchObject({
- action: null,
- status: 'Slack remains connected while you fix this deployment.',
- })
- })
-
- it('does not mistake loading for a never-connected result', () => {
- expect(presentation({ managedStatus: undefined })).toMatchObject({
- action: null,
- label: null,
- })
- })
-
- it('keeps reconnect a connector-local action', () => {
- for (const managedStatus of ['disconnected', 'error', 'revoked'] as const) {
- expect(presentation({ managedStatus })).toMatchObject({
- action: 'reconnect',
- label: 'Reconnect Slack',
- })
- }
- })
-})
diff --git a/web/src/lib/deployment-slack-cta.ts b/web/src/lib/deployment-slack-cta.ts
deleted file mode 100644
index 72ca2c83..00000000
--- a/web/src/lib/deployment-slack-cta.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-export type ManagedSlackStatus =
- | 'active'
- | 'disconnected'
- | 'error'
- | 'revoked'
- | null
- | undefined
-
-export type DeploymentSlackAction =
- | 'connect'
- | 'connecting'
- | 'reconnect'
- | 'open'
- | null
-
-export interface DeploymentSlackPresentation {
- action: DeploymentSlackAction
- label: string | null
- disclosure: boolean
- status: string | null
- announcement: string
-}
-
-export function deploymentStage(
- state: string,
- terminal: boolean,
-): 'running' | 'ready' | 'failed' {
- if (state === 'ready') return 'ready'
- return terminal ? 'failed' : 'running'
-}
-
-/**
- * Compose two independent resources without inventing a combined backend
- * state: durable deployment readiness and the managed Slack connection.
- * `undefined` means the connection query has not produced a trustworthy result;
- * `null` is the durable "never connected" result.
- */
-export function deploymentSlackPresentation(input: {
- deploymentState: string
- deploymentTerminal: boolean
- canStartSession: boolean
- managedStatus: ManagedSlackStatus
- openUrl?: string | null
- connecting: boolean
-}): DeploymentSlackPresentation {
- const stage = deploymentStage(input.deploymentState, input.deploymentTerminal)
- const ready = stage === 'ready' && input.canStartSession
-
- if (stage === 'failed') {
- return {
- action: null,
- label: null,
- disclosure: false,
- status:
- input.managedStatus === 'active'
- ? 'Slack remains connected while you fix this deployment.'
- : null,
- announcement:
- input.managedStatus === 'active'
- ? 'Deployment failed. Slack remains connected.'
- : 'Deployment failed.',
- }
- }
-
- if (input.managedStatus === undefined) {
- return {
- action: null,
- label: null,
- disclosure: false,
- status: null,
- announcement: '',
- }
- }
-
- if (input.managedStatus === 'active') {
- if (ready && input.openUrl) {
- return {
- action: 'open',
- label: 'Open Slack',
- disclosure: false,
- status: null,
- announcement: 'Deployment ready. Open Slack is now available.',
- }
- }
- return {
- action: null,
- label: null,
- disclosure: false,
- status: !ready
- ? 'Slack connected. Open Slack when this deployment is ready.'
- : 'Slack is connected.',
- announcement: !ready
- ? 'Slack connected. Open Slack will be available when the deployment is ready.'
- : 'Slack connected.',
- }
- }
-
- const reconnect =
- input.managedStatus === 'disconnected' ||
- input.managedStatus === 'error' ||
- input.managedStatus === 'revoked'
-
- if (input.connecting) {
- return {
- action: 'connecting',
- label: 'Connecting…',
- disclosure: input.managedStatus === null,
- status: null,
- announcement: 'Opening Slack authorization.',
- }
- }
-
- if (reconnect) {
- return {
- action: 'reconnect',
- label: 'Reconnect Slack',
- disclosure: false,
- status: 'The OpenComputer Slack app needs authorization.',
- announcement: 'The Slack connection needs authorization.',
- }
- }
-
- return {
- action: 'connect',
- label: 'Connect Slack',
- disclosure: true,
- status: null,
- announcement: ready
- ? 'Connect Slack to use this ready agent.'
- : 'Connect Slack while the deployment continues.',
- }
-}
diff --git a/web/src/lib/managed-slack-connections.ts b/web/src/lib/managed-slack-connections.ts
deleted file mode 100644
index 51688636..00000000
--- a/web/src/lib/managed-slack-connections.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import { useQuery } from '@tanstack/react-query'
-import {
- getManagedSlackConnections,
- type ManagedSlackWorkspaceConnection,
-} from '@/api/client'
-
-export const managedSlackConnectionsQueryKey = [
- 'slack',
- 'managed',
- 'connections',
-] as const
-
-export function useManagedSlackConnections(enabled = true) {
- return useQuery({
- queryKey: managedSlackConnectionsQueryKey,
- queryFn: getManagedSlackConnections,
- enabled,
- refetchOnWindowFocus: 'always',
- })
-}
-
-export function managedSlackDisconnectCopy(
- connection: ManagedSlackWorkspaceConnection,
- nextAgentName: string,
- moveHere = false,
-) {
- const workspace = connection.workspace?.name || connection.workspace?.id
- const workspaceLabel = workspace || 'this Slack workspace'
- if (moveHere) {
- return {
- title: `Move ${workspaceLabel} to ${nextAgentName}?`,
- description: `OpenComputer will disconnect ${workspaceLabel} from ${connection.agent.name}, then open Slack so you can authorize it for ${nextAgentName}. If you stop before authorization completes, the app stays installed but does not send messages to an agent.`,
- }
- }
- return {
- title: `Disconnect ${workspaceLabel} from ${connection.agent.name}?`,
- description: `New Slack messages from ${workspaceLabel} will stop going to ${connection.agent.name}. The agent and its existing sessions stay available, and the OpenComputer app stays installed. After disconnecting, connect Slack again and select this workspace for ${nextAgentName}.`,
- }
-}
diff --git a/web/src/lib/managed-slack-notice.test.ts b/web/src/lib/managed-slack-notice.test.ts
deleted file mode 100644
index 6acdafee..00000000
--- a/web/src/lib/managed-slack-notice.test.ts
+++ /dev/null
@@ -1,29 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- managedSlackNotice,
- managedSlackOAuthPending,
-} from '@/lib/managed-slack-notice'
-
-describe('managed Slack OAuth settlement', () => {
- it('polls only while a successful callback is still converging', () => {
- expect(managedSlackOAuthPending('connected', undefined, null)).toBe(true)
- expect(managedSlackOAuthPending('connected', 'active', null)).toBe(true)
- expect(
- managedSlackOAuthPending('connected', 'active', '2026-07-17T10:00:00Z'),
- ).toBe(false)
-
- for (const status of ['disconnected', 'error', 'revoked'] as const) {
- expect(managedSlackOAuthPending('connected', status, null)).toBe(false)
- }
- })
-
- it('explains a terminal non-active callback result', () => {
- expect(
- managedSlackNotice('connected', 'Acme', 'Support triage', null, 'error'),
- ).toEqual({
- title: "Slack couldn't finish connecting",
- description: 'Reconnect Slack and try again.',
- destructive: true,
- })
- })
-})
diff --git a/web/src/lib/managed-slack-notice.ts b/web/src/lib/managed-slack-notice.ts
deleted file mode 100644
index d7a655c7..00000000
--- a/web/src/lib/managed-slack-notice.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import type { ManagedSlackStatus } from '@/lib/deployment-slack-cta'
-
-const MANAGED_SLACK_RESULTS = new Set([
- 'connected',
- 'oauth_denied',
- 'oauth_state_invalid',
- 'oauth_state_expired',
- 'oauth_exchange_failed',
- 'oauth_scope_missing',
- 'enterprise_install_unsupported',
- 'slack_upstream_unavailable',
- 'agent_not_ready',
- 'workspace_already_connected',
-])
-
-const TERMINAL_MANAGED_SLACK_STATUSES = new Set<ManagedSlackStatus>([
- 'disconnected',
- 'error',
- 'revoked',
-])
-
-export function managedSlackOAuthPending(
- result: string | null,
- status: ManagedSlackStatus,
- connectedAt?: string | null,
-): boolean {
- if (result !== 'connected') return false
- if (TERMINAL_MANAGED_SLACK_STATUSES.has(status)) return false
- return status !== 'active' || !connectedAt
-}
-
-export function managedSlackNotice(
- result: string | null,
- workspace: string | null | undefined,
- agentName: string,
- connectedAgentName?: string | null,
- managedStatus?: ManagedSlackStatus,
-): { title: string; description?: string; destructive?: boolean } | null {
- if (!result || !MANAGED_SLACK_RESULTS.has(result)) return null
- if (
- result === 'connected' &&
- TERMINAL_MANAGED_SLACK_STATUSES.has(managedStatus)
- ) {
- switch (managedStatus) {
- case 'revoked':
- return {
- title: 'Slack authorization was revoked',
- description: 'Reconnect Slack to authorize OpenComputer again.',
- destructive: true,
- }
- case 'disconnected':
- return {
- title: 'Slack did not stay connected',
- description: 'Reconnect Slack to finish setup.',
- destructive: true,
- }
- default:
- return {
- title: "Slack couldn't finish connecting",
- description: 'Reconnect Slack and try again.',
- destructive: true,
- }
- }
- }
- switch (result) {
- case 'connected':
- return {
- title: 'Slack connected',
- description: workspace
- ? `OpenComputer will send messages in ${workspace} to ${agentName}.`
- : `OpenComputer will send Slack messages to ${agentName}.`,
- }
- case 'oauth_denied':
- return { title: 'Slack connection was canceled' }
- case 'oauth_state_invalid':
- case 'oauth_state_expired':
- return {
- title: 'Slack connection session expired',
- description: 'Connect Slack again.',
- destructive: true,
- }
- case 'oauth_scope_missing':
- return {
- title: 'Slack permissions are incomplete',
- description: 'Reconnect and approve the requested permissions.',
- destructive: true,
- }
- case 'enterprise_install_unsupported':
- return {
- title: 'Enterprise Grid installation is not supported yet',
- description: 'Install the app in a single Slack workspace instead.',
- destructive: true,
- }
- case 'agent_not_ready':
- return {
- title: 'This agent cannot connect to Slack yet',
- description: 'Finish its initial setup, then try again.',
- destructive: true,
- }
- case 'workspace_already_connected':
- return {
- title: 'This Slack workspace is already connected',
- description: connectedAgentName
- ? `This workspace sends messages to ${connectedAgentName}. Move it below to connect it to ${agentName}.`
- : 'Connect a different workspace or use your own Slack app for this agent.',
- destructive: true,
- }
- case 'oauth_exchange_failed':
- case 'slack_upstream_unavailable':
- return {
- title: "Slack couldn't complete the connection",
- description: 'Try again in a moment.',
- destructive: true,
- }
- default:
- return null
- }
-}
diff --git a/web/src/lib/managed-slack-session.test.ts b/web/src/lib/managed-slack-session.test.ts
deleted file mode 100644
index fde4aca2..00000000
--- a/web/src/lib/managed-slack-session.test.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { Session } from '@/api/client'
-import {
- isManagedSlackSession,
- latestManagedSlackSession,
-} from '@/lib/managed-slack-session'
-
-function session(
- id: string,
- createdAt: string,
- mode: 'managed' | 'byo' | null,
-): Session {
- return {
- id,
- status: 'idle',
- created_at: createdAt,
- metadata: mode ? { slack: { mode } } : null,
- }
-}
-
-describe('managed Slack activation sessions', () => {
- it('uses the durable session origin and current connection boundary', () => {
- expect(
- isManagedSlackSession(
- session('ses_managed', '2026-07-17T10:00:01Z', 'managed'),
- '2026-07-17T10:00:00Z',
- ),
- ).toBe(true)
- expect(
- isManagedSlackSession(
- session('ses_old', '2026-07-17T09:59:59Z', 'managed'),
- '2026-07-17T10:00:00Z',
- ),
- ).toBe(false)
- expect(
- isManagedSlackSession(
- session('ses_byo', '2026-07-17T10:00:01Z', 'byo'),
- '2026-07-17T10:00:00Z',
- ),
- ).toBe(false)
- })
-
- it('finds the latest matching conversation without claiming dashboard sessions', () => {
- const sessions = [
- session('ses_dashboard', '2026-07-17T10:03:00Z', null),
- session('ses_first', '2026-07-17T10:01:00Z', 'managed'),
- session('ses_latest', '2026-07-17T10:02:00Z', 'managed'),
- ]
-
- expect(
- latestManagedSlackSession(sessions, '2026-07-17T10:00:00Z')?.id,
- ).toBe('ses_latest')
- })
-
- it('does not claim an older conversation without a connection boundary', () => {
- const prior = session(
- 'ses_prior_connection',
- '2026-07-17T10:00:00Z',
- 'managed',
- )
-
- expect(isManagedSlackSession(prior, null)).toBe(false)
- expect(latestManagedSlackSession([prior], null)).toBeUndefined()
- })
-})
diff --git a/web/src/lib/managed-slack-session.ts b/web/src/lib/managed-slack-session.ts
deleted file mode 100644
index a15e5948..00000000
--- a/web/src/lib/managed-slack-session.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { Session } from '@/api/client'
-
-function record(value: unknown): Record<string, unknown> {
- return value && typeof value === 'object' && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : {}
-}
-
-/**
- * Managed Slack ingress records its origin on the ordinary durable session.
- * Keep onboarding discovery on that public session truth instead of inventing
- * a second activation state machine in the dashboard.
- */
-export function isManagedSlackSession(
- session: Session,
- connectedAt?: string | null,
-): boolean {
- const slack = record(record(session.metadata).slack)
- if (slack.mode !== 'managed') return false
-
- // The connection timestamp is the generation boundary. Without it, an
- // active reconnect must not claim an older managed session as this setup's
- // first conversation.
- if (!connectedAt) return false
- const connectedTime = Date.parse(connectedAt)
- const sessionTime = Date.parse(session.created_at)
- return (
- Number.isFinite(connectedTime) &&
- Number.isFinite(sessionTime) &&
- sessionTime >= connectedTime
- )
-}
-
-export function latestManagedSlackSession(
- sessions: Session[],
- connectedAt?: string | null,
-): Session | undefined {
- return sessions
- .filter((session) => isManagedSlackSession(session, connectedAt))
- .sort(
- (a, b) =>
- Date.parse(b.created_at) - Date.parse(a.created_at) ||
- b.id.localeCompare(a.id),
- )[0]
-}
diff --git a/web/src/lib/repository-access.test.ts b/web/src/lib/repository-access.test.ts
deleted file mode 100644
index 615d4715..00000000
--- a/web/src/lib/repository-access.test.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- isNarrowingRepositoryAccess,
- repositoryAccessCandidates,
- repositoryAccessQueryKey,
- showRepositoryAccessDuringSetup,
- toggleSelectedRepository,
-} from './repository-access'
-
-describe('repository access helpers', () => {
- it('uses the documented agent-scoped query key', () => {
- expect(repositoryAccessQueryKey('agt_1')).toEqual([
- 'agent-repository-access',
- 'agt_1',
- ])
- })
-
- it('shows built-in repository access before Slack while preserving Flue setup order', () => {
- expect(showRepositoryAccessDuringSetup('claude', 'disconnected')).toBe(true)
- expect(showRepositoryAccessDuringSetup('codex', undefined)).toBe(true)
- expect(showRepositoryAccessDuringSetup('pi', null)).toBe(true)
- expect(showRepositoryAccessDuringSetup('flue', 'disconnected')).toBe(false)
- expect(showRepositoryAccessDuringSetup('flue', 'active')).toBe(true)
- })
-
- it('detects narrowing without treating expansion as narrowing', () => {
- expect(
- isNarrowingRepositoryAccess(
- { mode: 'all' },
- { mode: 'selected', repository_ids: ['repo_1'] },
- ),
- ).toBe(true)
- expect(
- isNarrowingRepositoryAccess(
- { mode: 'selected', repository_ids: ['repo_1'] },
- { mode: 'all' },
- ),
- ).toBe(false)
- expect(
- isNarrowingRepositoryAccess(
- { mode: 'selected', repository_ids: ['repo_1', 'repo_hidden'] },
- { mode: 'selected', repository_ids: ['repo_1'] },
- ),
- ).toBe(true)
- })
-
- it('preserves a hidden selection when toggling a visible repository', () => {
- expect(
- toggleSelectedRepository(
- {
- mode: 'selected',
- repository_ids: ['repo_hidden', 'repo_visible'],
- },
- 'repo_new',
- true,
- ),
- ).toEqual({
- mode: 'selected',
- repository_ids: ['repo_hidden', 'repo_new', 'repo_visible'],
- })
- })
-
- it('merges candidates by stable id and ignores unregistered rows', () => {
- const candidates = repositoryAccessCandidates(
- {
- policy: { mode: 'selected', repository_ids: ['repo_1'] },
- grant: {
- status: 'active',
- account: 'acme',
- repository_selection: 'selected',
- install_url: 'https://github.test/install',
- configure_url: null,
- truncated: false,
- },
- effective_repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/renamed',
- default_branch: 'main',
- private: true,
- },
- ],
- unavailable_selected_repositories: [],
- },
- {
- installed: true,
- install_url: null,
- configure_url: null,
- account: 'acme',
- repository_selection: 'selected',
- repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/old-name',
- default_branch: 'trunk',
- private: true,
- linked_sources: [],
- },
- {
- id: null,
- full_name: 'acme/unregistered',
- default_branch: 'main',
- private: false,
- linked_sources: [],
- },
- ],
- },
- )
- expect(candidates).toEqual([
- {
- id: 'repo_1',
- full_name: 'acme/renamed',
- default_branch: 'main',
- private: true,
- },
- ])
- })
-})
diff --git a/web/src/lib/repository-access.ts b/web/src/lib/repository-access.ts
deleted file mode 100644
index eab3fc5e..00000000
--- a/web/src/lib/repository-access.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-import type {
- DeployApp,
- RepositoryAccess,
- RepositoryAccessPolicy,
- RepositoryAccessRepository,
-} from '@/api/client'
-
-export const repositoryAccessQueryKey = (agentId: string) =>
- ['agent-repository-access', agentId] as const
-
-/** Built-in runtimes can configure repository scope before Slack. Flue keeps
- * its established guided order, which reveals repository access after managed
- * Slack is active. */
-export function showRepositoryAccessDuringSetup(
- runtime: string | null | undefined,
- managedSlackStatus: string | null | undefined,
-): boolean {
- return runtime !== 'flue' || managedSlackStatus === 'active'
-}
-
-export function selectedRepositoryIds(
- policy: RepositoryAccessPolicy,
-): string[] {
- return policy.mode === 'selected' ? policy.repository_ids : []
-}
-
-export function isNarrowingRepositoryAccess(
- previous: RepositoryAccessPolicy,
- next: RepositoryAccessPolicy,
-): boolean {
- if (previous.mode === 'all') return next.mode === 'selected'
- if (next.mode === 'all') return false
- const nextIds = new Set(next.repository_ids)
- return previous.repository_ids.some((id) => !nextIds.has(id))
-}
-
-export function sameRepositoryAccessPolicy(
- left: RepositoryAccessPolicy,
- right: RepositoryAccessPolicy,
-): boolean {
- if (left.mode !== right.mode) return false
- if (left.mode === 'all' || right.mode === 'all') return true
- if (left.repository_ids.length !== right.repository_ids.length) return false
- const rightIds = new Set(right.repository_ids)
- return left.repository_ids.every((id) => rightIds.has(id))
-}
-
-/**
- * Repository-access is authoritative for policy and effective access. The
- * org-scoped deploy-app response only fills the editor's candidate catalog so
- * selected mode can be expanded. Identity is always the stable repo id.
- */
-export function repositoryAccessCandidates(
- access: RepositoryAccess,
- deployApp?: DeployApp,
-): RepositoryAccessRepository[] {
- const byId = new Map<string, RepositoryAccessRepository>()
- for (const repo of deployApp?.repositories ?? []) {
- if (!repo.id) continue
- byId.set(repo.id, {
- id: repo.id,
- full_name: repo.full_name,
- default_branch: repo.default_branch ?? 'main',
- private: repo.private ?? true,
- })
- }
- for (const repo of access.effective_repositories ?? [])
- byId.set(repo.id, repo)
- for (const repo of access.unavailable_selected_repositories) {
- if (!byId.has(repo.id)) {
- byId.set(repo.id, {
- ...repo,
- default_branch: 'main',
- private: true,
- })
- }
- }
- return [...byId.values()].sort((a, b) =>
- a.full_name.localeCompare(b.full_name),
- )
-}
-
-export function toggleSelectedRepository(
- policy: RepositoryAccessPolicy,
- repositoryId: string,
- checked: boolean,
-): RepositoryAccessPolicy {
- const ids = new Set(selectedRepositoryIds(policy))
- if (checked) ids.add(repositoryId)
- else ids.delete(repositoryId)
- return { mode: 'selected', repository_ids: [...ids].sort() }
-}
diff --git a/web/src/lib/repository-onboarding.test.ts b/web/src/lib/repository-onboarding.test.ts
deleted file mode 100644
index 0c8719a3..00000000
--- a/web/src/lib/repository-onboarding.test.ts
+++ /dev/null
@@ -1,181 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import { ApiError, type RepositorySourceInspection } from '@/api/client'
-import {
- normalizeRepositoryRoot,
- repositoryReviewPresentation,
- repositorySeedFromState,
- sourceChangedRequiresReview,
-} from './repository-onboarding'
-
-const common = {
- repository: {
- id: 'repo_0123456789abcdef01234567',
- full_name: 'example/agent',
- default_branch: 'main',
- },
- root: '',
- production_ref: 'main',
- sha: 'a'.repeat(40),
- profile: null,
- review_fingerprint: `sha256:${'b'.repeat(64)}`,
- candidate_roots: [],
- candidate_roots_truncated: false,
-} satisfies Omit<RepositorySourceInspection, 'interpretation' | 'profile'> & {
- profile: null
-}
-
-describe('repository onboarding presentation', () => {
- it('matches linked roots after harmless path formatting differences', () => {
- expect(normalizeRepositoryRoot(' agents//support/ ')).toBe(
- 'agents/support',
- )
- expect(normalizeRepositoryRoot('')).toBe('')
- })
-
- it('keeps invalid Flue authoritative and recoverable by re-review', () => {
- const presentation = repositoryReviewPresentation({
- ...common,
- interpretation: {
- disposition: 'invalid',
- source_profile: 'flue-app-v1',
- source_profile_version: 1,
- summary: 'Flue manifest is missing',
- reason_code: 'flue_manifest_missing',
- issues: [
- {
- code: 'flue_manifest_missing',
- message: 'Add agent.toml to this Flue root.',
- },
- ],
- },
- })
-
- expect(presentation).toMatchObject({
- heading: 'This Flue agent needs a fix',
- primaryAction: 'review_again',
- })
- })
-
- it('offers explicit candidate selection without auto-selecting a root', () => {
- const presentation = repositoryReviewPresentation({
- ...common,
- interpretation: {
- disposition: 'unrecognized',
- source_profile: null,
- source_profile_version: null,
- summary: "We couldn't find an agent definition in this folder",
- reason_code: 'unrecognized_source',
- },
- candidate_roots: [
- {
- path: 'agents/support',
- source_profile: null,
- summary: 'Agent manifest found',
- marker: 'agent.toml',
- },
- ],
- })
-
- expect(presentation).toEqual({
- heading: 'Agent definitions found in other folders',
- explanation:
- 'Choose a repository root to review. OpenComputer will never select one for you.',
- primaryAction: 'choose_folder',
- })
- })
-
- it('explains how to make an unrecognized folder deployable', () => {
- const presentation = repositoryReviewPresentation({
- ...common,
- interpretation: {
- disposition: 'unrecognized',
- source_profile: null,
- source_profile_version: null,
- summary: "We couldn't find an agent definition in this folder",
- reason_code: 'unrecognized_source',
- },
- })
-
- expect(presentation.explanation).toContain('agent.toml')
- })
-
- it('presents an exact prompt-defined Flue agent without implying source code', () => {
- const presentation = repositoryReviewPresentation({
- ...common,
- interpretation: {
- disposition: 'exact',
- source_profile: 'flue-prompt-v1',
- source_profile_version: 1,
- summary: 'Prompt-defined Flue agent detected',
- reason_code: 'flue_prompt_detected',
- assumptions: [],
- agent: { runtime: 'flue', model: 'anthropic/claude-haiku-4-5' },
- },
- profile: {
- source_profile: 'flue-prompt-v1',
- source_profile_version: 1,
- manifest: {
- schema_version: 1,
- entrypoint: 'support',
- model: 'anthropic/claude-haiku-4-5',
- runtime: { family: 'flue', type: 'default' },
- vars: {},
- },
- package: {
- name: 'opencomputer-flue-prompt-agent',
- node_engine: '>=22.19 <23',
- flue_cli: '1.0.0-beta.9',
- },
- lockfile: { version: 3 },
- builder: {
- node: '22.19.0',
- synthesis_template: 'flue-prompt-template-v1',
- },
- source: { files: 3, bytes: 1024 },
- prompt: { bytes: 128 },
- skills: { count: 1, bytes: 512, names: ['triage'] },
- variable_names: [],
- warnings: [],
- },
- })
-
- expect(presentation).toEqual({
- heading: 'Prompt-defined Flue agent',
- explanation:
- 'OpenComputer will turn this prompt and its skills into a Flue app at build time.',
- primaryAction: 'deploy',
- })
- })
-
- it('requires a fresh review for the typed source-change conflict', () => {
- expect(
- sourceChangedRequiresReview(
- new ApiError('Repository changed', 409, 'source_changed_re_review'),
- ),
- ).toBe(true)
- expect(
- sourceChangedRequiresReview(
- new ApiError('Conflict', 409, 'name_conflict'),
- ),
- ).toBe(false)
- })
-
- it('accepts only a bounded same-origin source handoff', () => {
- const seed = {
- repo: 'repo_0123456789abcdef01234567',
- path: 'agents/support',
- productionRef: 'main',
- }
- expect(repositorySeedFromState({ repositoryImport: seed })).toEqual(seed)
- expect(
- repositorySeedFromState({
- repositoryImport: { ...seed, path: '../other-agent' },
- }),
- ).toBeUndefined()
- expect(
- repositorySeedFromState({
- repositoryImport: { ...seed, repo: 'example/support' },
- }),
- ).toBeUndefined()
- })
-})
diff --git a/web/src/lib/repository-onboarding.ts b/web/src/lib/repository-onboarding.ts
deleted file mode 100644
index 83257ad2..00000000
--- a/web/src/lib/repository-onboarding.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { ApiError, type RepositorySourceInspection } from '@/api/client'
-
-export type RepositoryReviewPresentation = {
- heading: string
- explanation: string
- primaryAction: 'deploy' | 'review_again' | 'choose_folder'
-}
-
-export type RepositorySeed = {
- repo: string
- path: string
- productionRef: string
-}
-
-export function isValidRepositoryRoot(root: string): boolean {
- if (
- root.length > 1024 ||
- root.includes('\0') ||
- root.includes('\\') ||
- root.startsWith('/')
- )
- return false
- return !root
- .split('/')
- .filter(Boolean)
- .some((part) => part === '.' || part === '..')
-}
-
-/** Mirrors the server's repository-root canonicalization for local conflict
- * presentation only. Review/import still re-normalize and enforce it. */
-export function normalizeRepositoryRoot(root: string): string {
- return root.trim().split('/').filter(Boolean).join('/')
-}
-
-/** Read the bounded same-origin handoff used after a confirmed source unlink. */
-export function repositorySeedFromState(
- value: unknown,
-): RepositorySeed | undefined {
- if (!value || typeof value !== 'object' || Array.isArray(value)) return
- const seed = (value as { repositoryImport?: unknown }).repositoryImport
- if (!seed || typeof seed !== 'object' || Array.isArray(seed)) return
- const candidate = seed as Record<string, unknown>
- if (
- typeof candidate.repo !== 'string' ||
- !/^repo_[a-z0-9]{24}$/.test(candidate.repo) ||
- typeof candidate.path !== 'string' ||
- !isValidRepositoryRoot(candidate.path) ||
- typeof candidate.productionRef !== 'string' ||
- !candidate.productionRef.trim() ||
- candidate.productionRef.length > 255
- ) {
- return
- }
- return {
- repo: candidate.repo,
- path: candidate.path,
- productionRef: candidate.productionRef,
- }
-}
-
-/** Canonical user-facing state for the server's repository interpretation. */
-export function repositoryReviewPresentation(
- inspection: RepositorySourceInspection,
-): RepositoryReviewPresentation {
- switch (inspection.interpretation.disposition) {
- case 'exact':
- return inspection.interpretation.source_profile === 'flue-prompt-v1'
- ? {
- heading: 'Prompt-defined Flue agent',
- explanation:
- 'OpenComputer will turn this prompt and its skills into a Flue app at build time.',
- primaryAction: 'deploy',
- }
- : {
- heading: 'Flue app detected',
- explanation:
- 'Review the detected entrypoint, model, and agent name.',
- primaryAction: 'deploy',
- }
- case 'invalid':
- return {
- heading: 'This Flue agent needs a fix',
- explanation:
- 'OpenComputer found a Flue definition, but it is not deployable yet. It was not treated as another agent type.',
- primaryAction: 'review_again',
- }
- case 'unrecognized':
- return inspection.candidate_roots.length
- ? {
- heading: 'Agent definitions found in other folders',
- explanation:
- 'Choose a repository root to review. OpenComputer will never select one for you.',
- primaryAction: 'choose_folder',
- }
- : {
- heading: "We couldn't find an agent definition in this folder",
- explanation:
- 'Add an agent.toml next to prompt.md, choose another folder, or start from the Flue app template.',
- primaryAction: 'choose_folder',
- }
- }
-}
-
-export function sourceChangedRequiresReview(error: unknown): boolean {
- return error instanceof ApiError && error.type === 'source_changed_re_review'
-}
diff --git a/web/src/lib/runtimes.ts b/web/src/lib/runtimes.ts
deleted file mode 100644
index 369b8737..00000000
--- a/web/src/lib/runtimes.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-// The runtimes the dashboard exposes, with their models + credential provider.
-// `claude` and `codex` each pair with one provider (claude→anthropic, codex→openai);
-// `pi` drives any provider, so for pi the provider comes from the selected model's
-// `provider/` prefix, not the runtime — see providerForModel + keyFieldFor, which the
-// create dialog uses so a pi agent's key field follows its model. More runtimes (and
-// models) land here as they ship.
-
-export type RuntimeModel = { value: string; label: string }
-
-export type RuntimeOption = {
- value: string // the API `runtime` value
- label: string
- provider: string // credential provider + model-id prefix
- keyLabel: string // label for the inline "new credential" key field
- keyPlaceholder: string
- // Models are listed most-powerful-first within each provider. `defaultModel`
- // is the one a new agent preselects (else models[0]) — so the list can be
- // power-ordered while the default stays a mid-tier pick.
- defaultModel?: string
- models: RuntimeModel[]
-}
-
-export const RUNTIMES: RuntimeOption[] = [
- {
- value: 'claude',
- label: 'Claude',
- provider: 'anthropic',
- keyLabel: 'Anthropic API key',
- keyPlaceholder: 'sk-ant-…',
- // Power-ordered; Sonnet 5 is the preselected default for new agents.
- defaultModel: 'anthropic/claude-sonnet-5',
- models: [
- { value: 'anthropic/claude-opus-4-8', label: 'Claude Opus 4.8' },
- { value: 'anthropic/claude-sonnet-5', label: 'Claude Sonnet 5' },
- { value: 'anthropic/claude-fable-5', label: 'Claude Fable 5' },
- { value: 'anthropic/claude-haiku-4-5', label: 'Claude Haiku 4.5' },
- ],
- },
- {
- value: 'codex',
- label: 'Codex',
- provider: 'openai',
- keyLabel: 'OpenAI API key',
- keyPlaceholder: 'sk-…',
- // The API only validates the `openai/` prefix — any model OpenAI serves works;
- // this is UI curation. A range mirroring the Claude tiers: codex-optimized
- // default, frontier, value, fastest. (Verified against OpenAI's model list.)
- models: [
- { value: 'openai/gpt-5.3-codex', label: 'GPT-5.3 Codex' },
- { value: 'openai/gpt-5.5', label: 'GPT-5.5' },
- { value: 'openai/gpt-5.4-mini', label: 'GPT-5.4 Mini' },
- { value: 'openai/gpt-5.4-nano', label: 'GPT-5.4 Nano' },
- ],
- },
- {
- value: 'pi',
- label: 'Pi',
- // Pi drives ANY provider — this `provider` is only the default (the first model's
- // prefix) for defaultModelFor/fallbacks. The create form derives the ACTUAL provider
- // from the selected model via providerForModel, since a pi agent's provider (and so
- // its key field + credential list) varies by model.
- provider: 'anthropic',
- keyLabel: 'Model provider API key',
- keyPlaceholder: 'API key',
- // Anthropic-only TODAY (what prod validates for pi). The runtime is built
- // provider-agnostic; other providers' models land here when the platform accepts
- // them (the create dialog already groups by provider via withModelGroups).
- defaultModel: 'anthropic/claude-sonnet-5',
- models: [
- { value: 'anthropic/claude-opus-4-8', label: 'Claude Opus 4.8' },
- { value: 'anthropic/claude-sonnet-5', label: 'Claude Sonnet 5' },
- { value: 'anthropic/claude-fable-5', label: 'Claude Fable 5' },
- { value: 'anthropic/claude-haiku-4-5', label: 'Claude Haiku 4.5' },
- ],
- },
-]
-
-// Key-field copy per provider. Pi mixes providers within one runtime, so the create
-// dialog keys the credential field off the selected model's provider, not the runtime.
-export const PROVIDER_KEY_FIELDS: Record<string, { keyLabel: string; keyPlaceholder: string }> = {
- anthropic: { keyLabel: 'Anthropic API key', keyPlaceholder: 'sk-ant-…' },
- openai: { keyLabel: 'OpenAI API key', keyPlaceholder: 'sk-…' },
- google: { keyLabel: 'Google AI API key', keyPlaceholder: 'AIza…' },
- openrouter: { keyLabel: 'OpenRouter API key', keyPlaceholder: 'sk-or-…' },
-}
-
-export const DEFAULT_RUNTIME = RUNTIMES[0].value
-
-// Display labels for EVERY runtime a session can report — a superset of the create
-// picker (RUNTIMES). `flue` is intentionally NOT in RUNTIMES (its behavior ships in a
-// deployed artifact — there's no model/key to pick here), but read-only views must
-// still label it correctly instead of falling back to "Claude". `hands` is the
-// tool-sandbox runtime, shown only if it ever surfaces on a session.
-export const RUNTIME_LABELS: Record<string, string> = {
- claude: 'Claude',
- codex: 'Codex',
- pi: 'Pi',
- flue: 'Flue',
- hands: 'Hands',
-}
-
-// A stable label for any runtime string (display-only — does NOT gate the create picker).
-export function runtimeLabel(runtime: string | null | undefined): string {
- if (!runtime) return '—'
- return RUNTIME_LABELS[runtime] ?? runtime
-}
-
-export const runtimeOptions = RUNTIMES.map((r) => ({
- value: r.value,
- label: r.label,
-}))
-
-// Falls back to the first runtime for an unknown/loading value, so callers can pass
-// `agent?.runtime` safely.
-export function getRuntime(value: string | undefined): RuntimeOption {
- return RUNTIMES.find((r) => r.value === value) ?? RUNTIMES[0]
-}
-
-export function defaultModelFor(runtime: string): string {
- const rt = getRuntime(runtime)
- return rt.defaultModel ?? rt.models[0].value
-}
-
-// The provider a model runs on is its `provider/` prefix — the API's source of truth.
-// Works for every runtime: claude/codex models all share one prefix; pi's vary.
-export function providerForModel(model: string): string {
- return model.split('/')[0] || ''
-}
-
-// The key-field copy for a provider, with a generic fallback for uncurated providers.
-export function keyFieldFor(provider: string): { keyLabel: string; keyPlaceholder: string } {
- return PROVIDER_KEY_FIELDS[provider] ?? { keyLabel: 'Model provider API key', keyPlaceholder: 'API key' }
-}
-
-// A Select option that is either a model or a group divider.
-export type ModelSelectOption = RuntimeModel | { separator: true }
-
-// Insert a divider between consecutive models from different providers, so a
-// multi-provider runtime's dropdown (pi) reads as grouped without vendor labels.
-// Single-provider runtimes (claude/codex) have no boundary, so nothing changes.
-export function withModelGroups(models: RuntimeModel[]): ModelSelectOption[] {
- const out: ModelSelectOption[] = []
- let prev: string | null = null
- for (const m of models) {
- const p = providerForModel(m.value)
- if (prev !== null && p !== prev) out.push({ separator: true })
- out.push(m)
- prev = p
- }
- return out
-}
diff --git a/web/src/lib/session-source-polling.ts b/web/src/lib/session-source-polling.ts
deleted file mode 100644
index 286c46d1..00000000
--- a/web/src/lib/session-source-polling.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import type { Session, SessionSource } from '@/api/client'
-
-const ACTIVE_SOURCE_STATUSES = new Set(['pending', 'materializing'])
-const LIVE_SESSION_STATUSES = new Set([
- 'queued',
- 'running',
- 'awaiting_input',
- 'idle',
-])
-
-export function isFlueSession(
- session: Pick<Session, 'agent_snapshot'> | undefined,
-): boolean {
- return session?.agent_snapshot?.runtime === 'flue'
-}
-
-export function canSessionChangeFlueSources(
- session: Pick<Session, 'status' | 'agent_snapshot'> | undefined,
-): boolean {
- if (!session || !isFlueSession(session)) return false
- return LIVE_SESSION_STATUSES.has(session.status)
-}
-
-/**
- * Empty sessions keep a slow watch for the first lazy Flue checkout. Active
- * materialization polls quickly. Terminal sources return to the slow watch so
- * a later turn adding another source still appears. React Query pauses these
- * intervals while the page is backgrounded.
- */
-export function sessionSourcesRefetchInterval(
- sources: SessionSource[] | undefined,
-): number {
- if (sources?.some((source) => ACTIVE_SOURCE_STATUSES.has(source.status)))
- return 1_500
- return 5_000
-}
diff --git a/web/src/lib/session-turns.test.ts b/web/src/lib/session-turns.test.ts
deleted file mode 100644
index a3801937..00000000
--- a/web/src/lib/session-turns.test.ts
+++ /dev/null
@@ -1,270 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import type { SessionEvent } from '@/api/client'
-import { groupIntoTurns, httpRequestPayloadText } from './session-turns'
-
-function event(
- seq: number,
- type: string,
- overrides: Partial<SessionEvent> = {},
-): SessionEvent {
- return {
- id: `evt_${seq}_${type.replace(/\./g, '_')}`,
- seq,
- type,
- level: type.endsWith('message') ? 'user' : 'progress',
- body: {},
- ...overrides,
- }
-}
-
-describe('groupIntoTurns', () => {
- it('groups a normal brain-box turn by its explicit input bounds', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- body: { text: 'hello' },
- turn_id: null,
- }),
- event(2, 'turn.started', {
- turn_id: 'trn_brain',
- body: { input_from_seq: 1, input_to_seq: 1 },
- }),
- event(3, 'agent.message', {
- turn_id: 'trn_brain',
- body: { text: 'hi' },
- }),
- event(4, 'turn.completed', {
- turn_id: 'trn_brain',
- body: { yield_reason: 'completed' },
- }),
- ])
-
- expect(timeline.pending).toEqual([])
- expect(timeline.groups).toHaveLength(1)
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_brain',
- fromSeq: 1,
- toSeq: 1,
- state: 'completed',
- yieldReason: 'completed',
- })
- expect(timeline.groups[0]?.events.map((item) => item.seq)).toEqual([1, 3])
- })
-
- it('uses the platform turn id and neutral outcome for a new Flue turn', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- turn_id: 'trn_platform',
- body: { text: 'triage this' },
- }),
- event(2, 'turn.started', {
- turn_id: 'trn_platform',
- body: {
- turn_id: 'trn_platform',
- input_from_seq: 1,
- input_to_seq: 1,
- },
- }),
- event(3, 'agent.message', {
- turn_id: 'trn_platform',
- body: { text: 'done' },
- }),
- event(4, 'turn.completed', {
- turn_id: 'trn_platform',
- level: 'user',
- body: {
- turn_id: 'trn_platform',
- outcome: 'quiescent',
- result_event_id: 'evt_3_agent_message',
- },
- }),
- ])
-
- expect(timeline.pending).toEqual([])
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_platform',
- state: 'completed',
- yieldReason: 'quiescent',
- })
- expect(timeline.groups[0]).not.toHaveProperty('inferredBounds')
- expect(timeline.groups[0]?.events.map((item) => item.seq)).toEqual([1, 3])
- })
-
- it('repairs the production preview start that omitted input bounds', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- turn_id: null,
- body: { text: 'how are we doing' },
- }),
- event(2, 'turn.started', {
- turn_id: 'trn_flue_preview',
- body: { submission_id: 'sub_preview' },
- }),
- event(3, 'agent.message', {
- turn_id: 'trn_flue_preview',
- body: { text: 'all good' },
- }),
- event(4, 'turn.completed', {
- turn_id: 'trn_flue_preview',
- level: 'user',
- body: { outcome: 'quiescent' },
- }),
- ])
-
- expect(timeline.pending).toEqual([])
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_flue_preview',
- fromSeq: 1,
- toSeq: 1,
- inferredBounds: true,
- state: 'completed',
- })
- expect(timeline.groups[0]?.events.map((item) => item.seq)).toEqual([1, 3])
- })
-
- it('keeps a completion-only failure visible with its error', () => {
- const timeline = groupIntoTurns([
- event(7, 'turn.completed', {
- turn_id: 'trn_failed',
- level: 'user',
- body: {
- outcome: 'error',
- error: { code: 'admission_rejected', message: 'tenant rejected it' },
- },
- }),
- ])
-
- expect(timeline.groups).toEqual([
- expect.objectContaining({
- turnId: 'trn_failed',
- state: 'error',
- errorMessage: 'admission_rejected: tenant rejected it',
- events: [],
- }),
- ])
- })
-
- it('leaves a follow-up queued until a new turn claims it', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- turn_id: null,
- body: { text: 'first' },
- }),
- event(2, 'turn.started', {
- turn_id: 'trn_first',
- body: { input_from_seq: 1, input_to_seq: 1 },
- }),
- event(3, 'user.message', {
- source: 'client',
- turn_id: null,
- body: { text: 'second' },
- }),
- ])
-
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_first',
- state: 'running',
- })
- expect(timeline.pending.map((item) => item.seq)).toEqual([3])
- })
-
- it('shows a new accepted input as queued before turn.started exists', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- turn_id: 'trn_accepted',
- body: { text: 'start' },
- }),
- ])
-
- expect(timeline.pending).toEqual([])
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_accepted',
- state: 'queued',
- })
- })
-
- it('groups and preserves structured HTTP input', () => {
- const input = event(1, 'http.request', {
- source: 'http',
- turn_id: 'trn_http',
- actor: { id: 'hk_test', type: 'trigger', display: 'grafana-prod' },
- body: { payload: { severity: 'critical', count: 2 } },
- })
- const timeline = groupIntoTurns([input])
-
- expect(timeline.pending).toEqual([])
- expect(timeline.groups[0]).toMatchObject({
- turnId: 'trn_http',
- state: 'queued',
- events: [input],
- })
- expect(httpRequestPayloadText(input)).toBe(
- '{\n "severity": "critical",\n "count": 2\n}',
- )
- })
-
- it('deduplicates history and SSE copies and cannot regress on arrival order', () => {
- const input = event(1, 'user.message', {
- source: 'client',
- turn_id: 'trn_ordered',
- body: { text: 'go' },
- })
- const started = event(2, 'turn.started', {
- turn_id: 'trn_ordered',
- body: { input_from_seq: 1, input_to_seq: 1 },
- })
- const answer = event(3, 'agent.message', {
- turn_id: 'trn_ordered',
- body: { text: 'done' },
- })
- const completed = event(4, 'turn.completed', {
- turn_id: 'trn_ordered',
- body: { outcome: 'quiescent' },
- })
-
- const timeline = groupIntoTurns([
- completed,
- answer,
- input,
- started,
- completed,
- answer,
- ])
-
- expect(timeline.groups).toHaveLength(1)
- expect(timeline.groups[0]?.state).toBe('completed')
- expect(timeline.groups[0]?.events.map((item) => item.id)).toEqual([
- input.id,
- answer.id,
- ])
- })
-
- it('never steals an input already owned by an explicit range', () => {
- const timeline = groupIntoTurns([
- event(1, 'user.message', {
- source: 'client',
- turn_id: null,
- body: { text: 'owned' },
- }),
- event(2, 'turn.started', {
- turn_id: 'trn_explicit',
- body: { input_from_seq: 1, input_to_seq: 1 },
- }),
- event(3, 'turn.started', {
- turn_id: 'trn_legacy',
- body: { submission_id: 'sub_later' },
- }),
- ])
-
- expect(
- timeline.groups.find((group) => group.turnId === 'trn_explicit')?.events,
- ).toHaveLength(1)
- expect(
- timeline.groups.find((group) => group.turnId === 'trn_legacy')?.events,
- ).toHaveLength(0)
- })
-})
diff --git a/web/src/lib/session-turns.ts b/web/src/lib/session-turns.ts
deleted file mode 100644
index 4f51a5a8..00000000
--- a/web/src/lib/session-turns.ts
+++ /dev/null
@@ -1,317 +0,0 @@
-import type { SessionEvent } from '@/api/client'
-
-// Pure, React-free reconstruction of the durable event log into neutral OC turns.
-// New inputs already carry their platform turn id. Older brain-box and preview
-// Flue inputs may need explicit seq bounds or the conservative legacy fallback.
-
-export type TurnState =
- | 'queued'
- | 'running'
- | 'completed'
- | 'error'
- | 'canceled'
-
-export interface TurnGroup {
- turnId: string
- fromSeq: number | null
- toSeq: number | null
- state: TurnState
- yieldReason?: string
- errorMessage?: string
- inferredBounds?: boolean
- // seq-ordered inputs and outputs; lifecycle markers stay as group metadata.
- events: SessionEvent[]
-}
-
-export interface GroupedTimeline {
- groups: TurnGroup[]
- // Inputs with no authoritative or unambiguous inferred owner.
- pending: SessionEvent[]
-}
-
-interface MutableTurn extends TurnGroup {
- firstSeq: number
- startSeq: number | null
- completion: SessionEvent | null
-}
-
-const FAILURE_OUTCOMES = new Set([
- 'error',
- 'failed',
- 'deadline_exceeded',
- 'max_turns',
- 'budget_exceeded',
-])
-
-const TERMINAL_SESSION_STATUSES = new Set([
- 'idle',
- 'awaiting_input',
- 'failed',
- 'archived',
-])
-
-function record(value: unknown): Record<string, unknown> {
- return value && typeof value === 'object' && !Array.isArray(value)
- ? (value as Record<string, unknown>)
- : {}
-}
-
-// body is unknown (inline JSON <=32KB); pull the common { text } shape defensively.
-export function bodyText(ev: SessionEvent): string | null {
- const text = record(ev.body).text
- return typeof text === 'string' ? text : null
-}
-
-// HTTP invocation bodies stay structured in the durable event log. Render the
-// authoritative payload rather than the adapter's derived model-input string.
-export function httpRequestPayloadText(ev: SessionEvent): string | null {
- if (ev.type !== 'http.request') return null
- const body = record(ev.body)
- if (!Object.prototype.hasOwnProperty.call(body, 'payload')) return null
- try {
- return JSON.stringify(body.payload, null, 2) ?? null
- } catch {
- return null
- }
-}
-
-// The runtime's failPreExec emits an agent.message tagged with an
-// insufficient_credits code so the UI can offer the upgrade-to-Pro paywall.
-export function isOutOfCredits(ev: SessionEvent): boolean {
- return (
- ev.type === 'agent.message' &&
- record(ev.body).code === 'insufficient_credits'
- )
-}
-
-export function isTurnInput(ev: SessionEvent): boolean {
- return (
- ev.type === 'http.request' ||
- ev.type === 'user.message' ||
- ev.source === 'client' ||
- ev.source === 'github'
- )
-}
-
-export function isTerminalSessionStatus(status?: string): boolean {
- return status != null && TERMINAL_SESSION_STATUSES.has(status)
-}
-
-// Reads input_from_seq/input_to_seq off a turn.started body, coercing legacy
-// string seqs. A partial or invalid range is not authoritative.
-export function turnBounds(ev: SessionEvent): {
- from: number | null
- to: number | null
-} {
- const body = record(ev.body)
- const num = (value: unknown) => {
- if (value == null) return null
- const parsed = Number(value)
- return Number.isFinite(parsed) ? parsed : null
- }
- return { from: num(body.input_from_seq), to: num(body.input_to_seq) }
-}
-
-function turnIdOf(ev: SessionEvent): string | null {
- if (typeof ev.turn_id === 'string' && ev.turn_id) return ev.turn_id
- const bodyTurnId = record(ev.body).turn_id
- return typeof bodyTurnId === 'string' && bodyTurnId ? bodyTurnId : null
-}
-
-function completionOutcome(ev: SessionEvent): string {
- const body = record(ev.body)
- const raw =
- typeof body.outcome === 'string'
- ? body.outcome
- : typeof body.yield_reason === 'string'
- ? body.yield_reason
- : ''
- return raw.toLowerCase()
-}
-
-function completionState(ev: SessionEvent): TurnState {
- const outcome = completionOutcome(ev)
- if (outcome === 'canceled' || outcome === 'cancelled') return 'canceled'
- if (FAILURE_OUTCOMES.has(outcome)) return 'error'
- return 'completed'
-}
-
-function errorText(value: unknown): string | null {
- if (typeof value === 'string' && value) return value
- if (typeof value === 'number' || typeof value === 'boolean') {
- return String(value)
- }
- if (!value || typeof value !== 'object' || Array.isArray(value)) return null
- const error = value as Record<string, unknown>
- const code = typeof error.code === 'string' ? error.code : null
- const message = [error.message, error.error, error.detail].find(
- (candidate): candidate is string =>
- typeof candidate === 'string' && candidate.length > 0,
- )
- if (code && message) return `${code}: ${message}`
- if (message) return message
- if (code) return code
- try {
- return JSON.stringify(value)
- } catch {
- return null
- }
-}
-
-function completionError(ev: SessionEvent): string | null {
- const body = record(ev.body)
- return (
- errorText(body.error) ?? errorText(body.message) ?? errorText(body.detail)
- )
-}
-
-export function groupIntoTurns(input: SessionEvent[]): GroupedTimeline {
- // History and SSE intentionally overlap. Event id is the durable identity;
- // the later copy wins and seq ordering makes arrival order irrelevant.
- const deduped = new Map<string, SessionEvent>()
- for (const event of input) deduped.set(event.id, event)
- const sorted = [...deduped.values()].sort(
- (a, b) => a.seq - b.seq || a.id.localeCompare(b.id),
- )
-
- const byTurn = new Map<string, MutableTurn>()
- const ensureTurn = (turnId: string, seq: number): MutableTurn => {
- const existing = byTurn.get(turnId)
- if (existing) {
- existing.firstSeq = Math.min(existing.firstSeq, seq)
- return existing
- }
- const created: MutableTurn = {
- turnId,
- fromSeq: null,
- toSeq: null,
- state: 'queued',
- events: [],
- firstSeq: seq,
- startSeq: null,
- completion: null,
- }
- byTurn.set(turnId, created)
- return created
- }
-
- // Lifecycle pass. Completion is authoritative even if it arrived before
- // history or its start marker in the browser.
- for (const event of sorted) {
- const turnId = turnIdOf(event)
- if (!turnId) continue
- const group = ensureTurn(turnId, event.seq)
- if (event.type === 'turn.started') {
- const bounds = turnBounds(event)
- group.startSeq =
- group.startSeq == null ? event.seq : Math.min(group.startSeq, event.seq)
- if (bounds.from != null && bounds.to != null) {
- group.fromSeq = bounds.from
- group.toSeq = bounds.to
- }
- } else if (
- event.type === 'turn.completed' &&
- (!group.completion || event.seq >= group.completion.seq)
- ) {
- group.completion = event
- }
- }
-
- const claimedInputs = new Set<string>()
-
- // Direct turn ids are strongest. New OC inputs use this path, as do outputs.
- for (const event of sorted) {
- if (event.type === 'turn.started' || event.type === 'turn.completed')
- continue
- const turnId = turnIdOf(event)
- if (!turnId) continue
- const group = ensureTurn(turnId, event.seq)
- group.events.push(event)
- if (isTurnInput(event)) claimedInputs.add(event.id)
- }
-
- const inputs = sorted.filter(isTurnInput)
-
- // Older inputs have no turn id. Explicit inclusive bounds remain authoritative.
- for (const event of inputs) {
- if (claimedInputs.has(event.id)) continue
- const owners = [...byTurn.values()].filter(
- (group) =>
- group.fromSeq != null &&
- group.toSeq != null &&
- event.seq >= group.fromSeq &&
- event.seq <= group.toSeq,
- )
- const owner = owners.length === 1 ? owners[0] : undefined
- if (!owner) continue
- owner.events.push(event)
- owner.firstSeq = Math.min(owner.firstSeq, event.seq)
- claimedInputs.add(event.id)
- }
-
- // One-release preview fallback. Only a real start with both bounds absent
- // may claim the nearest earlier input, and never one already owned elsewhere.
- const legacyStarts = [...byTurn.values()]
- .filter(
- (group) =>
- group.startSeq != null &&
- group.fromSeq == null &&
- group.toSeq == null &&
- !group.events.some(isTurnInput),
- )
- .sort(
- (a, b) =>
- (a.startSeq ?? 0) - (b.startSeq ?? 0) ||
- a.turnId.localeCompare(b.turnId),
- )
- for (const group of legacyStarts) {
- const candidates = inputs.filter(
- (event) =>
- !claimedInputs.has(event.id) && event.seq < (group.startSeq ?? 0),
- )
- const candidate = candidates[candidates.length - 1]
- if (!candidate) continue
- group.events.push(candidate)
- group.fromSeq = candidate.seq
- group.toSeq = candidate.seq
- group.inferredBounds = true
- group.firstSeq = Math.min(group.firstSeq, candidate.seq)
- claimedInputs.add(candidate.id)
- }
-
- const pending = inputs.filter((event) => !claimedInputs.has(event.id))
-
- for (const group of byTurn.values()) {
- group.events.sort((a, b) => a.seq - b.seq || a.id.localeCompare(b.id))
- if (group.completion) {
- group.state = completionState(group.completion)
- const outcome = completionOutcome(group.completion)
- group.yieldReason = outcome || undefined
- if (group.state === 'error') {
- group.errorMessage = completionError(group.completion) ?? undefined
- }
- } else if (group.startSeq != null) {
- group.state = 'running'
- }
- }
-
- return {
- groups: [...byTurn.values()]
- .sort(
- (a, b) => a.firstSeq - b.firstSeq || a.turnId.localeCompare(b.turnId),
- )
- .map(
- (group): TurnGroup => ({
- turnId: group.turnId,
- fromSeq: group.fromSeq,
- toSeq: group.toSeq,
- state: group.state,
- events: group.events,
- ...(group.yieldReason ? { yieldReason: group.yieldReason } : {}),
- ...(group.errorMessage ? { errorMessage: group.errorMessage } : {}),
- ...(group.inferredBounds ? { inferredBounds: true } : {}),
- }),
- ),
- pending,
- }
-}
diff --git a/web/src/lib/source-profile-recovery.ts b/web/src/lib/source-profile-recovery.ts
deleted file mode 100644
index 8bc8e19d..00000000
--- a/web/src/lib/source-profile-recovery.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import type { DeploymentSource } from '@/api/schemas'
-
-export function sourceChangesUrl(
- source: Pick<DeploymentSource, 'full_name' | 'latest_seen_sha'>,
-): string | undefined {
- const parts = source.full_name?.split('/') ?? []
- if (parts.length !== 2 || parts.some((part) => !part)) return
- const repositoryUrl = `https://github.com/${parts.map(encodeURIComponent).join('/')}`
- return source.latest_seen_sha &&
- /^[0-9a-f]{40}$/i.test(source.latest_seen_sha)
- ? `${repositoryUrl}/commit/${source.latest_seen_sha}`
- : repositoryUrl
-}
diff --git a/web/src/lib/usage.test.ts b/web/src/lib/usage.test.ts
deleted file mode 100644
index 377034aa..00000000
--- a/web/src/lib/usage.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import {
- formatDuration,
- formatUsageCost,
- formatUsageDuration,
- formatUsageTokens,
- usageDisclosure,
-} from './usage'
-
-describe('canonical usage presentation', () => {
- it('renders complete session usage as exact values', () => {
- const usage = {
- active_seconds: 65,
- reported_turns: 1,
- unreported_turns: 0,
- complete: true,
- input_tokens: 10,
- output_tokens: 5,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- tokens: 15,
- total_cost_usd: 0.0042,
- attribution: 'exact' as const,
- }
-
- expect(formatUsageTokens(usage)).toBe('15')
- expect(formatUsageCost(usage)).toBe('$0.0042')
- expect(formatUsageDuration(usage)).toBe('1m 05s')
- expect(usageDisclosure(usage)).toBeNull()
- })
-
- it('marks incomplete totals and best-effort attribution', () => {
- const usage = {
- active_seconds: 4,
- reported_turns: 2,
- unreported_turns: 1,
- complete: false,
- tokens: 1234,
- total_cost_usd: 0.12,
- attribution: 'best_effort' as const,
- }
-
- expect(formatUsageTokens(usage)).toBe('≥1,234')
- expect(formatUsageCost(usage)).toBe('≥$0.120')
- expect(usageDisclosure(usage)).toBe(
- 'Lower bound · 1 turn did not report usage · Best-effort session attribution',
- )
- })
-
- it('marks a partially reported turn as a lower bound', () => {
- const usage = {
- reported: true as const,
- complete: false as const,
- input_tokens: 100,
- output_tokens: 20,
- cache_creation_input_tokens: 0,
- cache_read_input_tokens: 0,
- tokens: 120,
- }
-
- expect(formatUsageTokens(usage)).toBe('≥120')
- expect(usageDisclosure(usage)).toBe('Lower-bound usage')
- })
-
- it('keeps missing and historical usage unknown', () => {
- expect(formatUsageTokens({})).toBe('Unknown')
- expect(formatUsageCost({ reported: false })).toBe('Unknown')
- expect(formatUsageDuration(null)).toBe('Unknown')
- })
-
- it('formats long active durations compactly', () => {
- expect(formatDuration(0)).toBe('0s')
- expect(formatDuration(59)).toBe('59s')
- expect(formatDuration(3661)).toBe('1h 01m')
- })
-})
diff --git a/web/src/lib/usage.ts b/web/src/lib/usage.ts
deleted file mode 100644
index 009190b0..00000000
--- a/web/src/lib/usage.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import type { SessionUsage, TurnUsage } from '@/api/schemas'
-
-export type UsageLike = SessionUsage | TurnUsage | null | undefined
-
-function asRecord(value: UsageLike): Record<string, unknown> | null {
- return value !== null && typeof value === 'object' ? value : null
-}
-
-export function hasUsage(usage: UsageLike): boolean {
- const record = asRecord(usage)
- return record !== null && Object.keys(record).length > 0
-}
-
-export function usageCostUsd(usage: UsageLike): number | null {
- const record = asRecord(usage)
- if (!record) return null
- const value = record.total_cost_usd
- return typeof value === 'number' && Number.isFinite(value) ? value : null
-}
-
-export function usageTokens(usage: UsageLike): number | null {
- const record = asRecord(usage)
- if (!record) return null
- const value = record.tokens
- return typeof value === 'number' && Number.isSafeInteger(value) ? value : null
-}
-
-export function usageActiveSeconds(usage: UsageLike): number | null {
- const record = asRecord(usage)
- if (!record) return null
- const value = record.active_seconds
- return typeof value === 'number' && Number.isSafeInteger(value) ? value : null
-}
-
-export function usageIsIncomplete(usage: UsageLike): boolean {
- return asRecord(usage)?.complete === false
-}
-
-export function usageAttribution(
- usage: UsageLike,
-): 'exact' | 'best_effort' | null {
- const record = asRecord(usage)
- if (!record) return null
- return record.attribution === 'exact' || record.attribution === 'best_effort'
- ? record.attribution
- : null
-}
-
-export function formatUsd(value: number): string {
- if (value === 0) return '$0'
- if (value < 0.01) return `$${value.toFixed(4)}`
- if (value < 1) return `$${value.toFixed(3)}`
- return `$${value.toFixed(2)}`
-}
-
-export function formatUsageTokens(usage: UsageLike): string {
- const value = usageTokens(usage)
- if (value === null) return 'Unknown'
- return `${usageIsIncomplete(usage) ? '≥' : ''}${value.toLocaleString()}`
-}
-
-export function formatUsageCost(usage: UsageLike): string {
- const value = usageCostUsd(usage)
- if (value === null) return 'Unknown'
- return `${usageIsIncomplete(usage) ? '≥' : ''}${formatUsd(value)}`
-}
-
-export function formatDuration(seconds: number): string {
- if (seconds < 60) return `${seconds}s`
- const minutes = Math.floor(seconds / 60)
- const remainder = seconds % 60
- if (minutes < 60) return `${minutes}m ${String(remainder).padStart(2, '0')}s`
- const hours = Math.floor(minutes / 60)
- const minuteRemainder = minutes % 60
- return `${hours}h ${String(minuteRemainder).padStart(2, '0')}m`
-}
-
-export function formatUsageDuration(usage: UsageLike): string {
- const seconds = usageActiveSeconds(usage)
- return seconds === null ? 'Unknown' : formatDuration(seconds)
-}
-
-export function usageDisclosure(usage: UsageLike): string | null {
- const record = asRecord(usage)
- if (!record) return null
- const notes: string[] = []
- if (record.complete === false) {
- const missing = record.unreported_turns
- notes.push(
- typeof missing === 'number' && missing > 0
- ? `Lower bound · ${missing} turn${missing === 1 ? '' : 's'} did not report usage`
- : 'Lower-bound usage',
- )
- }
- if (record.attribution === 'best_effort') {
- notes.push('Best-effort session attribution')
- }
- return notes.length > 0 ? notes.join(' · ') : null
-}
diff --git a/web/src/lib/working-repo.ts b/web/src/lib/working-repo.ts
deleted file mode 100644
index 2f4afdef..00000000
--- a/web/src/lib/working-repo.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-export interface WorkingRepoValue {
- repo: string
- fullName?: string
- ref: string
-}
-
-export interface WorkingRepoOption {
- id?: string | null
- full_name: string
- default_branch?: string | null
-}
-
-export function workingRepoValue(
- repo: WorkingRepoOption,
- flue: boolean,
-): string {
- return flue ? (repo.id ?? repo.full_name) : repo.full_name
-}
-
-export function selectedWorkingRepo(
- repo: WorkingRepoOption,
- flue: boolean,
- current: WorkingRepoValue | null,
-): WorkingRepoValue {
- const repoValue = workingRepoValue(repo, flue)
- return {
- repo: repoValue,
- ...(flue ? { fullName: repo.full_name } : {}),
- ref:
- current?.repo === repoValue
- ? current.ref
- : (repo.default_branch ?? 'main'),
- }
-}
diff --git a/web/src/pages/AgentDeployment.tsx b/web/src/pages/AgentDeployment.tsx
deleted file mode 100644
index 66ac1aa2..00000000
--- a/web/src/pages/AgentDeployment.tsx
+++ /dev/null
@@ -1,638 +0,0 @@
-import { useRef } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'
-import {
- ArrowLeft,
- ArrowRight,
- CircleAlert,
- Clock,
- ExternalLink,
- GitCommitHorizontal,
- RotateCw,
- X,
-} from 'lucide-react'
-import {
- ApiError,
- authorizeManagedSlack,
- deployFromGithub,
- getAgent,
- getAgentDeployment,
- getDeploymentSource,
- getManagedSlackConnection,
- unlinkDeploymentSource,
- type AgentDeployment,
-} from '@/api/client'
-import {
- Alert,
- AlertAction,
- AlertDescription,
- AlertTitle,
-} from '@/components/ui/alert'
-import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
-import {
- DeploymentLog,
- DeploymentPhases,
-} from '@/components/deployment-progress'
-import { SourceProfileChangedRecovery } from '@/components/source-profile-changed-recovery'
-import { ManagedSlackWorkspaceClaims } from '@/components/managed-slack-workspace-claims'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { StatusBadge } from '@/components/status-badge'
-import { agentDeploymentOutcome } from '@/lib/agent-deployment-outcome'
-import {
- deploymentSlackPresentation,
- deploymentStage,
-} from '@/lib/deployment-slack-cta'
-import { notifyError, notifySuccess } from '@/lib/errors'
-import {
- managedSlackNotice,
- managedSlackOAuthPending,
-} from '@/lib/managed-slack-notice'
-import { useManagedSlackConnections } from '@/lib/managed-slack-connections'
-import { cn } from '@/lib/utils'
-import { useAgentDeploymentLogs } from '@/hooks/use-agent-deployment-logs'
-
-const DEPLOY_COMMAND_STORAGE = 'oc.flue-deploy-latest-command.v1'
-
-type DeployCommand = { fingerprint: string; key: string }
-
-function newCommandKey(): string {
- return (
- globalThis.crypto?.randomUUID?.() ??
- `deploy-${Date.now()}-${Math.random().toString(36).slice(2)}`
- )
-}
-
-function stableCommandKey(
- fingerprint: string,
- storageKey: string,
- memory: { current: DeployCommand | null },
-): string {
- if (memory.current?.fingerprint === fingerprint) return memory.current.key
-
- try {
- const stored = window.sessionStorage.getItem(storageKey)
- if (stored) {
- const parsed = JSON.parse(stored) as Partial<DeployCommand>
- 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(
- storageKey,
- JSON.stringify({ fingerprint, key }),
- )
- } catch {
- // The in-memory key still makes repeated submits stable for this page load.
- }
- return key
-}
-
-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 OutcomeDetail({ deployment }: { deployment: AgentDeployment }) {
- const outcome = agentDeploymentOutcome(deployment)
-
- if (outcome.kind === 'success' || outcome.kind === 'progress') return null
-
- if (outcome.kind === 'error') {
- return (
- <Alert variant="destructive">
- <CircleAlert className="size-4" />
- <AlertTitle>{outcome.title}</AlertTitle>
- <AlertDescription>{outcome.description}</AlertDescription>
- </Alert>
- )
- }
-
- return (
- <Alert>
- <AlertTitle>{outcome.title}</AlertTitle>
- <AlertDescription>{outcome.description}</AlertDescription>
- </Alert>
- )
-}
-
-export default function AgentDeployment() {
- const { agentId = '', deploymentId = '' } = useParams()
- const navigate = useNavigate()
- const [searchParams, setSearchParams] = useSearchParams()
- const queryClient = useQueryClient()
- const deployCommand = useRef<DeployCommand | null>(null)
- const deployCommandStorage = `${DEPLOY_COMMAND_STORAGE}:${agentId}`
- const deploymentQuery = useQuery({
- queryKey: ['agent-deployment', agentId, deploymentId],
- queryFn: () => getAgentDeployment(agentId, deploymentId),
- enabled: !!agentId && !!deploymentId,
- refetchInterval: (query) => {
- const deployment = query.state.data
- if (!deployment) return false
- if (
- deployment.state === 'ready' &&
- !deployment.allowed_actions.includes('start_session')
- ) {
- return 1500
- }
- return deployment.terminal ? false : 1500
- },
- })
- const { data: agent } = useQuery({
- queryKey: ['agent', agentId],
- queryFn: () => getAgent(agentId),
- enabled: !!agentId,
- })
- const managedSlackQuery = useQuery({
- queryKey: ['slack', 'managed', agentId],
- queryFn: () => getManagedSlackConnection(agentId),
- enabled: !!agentId,
- refetchOnWindowFocus: 'always',
- })
- const managedSlackConnectionsQuery = useManagedSlackConnections(!!agentId)
- const oauthResult = searchParams.get('slack')
- const connectedAgentId = searchParams.get('connected_agent')
- const sameOwnerConnectedAgentId =
- oauthResult === 'workspace_already_connected' &&
- connectedAgentId &&
- /^agt_[0-9a-f]{24}$/.test(connectedAgentId)
- ? connectedAgentId
- : null
- const connectedAgentQuery = useQuery({
- queryKey: ['agent', sameOwnerConnectedAgentId],
- queryFn: () => getAgent(sameOwnerConnectedAgentId!),
- enabled: !!sameOwnerConnectedAgentId,
- })
- const deploymentReportedSourceProfileChange =
- deploymentQuery.data?.error_class === 'source_profile_changed' ||
- deploymentQuery.data?.error?.class === 'source_profile_changed'
- const changedSourceQuery = useQuery({
- queryKey: ['agent-deploy-source', agentId],
- queryFn: async () => {
- try {
- return (await getDeploymentSource(agentId)).source
- } catch (error) {
- if (error instanceof ApiError && error.status === 404) return null
- throw error
- }
- },
- enabled: !!agentId && deploymentReportedSourceProfileChange,
- refetchOnWindowFocus: 'always',
- })
- const logsQuery = useAgentDeploymentLogs({
- agentId,
- deploymentId,
- enabled: true,
- terminal: deploymentQuery.data?.terminal ?? false,
- })
- const deployLatestMutation = useMutation({
- mutationFn: (fingerprint: string) =>
- deployFromGithub(
- agentId,
- stableCommandKey(fingerprint, deployCommandStorage, deployCommand),
- ),
- onSuccess: ({ deployment }) => {
- deployCommand.current = null
- try {
- window.sessionStorage.removeItem(deployCommandStorage)
- } catch {
- // Storage can be unavailable in privacy-restricted browser contexts.
- }
- void queryClient.invalidateQueries({
- queryKey: ['agent-deployments', agentId],
- })
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- void navigate(`/agents/${agentId}/deployments/${deployment.id}`)
- },
- })
- const authorizeManagedSlackMutation = useMutation({
- mutationFn: () => authorizeManagedSlack(agentId, deploymentId),
- onSuccess: (result) => {
- if ('authorize_url' in result) {
- window.location.assign(result.authorize_url)
- return
- }
- queryClient.setQueryData(['slack', 'managed', agentId], result)
- },
- onError: (error) =>
- notifyError("Couldn't start the Slack connection.", error),
- })
- const unlinkChangedSourceMutation = useMutation({
- mutationFn: () => unlinkDeploymentSource(agentId),
- onSuccess: () => {
- const source = changedSourceQuery.data
- void queryClient.invalidateQueries({
- queryKey: ['agent-deploy-source', agentId],
- })
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- notifySuccess(
- 'Repository source unlinked. Existing revisions are unchanged.',
- )
- if (source) {
- void navigate('/agents/new', {
- state: {
- repositoryImport: {
- repo: source.repo_id,
- path: source.path,
- productionRef: source.production_ref,
- },
- },
- })
- }
- },
- onError: (error) => notifyError("Couldn't unlink the repository.", error),
- })
-
- 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}/deployments`}>
- <ArrowLeft className="size-4" />
- Back to deployments
- </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 outcome = agentDeploymentOutcome(deployment)
- const managedSlack = managedSlackQuery.data
- const managedSlackStatus = managedSlackQuery.isSuccess
- ? (managedSlack?.status ?? null)
- : undefined
- const stage = deploymentStage(deployment.state, deployment.terminal)
- const canStartSession =
- stage === 'ready' && deployment.allowed_actions.includes('start_session')
- const slackPresentation = deploymentSlackPresentation({
- deploymentState: deployment.state,
- deploymentTerminal: deployment.terminal,
- canStartSession,
- managedStatus: managedSlackStatus,
- openUrl: managedSlack?.open_url,
- connecting: authorizeManagedSlackMutation.isPending,
- })
- const managedWorkspace =
- managedSlack?.workspace?.name ?? managedSlack?.workspace?.id
- const waitingForConnectedState = managedSlackOAuthPending(
- oauthResult,
- managedSlack?.status,
- managedSlack?.connected_at,
- )
- const waitingForConnectedAgent =
- !!sameOwnerConnectedAgentId && connectedAgentQuery.isLoading
- const slackNotice =
- waitingForConnectedState || waitingForConnectedAgent
- ? null
- : managedSlackNotice(
- oauthResult,
- managedWorkspace,
- agent?.name ?? 'this agent',
- connectedAgentQuery.data?.name,
- managedSlack?.status,
- )
- const connectedAgentHref =
- connectedAgentQuery.data && sameOwnerConnectedAgentId
- ? `/agents/${encodeURIComponent(sameOwnerConnectedAgentId)}`
- : null
- const hasOtherManagedSlackConnections =
- managedSlackConnectionsQuery.data?.some(
- (connection) => connection.agent.id !== agentId,
- ) ?? false
- const checkingManagedSlackConnections =
- slackPresentation.action === 'connect' &&
- managedSlackConnectionsQuery.isLoading
- const dismissSlackNotice = () => {
- const next = new URLSearchParams(searchParams)
- next.delete('slack')
- next.delete('connected_agent')
- setSearchParams(next, { replace: true })
- }
- const commitUrl = deployment.source_relation?.commit_url ?? undefined
- const canViewCommit =
- deployment.allowed_actions.includes('view_commit') && !!commitUrl
- const canOpenAgent = deployment.allowed_actions.includes('open_agent')
- const currentSourceProfileChanged =
- deploymentReportedSourceProfileChange &&
- changedSourceQuery.data?.status === 'source_profile_changed'
- // Keep routine ready/running pages focused on first use. Redeploy is the
- // recovery action here; ordinary source management remains on the agent.
- const canDeployLatest =
- stage === 'failed' &&
- !deploymentReportedSourceProfileChange &&
- deployment.allowed_actions.includes('deploy_latest')
- const deployLatestFingerprint = JSON.stringify({
- agent_id: agentId,
- repo_id: deployment.source_relation?.repo?.id ?? null,
- path: deployment.source_relation?.path ?? '',
- production_ref: deployment.source_relation?.production_ref ?? null,
- })
- const deployLatestConflict =
- deployLatestMutation.error instanceof ApiError &&
- deployLatestMutation.error.status === 409
-
- return (
- <div className="space-y-5">
- <div>
- <Link
- to={`/agents/${agentId}/deployments`}
- 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} deployments`
- : 'Back to deployments'}
- </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 max-w-xl flex-col gap-1.5 sm:items-end">
- <span className="sr-only" aria-live="polite" aria-atomic="true">
- {slackPresentation.announcement}
- </span>
- <div className="flex flex-wrap gap-2 sm:justify-end">
- {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 variant="outline" size="sm" asChild>
- <Link to={`/agents/${agentId}/sessions`}>
- Start session
- <ArrowRight className="size-4" />
- </Link>
- </Button>
- ) : null}
- {canDeployLatest ? (
- <Button
- size="sm"
- variant={stage === 'failed' ? 'default' : 'outline'}
- disabled={deployLatestMutation.isPending}
- onClick={() =>
- deployLatestMutation.mutate(deployLatestFingerprint)
- }
- >
- <RotateCw
- className={cn(
- 'size-4',
- deployLatestMutation.isPending &&
- 'animate-spin motion-reduce:animate-none',
- )}
- />
- {deployLatestMutation.isPending
- ? 'Starting deployment…'
- : 'Deploy latest'}
- </Button>
- ) : null}
- {slackPresentation.action === 'open' && managedSlack?.open_url ? (
- <Button size="sm" asChild>
- <a
- href={managedSlack.open_url}
- target="_blank"
- rel="noreferrer"
- >
- Open Slack
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- ) : slackPresentation.action === 'connect' ||
- slackPresentation.action === 'reconnect' ||
- slackPresentation.action === 'connecting' ? (
- <Button
- size="sm"
- disabled={
- authorizeManagedSlackMutation.isPending ||
- checkingManagedSlackConnections
- }
- onClick={() => authorizeManagedSlackMutation.mutate()}
- >
- {checkingManagedSlackConnections
- ? 'Checking Slack…'
- : slackPresentation.action === 'connect' &&
- hasOtherManagedSlackConnections
- ? 'Connect another workspace'
- : slackPresentation.label}
- </Button>
- ) : null}
- </div>
- {slackPresentation.disclosure ? (
- <p className="text-muted-foreground max-w-sm text-xs leading-relaxed sm:text-right">
- Anyone in this Slack workspace who can message the app can use
- this agent.
- </p>
- ) : managedSlackQuery.isError && stage !== 'failed' ? (
- <div className="flex items-center gap-2 text-xs">
- <span className="text-status-error">
- Slack status is unavailable.
- </span>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => void managedSlackQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : null}
- </div>
- </div>
- </div>
-
- {slackNotice ? (
- <Alert variant={slackNotice.destructive ? 'destructive' : 'default'}>
- <AlertTitle>{slackNotice.title}</AlertTitle>
- {slackNotice.description || connectedAgentHref ? (
- <AlertDescription>
- {slackNotice.description}{' '}
- {connectedAgentHref ? (
- <Link to={connectedAgentHref}>Open connected agent</Link>
- ) : null}
- </AlertDescription>
- ) : null}
- <AlertAction>
- <Button
- size="icon-sm"
- variant="ghost"
- aria-label="Dismiss Slack notice"
- onClick={dismissSlackNotice}
- >
- <X aria-hidden />
- </Button>
- </AlertAction>
- </Alert>
- ) : null}
-
- {slackPresentation.action === 'connect' && agent ? (
- <Panel>
- <PanelContent>
- <ManagedSlackWorkspaceClaims
- currentAgentId={agentId}
- currentAgentName={agent.name}
- query={managedSlackConnectionsQuery}
- className="border-t-0 pt-0"
- />
- </PanelContent>
- </Panel>
- ) : null}
-
- {deployLatestMutation.isError ? (
- <Alert variant="destructive">
- <CircleAlert className="size-4" />
- <AlertTitle>
- {deployLatestConflict
- ? 'Repository needs attention'
- : 'Deployment could not start'}
- </AlertTitle>
- <AlertDescription>
- {deployLatestMutation.error instanceof Error
- ? deployLatestMutation.error.message
- : 'No new deployment was started. Retry when the repository is available.'}
- </AlertDescription>
- </Alert>
- ) : null}
-
- <Panel>
- <PanelHeader className="flex-col gap-3 sm:flex-row sm:items-center">
- <div className="min-w-0">
- <PanelTitle>Deployment log</PanelTitle>
- <PanelDescription className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs">
- <span
- className={cn(outcome.kind === 'error' && 'text-status-error')}
- >
- {outcome.title}
- </span>
- <span className="flex items-center gap-1">
- <Clock className="size-3" aria-hidden />
- {formatDuration(deployment)}
- {!deployment.terminal ? ' elapsed' : ''}
- </span>
- {deployment.log_truncated ? (
- <span className="text-status-pending">Output truncated</span>
- ) : null}
- </PanelDescription>
- </div>
- <div className="space-y-1.5 sm:text-right">
- <DeploymentPhases deployment={deployment} />
- {slackPresentation.status ? (
- <p className="text-muted-foreground text-xs">
- {slackPresentation.status}
- </p>
- ) : null}
- </div>
- </PanelHeader>
- <PanelContent className="space-y-3">
- {currentSourceProfileChanged && changedSourceQuery.data ? (
- <SourceProfileChangedRecovery
- source={changedSourceQuery.data}
- pending={unlinkChangedSourceMutation.isPending}
- onUnlink={() => unlinkChangedSourceMutation.mutate()}
- />
- ) : deploymentReportedSourceProfileChange &&
- changedSourceQuery.isLoading ? (
- <Skeleton className="h-24 w-full" />
- ) : (
- <OutcomeDetail deployment={deployment} />
- )}
- {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>
- )
-}
diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsx
deleted file mode 100644
index 0410a853..00000000
--- a/web/src/pages/AgentDetail.tsx
+++ /dev/null
@@ -1,1038 +0,0 @@
-import { useEffect, useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useLocation, useNavigate, useParams } from 'react-router-dom'
-import {
- ArrowLeft,
- MessageSquare,
- MessagesSquare,
- Send,
- GitBranch,
- ExternalLink,
-} from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import {
- getAgent,
- updateAgent,
- getSessions,
- createSession,
- getCredentials,
- createCredential,
- getDeploymentSource,
- getManagedSlackConnection,
- type Agent,
-} from '@/api/client'
-import type { Session } from '@/api/schemas'
-import {
- Panel,
- PanelContent,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { Field, Input, Select, Textarea } from '@/components/form'
-import { ChatTextarea } from '@/components/chat-textarea'
-import { StatusBadge } from '@/components/status-badge'
-import { EmptyState } from '@/components/empty-state'
-import { ResourceTable, type Column } from '@/components/resource-table'
-import { Skeleton } from '@/components/ui/skeleton'
-import {
- SlackConnect,
- SlackConnectionSummary,
-} from '@/components/slack-connect'
-import { AgentSkills } from '@/components/agent-skills'
-import {
- AgentDeploySource,
- DeploymentSourceSummary,
-} from '@/components/agent-deploy-source'
-import { AgentSchedulesTab } from '@/components/agent-schedules'
-import { AgentRevisions } from '@/components/agent-revisions'
-import { AgentDeployments } from '@/components/agent-deployments'
-import { AgentHooksPanel } from '@/components/agent-hooks-panel'
-import {
- RepositoryAccessPanel,
- RepositoryAccessSummary,
-} from '@/components/repository-access'
-import {
- WorkingRepoField,
- type WorkingRepo,
-} from '@/components/working-repo-field'
-import { ApiHint, type ApiRef } from '@/components/api-hint'
-import {
- agentCanStartNewSession,
- agentDeploymentDisplayStatus,
-} from '@/lib/agent-deployment-status'
-import {
- getRuntime,
- keyFieldFor,
- providerForModel,
- withModelGroups,
-} from '@/lib/runtimes'
-import { cn } from '@/lib/utils'
-import { latestManagedSlackSession } from '@/lib/managed-slack-session'
-
-const DOCS = 'https://docs.opencomputer.dev/agent-sessions'
-
-// Sentinels for the non-credential choices in the picker.
-const ORG_DEFAULT = '__default__' // no pinned credential → org default resolves
-const NEW_CRED = '__new__' // create one inline
-const MANAGED = 'managed' // run via OpenComputer, no BYO key (token-billing §6.6)
-
-type Tab =
- | 'overview'
- | 'deployments'
- | 'revisions'
- | 'sessions'
- | 'schedules'
- | 'settings'
-
-export default function AgentDetail() {
- const { agentId = '', tab } = useParams()
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const active: Tab =
- tab === 'deployments'
- ? 'deployments'
- : tab === 'revisions'
- ? 'revisions'
- : tab === 'sessions'
- ? 'sessions'
- : tab === 'schedules'
- ? 'schedules'
- : tab === 'settings'
- ? 'settings'
- : 'overview'
-
- // Each tab is a thin control panel over one API resource — surface the call it drives
- // (REST + SDK), same as the other pages, so the dashboard reads as programmable.
- const tabApi: Record<Tab, ApiRef> = {
- overview: {
- method: 'GET',
- path: `/v3/agents/${agentId}`,
- sdk: 'oc.agents.get(id)',
- docs: `${DOCS}/agents`,
- },
- deployments: { method: 'GET', path: `/v3/agents/${agentId}/deployments` },
- revisions: {
- method: 'GET',
- path: `/v3/agents/${agentId}/revisions`,
- sdk: 'oc.agents.revisions.list(id)',
- docs: `${DOCS}/revisions`,
- },
- sessions: {
- method: 'POST',
- path: '/v3/sessions',
- sdk: 'oc.sessions.create({ agent })',
- docs: `${DOCS}/sessions`,
- },
- schedules: {
- method: 'GET',
- path: `/v3/agents/${agentId}/schedules`,
- sdk: 'oc.agents.schedules.list(id)',
- docs: `${DOCS}/schedules`,
- },
- settings: {
- method: 'PATCH',
- path: `/v3/agents/${agentId}`,
- sdk: 'oc.agents.update(id, …)',
- docs: `${DOCS}/agents`,
- },
- }
-
- const {
- data: agent,
- isLoading,
- isError,
- } = useQuery({
- queryKey: ['agent', agentId],
- queryFn: () => getAgent(agentId),
- enabled: !!agentId,
- })
-
- const managedSlackQuery = useQuery({
- queryKey: ['slack', 'managed', agentId],
- queryFn: () => getManagedSlackConnection(agentId),
- enabled: !!agentId,
- refetchOnWindowFocus: 'always',
- })
-
- // This agent's sessions — filtered server-side. While first-run Slack setup
- // is incomplete, refresh just long enough for the real managed session to
- // turn the persistent setup affordance from primary into secondary.
- const { data: sessions = [], isLoading: loadingSessions } = useQuery({
- queryKey: ['sessions', { agent: agentId }],
- queryFn: () => getSessions({ agent: agentId }),
- refetchInterval: (query) =>
- managedSlackQuery.data?.status === 'active' &&
- !latestManagedSlackSession(
- query.state.data ?? [],
- managedSlackQuery.data.connected_at,
- )
- ? 2000
- : false,
- refetchOnWindowFocus: 'always',
- })
-
- // The deployment-source link (shared cache key with the GitHub card). null = not linked.
- // When linked, the repo is the source of truth, so the inline editor goes read-only.
- const { data: source } = useQuery({
- queryKey: ['agent-deploy-source', agentId],
- queryFn: async () => {
- try {
- return (await getDeploymentSource(agentId)).source
- } catch {
- return null
- }
- },
- })
-
- // Credentials for the switch picker + to label the current one.
- const { data: credentials } = useQuery({
- queryKey: ['credentials'],
- queryFn: getCredentials,
- })
- const rt = getRuntime(agent?.runtime)
- // Provider follows the agent's MODEL prefix (pi spans providers within one runtime);
- // for claude/codex it equals the runtime's provider.
- const provider = providerForModel(agent?.model ?? '') || rt.provider
- const keyField = keyFieldFor(provider)
- const providerCreds = (credentials ?? []).filter(
- (c) => c.provider === provider,
- )
- const credLabel = (id: string) => {
- const c = providerCreds.find((x) => x.id === id)
- if (!c) return id
- return `${c.name || 'Unnamed'}${c.last4 ? ` ·· ${c.last4}` : ''}${
- c.is_default ? ' (default)' : ''
- }`
- }
-
- // ── Start a session (used by the Overview playground) ─────────────────────
- // Seed from a deferred action's prefill (agent_prefill lands here via router
- // state). Doesn't survive refresh — fine; the agent already exists.
- const location = useLocation()
-
- // Public endpoint-guide and Overview summary links land on one exact
- // Settings owner. Keep the query through authentication, then scroll and
- // focus the rendered section without triggering a connector mutation.
- useEffect(() => {
- if (active === 'overview' && location.hash === '#playground') {
- const frame = window.requestAnimationFrame(() => {
- const target = document.getElementById('playground')
- target?.scrollIntoView({ block: 'start' })
- target?.focus({ preventScroll: true })
- })
- return () => window.cancelAnimationFrame(frame)
- }
- if (active !== 'settings') return
- const section = new URLSearchParams(location.search).get('section')
- if (section !== 'github' && section !== 'slack' && section !== 'hooks') {
- return
- }
- const frame = window.requestAnimationFrame(() => {
- const target = document.getElementById(section)
- target?.scrollIntoView({ block: 'start' })
- target?.focus({ preventScroll: true })
- })
- return () => window.cancelAnimationFrame(frame)
- }, [active, location.hash, location.search])
-
- const [task, setTask] = useState(
- () =>
- (location.state as { composerPrefill?: string } | null)
- ?.composerPrefill ?? '',
- )
- // Optional working repo — the repo the agent checks out + opens PRs from. Explicitly chosen,
- // never derived from the connected/config repo (design 010 §2).
- const [workingRepo, setWorkingRepo] = useState<WorkingRepo | null>(null)
- const startMutation = useMutation({
- mutationFn: () =>
- createSession(
- {
- agent: agentId,
- input: task.trim(),
- ...(workingRepo
- ? { sources: [{ repo: workingRepo.repo, ref: workingRepo.ref }] }
- : {}),
- },
- crypto.randomUUID(),
- ),
- onSuccess: (session) => {
- void queryClient.invalidateQueries({ queryKey: ['sessions'] })
- void navigate(`/sessions/${session.id}`)
- },
- onError: (e) => notifyError("Couldn't start the session.", e),
- })
-
- // ── Live config controls ───────────────────────────────────────────────────
- const settleAgent = () => {
- void queryClient.invalidateQueries({ queryKey: ['agent', agentId] })
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- void queryClient.invalidateQueries({
- queryKey: ['agent-revisions', agentId],
- })
- void queryClient.invalidateQueries({ queryKey: ['agent-deploys', agentId] })
- }
- const optimistic = async (patch: Partial<Agent>) => {
- await queryClient.cancelQueries({ queryKey: ['agent', agentId] })
- const prev = queryClient.getQueryData<Agent>(['agent', agentId])
- queryClient.setQueryData<Agent>(['agent', agentId], (old) =>
- old ? { ...old, ...patch } : old,
- )
- return prev
- }
- const rollback = (prev?: Agent) => {
- if (prev) queryClient.setQueryData(['agent', agentId], prev)
- }
-
- const modelMutation = useMutation({
- mutationFn: (model: string) => updateAgent(agentId, { model }),
- onMutate: (model) => optimistic({ model }),
- onError: (e, _v, prev) => {
- rollback(prev)
- notifyError("Couldn't update the model.", e)
- },
- onSettled: settleAgent,
- })
-
- const [promptDraft, setPromptDraft] = useState<string | undefined>(undefined)
- const promptMutation = useMutation({
- mutationFn: (prompt: string) => updateAgent(agentId, { prompt }),
- onMutate: (prompt) => optimistic({ prompt }),
- onError: (e, _v, prev) => {
- rollback(prev)
- notifyError("Couldn't update the prompt.", e)
- },
- onSuccess: () => setPromptDraft(undefined),
- onSettled: settleAgent,
- })
-
- const switchCredMutation = useMutation({
- mutationFn: (credential: string | null) =>
- updateAgent(agentId, { credential }),
- onMutate: (credential) => optimistic({ credential_id: credential }),
- onError: (e, _v, prev) => {
- rollback(prev)
- notifyError("Couldn't switch the credential.", e)
- },
- onSettled: settleAgent,
- })
-
- const [credNew, setCredNew] = useState(false)
- const [newCredName, setNewCredName] = useState('')
- const [newCredKey, setNewCredKey] = useState('')
- const addCredMutation = useMutation({
- mutationFn: async () => {
- const cred = await createCredential({
- key: newCredKey.trim(),
- provider: provider,
- name: newCredName.trim() || undefined,
- is_default: !providerCreds.some((c) => c.is_default),
- })
- return updateAgent(agentId, { credential: cred.id })
- },
- onSuccess: (data) => {
- queryClient.setQueryData(['agent', agentId], data)
- void queryClient.invalidateQueries({ queryKey: ['credentials'] })
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- setCredNew(false)
- setNewCredName('')
- setNewCredKey('')
- },
- onError: (e) => notifyError("Couldn't add the credential.", e),
- })
- const credSaving = switchCredMutation.isPending || addCredMutation.isPending
-
- // Derived control values.
- const modelOptions = rt.models.some((m) => m.value === agent?.model)
- ? rt.models
- : [{ value: agent?.model ?? '', label: agent?.model ?? '' }, ...rt.models]
- const savedPrompt = agent?.prompt ?? ''
- const promptValue = promptDraft ?? savedPrompt
- const promptDirty = promptDraft !== undefined && promptDraft !== savedPrompt
- const credSelectValue = credNew
- ? NEW_CRED
- : (agent?.credential_id ?? ORG_DEFAULT)
- const credOptions = [
- { value: ORG_DEFAULT, label: 'Org default (no pinned credential)' },
- { value: MANAGED, label: 'Managed · no key needed' },
- ...providerCreds.map((c) => ({ value: c.id, label: credLabel(c.id) })),
- { value: NEW_CRED, label: '+ New credential…' },
- ]
- const onCredChange = (v: string) => {
- if (v === NEW_CRED) {
- setCredNew(true)
- return
- }
- setCredNew(false)
- switchCredMutation.mutate(v === ORG_DEFAULT ? null : v)
- }
-
- if (isLoading) {
- return (
- <div className="mx-auto max-w-5xl">
- <BackLink />
- <Skeleton className="h-40 w-full" />
- </div>
- )
- }
- if (isError || !agent) {
- return (
- <div className="mx-auto max-w-5xl">
- <BackLink />
- <EmptyState
- icon={MessagesSquare}
- title="Agent not found"
- description="This agent doesn't exist or you don't have access to it."
- action={
- <Button size="sm" onClick={() => void navigate('/agents')}>
- Back to agents
- </Button>
- }
- />
- </div>
- )
- }
-
- const activeRev =
- agent.active_revision?.number ??
- (agent.revision && agent.revision > 0 ? agent.revision : null)
- const base = `/agents/${agent.id}`
- const latestDeploymentId = agent.deployment_status?.deployment_id
- const deploymentStatus = agentDeploymentDisplayStatus(agent)
- const canStartNewSession = agentCanStartNewSession(agent)
- const setupHref = `${base}/setup${
- latestDeploymentId
- ? `?deployment=${encodeURIComponent(latestDeploymentId)}`
- : ''
- }`
- const managedSlackSession = latestManagedSlackSession(
- sessions,
- managedSlackQuery.data?.connected_at,
- )
- const setupComplete =
- canStartNewSession &&
- managedSlackQuery.isSuccess &&
- managedSlackQuery.data?.status === 'active' &&
- !loadingSessions &&
- !!managedSlackSession
-
- return (
- <div className="mx-auto max-w-5xl">
- <BackLink />
-
- {/* Sticky header: identity + status + primary action, with the tab bar. */}
- <div className="bg-background sticky top-0 z-20 border-b">
- <div className="flex flex-wrap items-start justify-between gap-3 pb-3">
- <div className="min-w-0 space-y-1.5">
- <h1 className="text-foreground truncate text-lg font-semibold">
- {agent.name}
- </h1>
- <div className="text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-xs">
- {agent.invoke_url ? (
- <a
- href={agent.invoke_url}
- target="_blank"
- rel="noreferrer"
- title={agent.invoke_url}
- aria-label={`Open Agent URL for ${agent.id}`}
- className="hover:text-foreground focus-visible:ring-ring/50 inline-flex items-center gap-1 whitespace-nowrap rounded-sm font-mono underline-offset-4 outline-none hover:underline focus-visible:ring-2"
- >
- <span>{agent.invoke_url.replace(/^https:\/\//, '')}</span>
- <ExternalLink className="size-3 shrink-0" aria-hidden />
- </a>
- ) : (
- <span className="font-mono">{agent.id}</span>
- )}
- <span className="capitalize">{agent.runtime}</span>
- <span className="font-mono">
- {activeRev ? `rev #${activeRev}` : 'Not deployed'}
- </span>
- {latestDeploymentId ? (
- <Link
- to={`${base}/deployments/${latestDeploymentId}`}
- aria-label={`Open latest deployment: ${deploymentStatus.replace(/_/g, ' ')}`}
- className="focus-visible:ring-ring/50 rounded-md outline-none focus-visible:ring-3"
- >
- <StatusBadge status={deploymentStatus} />
- </Link>
- ) : null}
- <SourceChip source={source ?? null} />
- </div>
- </div>
- <div className="flex flex-wrap items-center gap-2">
- {setupComplete ? (
- <Button asChild size="sm" variant="ghost">
- <Link to={setupHref}>Setup</Link>
- </Button>
- ) : canStartNewSession ? (
- <Button asChild size="sm" variant="outline">
- <Link to={`${base}#playground`}>
- <Send className="size-4" />
- New session
- </Link>
- </Button>
- ) : null}
- {setupComplete ? (
- <Button asChild size="sm">
- <Link to={`${base}#playground`}>
- <Send className="size-4" />
- New session
- </Link>
- </Button>
- ) : (
- <Button asChild size="sm">
- <Link to={setupHref}>
- <MessageSquare className="size-4" />
- Continue setup
- </Link>
- </Button>
- )}
- </div>
- </div>
- <nav className="-mb-px flex gap-1 overflow-x-auto" aria-label="Agent">
- <TabLink to={base} label="Overview" current={active === 'overview'} />
- <TabLink
- to={`${base}/deployments`}
- label="Deployments"
- current={active === 'deployments'}
- />
- <TabLink
- to={`${base}/revisions`}
- label="Revisions"
- current={active === 'revisions'}
- />
- <TabLink
- to={`${base}/sessions`}
- label="Sessions"
- current={active === 'sessions'}
- />
- <TabLink
- to={`${base}/schedules`}
- label="Schedules"
- current={active === 'schedules'}
- />
- <TabLink
- to={`${base}/settings`}
- label="Settings"
- current={active === 'settings'}
- />
- </nav>
- </div>
-
- <div className="py-6">
- <div className="mb-4">
- <ApiHint {...tabApi[active]} />
- </div>
- {active === 'overview' && (
- <div className="space-y-6">
- <Panel
- id="playground"
- tabIndex={-1}
- className="scroll-mt-36 overflow-hidden outline-none"
- >
- <PanelHeader>
- <div>
- <PanelTitle>Playground</PanelTitle>
- <p className="text-muted-foreground mt-1 text-xs">
- Every run starts a new durable session.
- </p>
- </div>
- <Link
- to={`${base}/sessions`}
- className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
- >
- View sessions
- </Link>
- </PanelHeader>
- <PanelContent>
- {canStartNewSession ? (
- <form
- className="space-y-2"
- onSubmit={(event) => {
- event.preventDefault()
- if (task.trim()) startMutation.mutate()
- }}
- >
- <ChatTextarea
- value={task}
- onChange={(event) => setTask(event.target.value)}
- onSend={() => {
- if (task.trim() && !startMutation.isPending) {
- startMutation.mutate()
- }
- }}
- placeholder="Give this agent a task…"
- className="min-h-20"
- />
- <div className="flex flex-wrap items-center justify-between gap-2">
- <WorkingRepoField
- agentId={agent.id}
- runtime={agent.runtime}
- value={workingRepo}
- onChange={setWorkingRepo}
- />
- <Button
- type="submit"
- size="sm"
- title="Enter to start · Shift+Enter for newline"
- disabled={startMutation.isPending || !task.trim()}
- className="ml-auto"
- >
- <Send className="size-4" />
- {startMutation.isPending
- ? 'Starting…'
- : 'Start session'}
- </Button>
- </div>
- </form>
- ) : (
- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
- <div>
- <p className="text-sm font-medium">
- {activeRev
- ? 'New sessions are paused until the live deployment is verified.'
- : 'Deploy this agent before starting a session.'}
- </p>
- <p className="text-muted-foreground mt-1 text-xs">
- Open deployment history to inspect progress and build
- logs.
- </p>
- </div>
- <Button variant="outline" size="sm" asChild>
- <Link to={`${base}/deployments`}>View deployments</Link>
- </Button>
- </div>
- )}
- </PanelContent>
- </Panel>
-
- <div className="grid gap-6 lg:grid-cols-[2fr_1fr]">
- {/* Left: behavior (model/prompt) + skills — read-only when a repo drives the agent. */}
- <div className="space-y-6">
- <Panel>
- <PanelContent className="space-y-5">
- {source ? (
- <div className="space-y-4">
- <div className="border-border bg-panel-2 flex items-start gap-2 rounded-md border px-3 py-2.5 text-xs">
- <GitBranch className="text-muted-foreground mt-0.5 size-3.5 shrink-0" />
- <div className="space-y-0.5">
- <p className="text-foreground">
- Managed from a connected repo:{' '}
- <span className="font-mono">
- {source.full_name ?? source.path ?? 'repo'}
- {source.full_name && source.path
- ? `/${source.path}`
- : ''}
- @{source.production_ref}
- </span>
- </p>
- <p className="text-muted-foreground">
- The repo is the source of truth.{' '}
- {agent.runtime === 'flue' ? (
- <>
- Edit and push there, then{' '}
- <Link
- className="underline underline-offset-4"
- to={
- latestDeploymentId
- ? `${base}/deployments/${latestDeploymentId}`
- : `${base}/deployments`
- }
- >
- {latestDeploymentId
- ? 'open the latest deployment'
- : 'open Deployments'}
- </Link>{' '}
- and choose Deploy latest.
- </>
- ) : (
- <>
- Edit there and push, or{' '}
- <Link
- className="underline underline-offset-4"
- to={`${base}/revisions`}
- >
- browse revisions
- </Link>
- .
- </>
- )}
- </p>
- </div>
- </div>
- <ReadOnlyField label="Model" value={agent.model} mono />
- <ReadOnlyField
- label="System prompt"
- value={savedPrompt || '—'}
- pre
- />
- </div>
- ) : (
- <>
- <Field label="Model" htmlFor="agent-model">
- <div className="flex items-center gap-3">
- <Select
- id="agent-model"
- value={agent.model}
- onValueChange={(m) => modelMutation.mutate(m)}
- options={withModelGroups(modelOptions)}
- className="max-w-xs"
- />
- <Saving show={modelMutation.isPending} />
- </div>
- </Field>
- <Field label="System prompt" htmlFor="agent-prompt">
- <Textarea
- id="agent-prompt"
- value={promptValue}
- onChange={(e) => setPromptDraft(e.target.value)}
- placeholder="You are a meticulous code reviewer…"
- className="min-h-32"
- />
- <div className="mt-2 flex items-center gap-3">
- <p className="text-muted-foreground text-xs">
- How the agent behaves. Saving bumps the agent's
- revision.
- </p>
- <div className="ml-auto flex items-center gap-2">
- <Saving show={promptMutation.isPending} />
- <Button
- type="button"
- variant="ghost"
- size="sm"
- disabled={
- !promptDirty || promptMutation.isPending
- }
- onClick={() => setPromptDraft(undefined)}
- >
- Discard
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={
- !promptDirty ||
- promptMutation.isPending ||
- !promptValue.trim()
- }
- onClick={() =>
- promptMutation.mutate(promptValue.trim())
- }
- >
- Save prompt
- </Button>
- </div>
- </div>
- </Field>
- </>
- )}
- </PanelContent>
- </Panel>
- <AgentSkills agentId={agent.id} />
- </div>
- {/* Overview keeps integrations compact; Settings owns mutations. */}
- <div className="space-y-4">
- {agent.runtime !== 'flue' ? (
- <DeploymentSourceSummary
- agentId={agent.id}
- onOpenSettings={() => {
- void navigate(`${base}/settings?section=github`)
- }}
- />
- ) : null}
- <RepositoryAccessSummary
- agentId={agent.id}
- onOpenSettings={() => {
- void navigate(`${base}/settings?section=github`)
- }}
- />
- <SlackConnectionSummary
- agentId={agent.id}
- onOpenSettings={() => {
- void navigate(`${base}/settings?section=slack`)
- }}
- />
- </div>
- </div>
- </div>
- )}
-
- {active === 'revisions' && <AgentRevisions agentId={agent.id} />}
- {active === 'deployments' && <AgentDeployments agentId={agent.id} />}
- {active === 'schedules' && <AgentSchedulesTab agentId={agent.id} />}
-
- {active === 'sessions' && (
- <Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Sessions</PanelTitle>
- <div className="flex items-center gap-3">
- <Link
- to="/sessions"
- className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
- >
- All sessions
- </Link>
- <Button asChild size="sm" variant="outline">
- <Link to={`${base}#playground`}>Start a session</Link>
- </Button>
- </div>
- </PanelHeader>
- <ResourceTable
- columns={sessionColumns}
- rows={sessions}
- rowKey={(s) => s.id}
- loading={loadingSessions}
- empty={
- <EmptyState
- icon={MessagesSquare}
- title="No sessions yet"
- description="Start one from the Overview playground to give this agent a durable task."
- />
- }
- />
- </Panel>
- )}
-
- {active === 'settings' && (
- <div className="space-y-6">
- <section
- id="github"
- tabIndex={-1}
- className="scroll-mt-36 space-y-6 outline-none"
- >
- <AgentDeploySource
- agentId={agent.id}
- profilePinned={agent.runtime === 'flue'}
- />
- <RepositoryAccessPanel agentId={agent.id} />
- </section>
- <section
- id="slack"
- tabIndex={-1}
- className="scroll-mt-36 outline-none"
- >
- <SlackConnect
- agentId={agent.id}
- agentName={agent.name}
- canOpenSlack={canStartNewSession}
- />
- </section>
- <AgentHooksPanel key={`hooks-${agent.id}`} agentId={agent.id} />
- {/* Credential — which key the agent runs on. */}
- <Panel>
- <PanelHeader>
- <PanelTitle>Credential</PanelTitle>
- <span className="text-muted-foreground text-xs">
- Which key this agent runs on.
- </span>
- </PanelHeader>
- <PanelContent className="space-y-3">
- <div className="flex items-center gap-3">
- <Select
- id="agent-cred"
- value={credSelectValue}
- onValueChange={onCredChange}
- options={credOptions}
- className="max-w-md"
- />
- <Saving show={credSaving} />
- </div>
- {credNew ? (
- <div className="border-border bg-panel-2 grid grid-cols-1 gap-3 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 className="flex justify-end gap-2 sm:col-span-2">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => {
- setCredNew(false)
- setNewCredName('')
- setNewCredKey('')
- }}
- >
- Cancel
- </Button>
- <Button
- type="button"
- variant="outline"
- size="sm"
- disabled={
- !newCredKey.trim() || addCredMutation.isPending
- }
- onClick={() => addCredMutation.mutate()}
- >
- {addCredMutation.isPending ? 'Adding…' : 'Add & use'}
- </Button>
- </div>
- </div>
- ) : null}
- <p className="text-muted-foreground text-xs">
- To change a key's value, rotate it on the Credentials page.
- </p>
- </PanelContent>
- </Panel>
- </div>
- )}
- </div>
- </div>
- )
-}
-
-// ── Small building blocks ─────────────────────────────────────────────────────
-
-function BackLink() {
- return (
- <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" />
- Agents
- </Link>
- )
-}
-
-function TabLink({
- to,
- label,
- current,
-}: {
- to: string
- label: string
- current: boolean
-}) {
- return (
- <Link
- to={to}
- aria-current={current ? 'page' : undefined}
- className={
- 'shrink-0 border-b-2 px-3 py-2 text-sm transition-colors ' +
- (current
- ? 'border-foreground text-foreground font-medium'
- : 'text-muted-foreground hover:text-foreground border-transparent')
- }
- >
- {label}
- </Link>
- )
-}
-
-export function SourceChip({
- source,
-}: {
- source: {
- full_name?: string | null
- path: string
- production_ref: string
- status?: string
- } | null
-}) {
- if (!source) {
- return null
- }
- const label = source.full_name ?? (source.path || 'repo')
- const needsAttention = source.status === 'source_profile_changed'
- return (
- <span
- className={cn(
- 'inline-flex items-center gap-1',
- needsAttention && 'text-status-error',
- )}
- >
- <GitBranch className="size-3" />
- <span className="font-mono">
- {label}@{source.production_ref}
- </span>
- {needsAttention ? (
- <span className="font-medium">· Source needs attention</span>
- ) : null}
- </span>
- )
-}
-
-function Saving({ show }: { show: boolean }) {
- if (!show) return null
- return <span className="text-muted-foreground text-xs">Saving…</span>
-}
-
-function ReadOnlyField({
- label,
- value,
- mono,
- pre,
-}: {
- label: string
- value: string
- mono?: boolean
- pre?: boolean
-}) {
- return (
- <div className="space-y-1.5">
- <div className="text-foreground text-sm font-medium">{label}</div>
- {pre ? (
- <pre className="text-muted-foreground max-h-40 overflow-auto text-xs whitespace-pre-wrap">
- {value}
- </pre>
- ) : (
- <div
- className={
- 'text-muted-foreground text-sm' + (mono ? ' font-mono' : '')
- }
- >
- {value}
- </div>
- )}
- </div>
- )
-}
-
-const sessionColumns: Column<Session>[] = [
- {
- key: 'id',
- header: 'Session',
- cell: (s) => (
- <Link
- to={`/sessions/${s.id}`}
- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"
- >
- {s.id}
- </Link>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (s) => <StatusBadge status={s.status} />,
- },
- {
- key: 'created',
- header: 'Created',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(s.created_at).toLocaleString()}
- </span>
- ),
- },
-]
diff --git a/web/src/pages/AgentNew.tsx b/web/src/pages/AgentNew.tsx
deleted file mode 100644
index 2add3960..00000000
--- a/web/src/pages/AgentNew.tsx
+++ /dev/null
@@ -1,1151 +0,0 @@
-import { useMemo, useRef, useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import {
- Link,
- useLocation,
- useNavigate,
- useSearchParams,
-} from 'react-router-dom'
-import {
- ArrowLeft,
- ArrowRight,
- Bot,
- Check,
- ExternalLink,
- FolderSearch,
- GitBranch,
- KeyRound,
- Loader2,
- Search,
- Unplug,
-} from 'lucide-react'
-import {
- ApiError,
- getDeployApp,
- importAgentFromGithub,
- reviewRepositoryAgent,
- unlinkDeploymentSource,
- type DeployApp,
- type RepositorySourceInspection,
-} from '@/api/client'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { Field, FieldError, Input } from '@/components/form'
-import { GithubMark } from '@/components/github-mark'
-import { ManualAgentForm } from '@/components/manual-agent-form'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelFooter,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
-import { Skeleton } from '@/components/ui/skeleton'
-import {
- resolveAgentCreationMode,
- type AgentCreationMode,
-} from '@/lib/agent-creation-mode'
-import {
- isValidRepositoryRoot,
- normalizeRepositoryRoot,
- repositoryReviewPresentation,
- repositorySeedFromState,
- sourceChangedRequiresReview,
- type RepositorySeed,
-} from '@/lib/repository-onboarding'
-import { notifyError, notifySuccess } from '@/lib/errors'
-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.repository-import-command.v1'
-
-type ImportBody = Parameters<typeof importAgentFromGithub>[0]
-type ImportCommand = { fingerprint: string; key: string }
-type LinkedSource = DeployApp['repositories'][number]['linked_sources'][number]
-function existingAgentFromError(
- error: unknown,
-): { id: string; name: string; conflict: 'name' | 'source' } | null {
- if (
- !(error instanceof ApiError) ||
- (error.type !== 'name_conflict' && error.type !== 'source_already_linked')
- ) {
- return null
- }
- const existing = error.details?.existing_agent
- if (!existing || typeof existing !== 'object' || Array.isArray(existing))
- return null
- const row = existing as Record<string, unknown>
- return typeof row.id === 'string' && typeof row.name === 'string'
- ? {
- id: row.id,
- name: row.name,
- conflict: error.type === 'source_already_linked' ? 'source' : 'name',
- }
- : null
-}
-
-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 agentReviewError(error: unknown): string {
- if (error instanceof ApiError && error.type === 'builds_unavailable') {
- return 'Repository import is temporarily unavailable. Try reviewing the agent again.'
- }
- return error instanceof Error ? error.message : 'Agent review failed.'
-}
-
-function ModeButton({
- active,
- onClick,
- icon: Icon,
- title,
-}: {
- active: boolean
- onClick: () => void
- icon: typeof GithubMark | typeof Bot
- title: string
-}) {
- return (
- <button
- type="button"
- aria-pressed={active}
- onClick={onClick}
- className={cn(
- 'focus-visible:ring-ring/50 -mb-px flex h-11 items-center gap-2 border-b-2 px-1 text-sm transition-colors outline-none focus-visible:rounded-sm focus-visible:ring-3',
- active
- ? 'border-foreground text-foreground'
- : 'text-muted-foreground hover:text-foreground border-transparent',
- )}
- >
- <Icon className="size-4 shrink-0" aria-hidden />
- <span className="font-medium">{title}</span>
- </button>
- )
-}
-
-export function RepositoryStarterGuide() {
- return (
- <aside
- className="bg-panel rounded-lg border p-4 xl:sticky xl:top-24"
- aria-labelledby="starter-heading"
- >
- <div className="flex items-center gap-2">
- <GithubMark className="size-4" aria-hidden />
- <h2 id="starter-heading" className="text-sm font-semibold">
- Start with an example
- </h2>
- </div>
- <p className="text-muted-foreground mt-2 text-sm leading-6">
- Fork the Flue starter, add your agent logic, then deploy it here.
- </p>
- <div className="mt-4 flex flex-wrap gap-2 xl:flex-col">
- <Button variant="outline" className="justify-between" asChild>
- <a href={STARTER_FORK_URL} target="_blank" rel="noreferrer">
- Fork on GitHub
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- <Button variant="ghost" className="justify-between" asChild>
- <a href={STARTER_URL} target="_blank" rel="noreferrer">
- View repository
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- </div>
- </aside>
- )
-}
-
-export function RepositoryImportPanel({
- initialSource,
-}: {
- initialSource?: RepositorySeed
-}) {
- const deployAppQuery = useQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- refetchOnWindowFocus: 'always',
- })
-
- if (deployAppQuery.isLoading) {
- return (
- <Panel aria-busy="true">
- <PanelHeader>
- <div>
- <PanelTitle>Connect GitHub</PanelTitle>
- <PanelDescription className="mt-1">
- Loading your GitHub installation and repositories.
- </PanelDescription>
- </div>
- </PanelHeader>
- <PanelContent>
- <Skeleton className="h-10 w-full max-w-sm" />
- </PanelContent>
- </Panel>
- )
- }
-
- if (deployAppQuery.isError) {
- return (
- <Alert variant="destructive">
- <AlertTitle>GitHub import could not be loaded</AlertTitle>
- <AlertDescription>
- {deployAppQuery.error instanceof Error
- ? deployAppQuery.error.message
- : 'The GitHub installation request failed.'}
- </AlertDescription>
- <div className="mt-3">
- <Button
- size="sm"
- variant="outline"
- onClick={() => void deployAppQuery.refetch()}
- disabled={deployAppQuery.isFetching}
- >
- {deployAppQuery.isFetching ? (
- <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
- ) : null}
- Retry
- </Button>
- </div>
- </Alert>
- )
- }
-
- return deployAppQuery.data ? (
- <GithubImport app={deployAppQuery.data} initialSource={initialSource} />
- ) : null
-}
-
-function GithubImport({
- app,
- initialSource,
-}: {
- app: DeployApp
- initialSource?: RepositorySeed
-}) {
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const importCommand = useRef<ImportCommand | null>(null)
- const nameInput = useRef<HTMLInputElement>(null)
- const rootInput = useRef<HTMLInputElement>(null)
- const [repoSearch, setRepoSearch] = useState('')
- const initialRepo = app.repositories.find(
- (repo) => repo.id === initialSource?.repo,
- )
- const [repoPickerOpen, setRepoPickerOpen] = useState(!initialRepo)
- const [repoId, setRepoId] = useState(initialRepo?.id ?? '')
- const [productionRef, setProductionRef] = useState(
- initialRepo
- ? initialSource?.productionRef || initialRepo.default_branch || 'main'
- : '',
- )
- const [root, setRoot] = useState(initialRepo ? initialSource?.path || '' : '')
- const [name, setName] = useState('')
- const [unlinkingSource, setUnlinkingSource] = useState<LinkedSource | null>(
- null,
- )
-
- 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 showRepoPicker = repoPickerOpen || !selectedRepo
- const rootValid = isValidRepositoryRoot(root.trim())
-
- const inspectMutation = useMutation({
- mutationFn: (source?: RepositorySeed) =>
- reviewRepositoryAgent({
- repo: source?.repo ?? repoId,
- path: (source?.path ?? root).trim(),
- production_ref: (source?.productionRef ?? productionRef).trim(),
- }),
- onSuccess: (inspection) => {
- setRoot(inspection.root)
- if (
- inspection.interpretation.disposition === 'exact' &&
- inspection.profile
- ) {
- setName((current) => current || inspection.profile!.manifest.entrypoint)
- globalThis.requestAnimationFrame?.(() => nameInput.current?.focus())
- }
- },
- })
-
- 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}/setup?deployment=${encodeURIComponent(deployment.id)}`,
- )
- },
- onError: (error) => {
- if (existingAgentFromError(error)?.conflict === 'source') {
- void queryClient.invalidateQueries({ queryKey: ['deploy-app'] })
- }
- },
- })
- const unlinkMutation = useMutation({
- mutationFn: (source: LinkedSource) =>
- unlinkDeploymentSource(source.agent.id),
- onSuccess: (_result, source) => {
- queryClient.setQueryData<DeployApp>(['deploy-app'], (current) =>
- current
- ? {
- ...current,
- repositories: current.repositories.map((repo) => ({
- ...repo,
- linked_sources: repo.linked_sources.filter(
- (claim) => claim.agent.id !== source.agent.id,
- ),
- })),
- }
- : current,
- )
- void queryClient.invalidateQueries({ queryKey: ['deploy-app'] })
- void queryClient.invalidateQueries({ queryKey: ['agents'] })
- void queryClient.invalidateQueries({
- queryKey: ['agent-deploy-source', source.agent.id],
- })
- setUnlinkingSource(null)
- notifySuccess(
- `Repository unlinked from ${source.agent.name}.`,
- 'The agent, active revision, deployments, and sessions are unchanged.',
- )
- },
- onError: (error) => notifyError("Couldn't unlink the repository.", error),
- })
-
- const clearInspection = () => {
- inspectMutation.reset()
- importMutation.reset()
- }
-
- const changeSource = () => {
- setName('')
- clearInspection()
- globalThis.requestAnimationFrame?.(() => rootInput.current?.focus())
- }
-
- const selectRepo = (id: string) => {
- const repo = app.repositories.find((candidate) => candidate.id === id)
- setRepoId(id)
- setRepoPickerOpen(false)
- setRepoSearch('')
- setProductionRef(repo?.default_branch || 'main')
- setRoot('')
- setName('')
- clearInspection()
- }
-
- const inspection = inspectMutation.data
- const existingAgent = existingAgentFromError(importMutation.error)
- const sourceChanged = sourceChangedRequiresReview(importMutation.error)
- const reviewPresentation = inspection
- ? repositoryReviewPresentation(inspection)
- : null
- const exactInspection =
- inspection?.interpretation.disposition === 'exact' && inspection.profile
- ? inspection
- : null
- const linkedSourceFor = (path: string) =>
- selectedRepo?.linked_sources.find(
- (source) => source.path === normalizeRepositoryRoot(path),
- )
- const selectedLinkedSource = linkedSourceFor(root)
- const canInspect =
- !!selectedRepo &&
- !!productionRef.trim() &&
- rootValid &&
- !selectedLinkedSource &&
- !inspectMutation.isPending
- const canImport =
- !!exactInspection &&
- !!name.trim() &&
- !sourceChanged &&
- !selectedLinkedSource &&
- !importMutation.isPending &&
- !inspectMutation.isPending
-
- const deployAgent = () => {
- if (
- !exactInspection ||
- exactInspection.interpretation.disposition !== 'exact' ||
- !canImport
- )
- return
- importMutation.mutate({
- name: name.trim(),
- source: {
- type: 'github',
- repo: exactInspection.repository.id,
- path: exactInspection.root,
- production_ref: exactInspection.production_ref,
- },
- review: {
- sha: exactInspection.sha,
- source_profile: exactInspection.interpretation.source_profile,
- fingerprint: exactInspection.review_fingerprint,
- },
- credential: 'managed',
- })
- }
-
- const reviewAgain = () => {
- importMutation.reset()
- inspectMutation.mutate(undefined)
- }
-
- const chooseCandidate = (
- candidate: RepositorySourceInspection['candidate_roots'][number],
- ) => {
- const next = {
- repo: repoId,
- path: candidate.path,
- productionRef,
- }
- setRoot(candidate.path)
- setName('')
- clearInspection()
- inspectMutation.mutate(next)
- }
-
- 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>
- {inspection ? (
- <div className="min-w-0">
- <PanelTitle className="truncate">
- {inspection.repository.full_name}
- </PanelTitle>
- <PanelDescription className="mt-1 truncate">
- {inspection.production_ref}
- {' · '}
- {inspection.root || 'Repository root'}
- {' · '}
- <span className="font-mono">{shortSha(inspection.sha)}</span>
- </PanelDescription>
- </div>
- ) : (
- <div className="min-w-0">
- <PanelTitle className="truncate">
- {selectedRepo && !showRepoPicker
- ? selectedRepo.full_name
- : 'Choose repository'}
- </PanelTitle>
- <PanelDescription className="mt-1">
- {selectedRepo && !showRepoPicker
- ? 'Choose the production branch and agent folder to deploy.'
- : app.account
- ? `Repositories available to the OpenComputer App for ${app.account}.`
- : 'Repositories available to the OpenComputer App.'}
- </PanelDescription>
- </div>
- )}
- {inspection ? (
- <Button variant="ghost" size="sm" onClick={changeSource}>
- Change source
- </Button>
- ) : selectedRepo && !showRepoPicker ? (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => setRepoPickerOpen(true)}
- >
- Change repository
- </Button>
- ) : selectedRepo && showRepoPicker ? (
- <Button
- variant="ghost"
- size="sm"
- onClick={() => {
- setRepoPickerOpen(false)
- setRepoSearch('')
- }}
- >
- Cancel
- </Button>
- ) : 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>
- {!inspection ? (
- <>
- <PanelContent className="space-y-5 py-5">
- {showRepoPicker ? (
- <div className="space-y-2.5">
- <div className="relative">
- <Search
- className="text-muted-foreground pointer-events-none absolute top-2.5 left-3 size-4"
- aria-hidden
- />
- <Input
- value={repoSearch}
- onChange={(event) => setRepoSearch(event.target.value)}
- placeholder="Search repositories"
- aria-label="Search repositories"
- className="h-9 pl-9"
- />
- </div>
- <div
- role="group"
- aria-label="Repository"
- className="max-h-52 divide-y overflow-y-auto rounded-md border"
- >
- {repositories.length ? (
- repositories.map((repo) => {
- const rootClaim = repo.linked_sources.find(
- (source) => source.path === '',
- )
- const linkedLabel = rootClaim
- ? `Linked to ${rootClaim.agent.name}`
- : repo.linked_sources.length
- ? `${repo.linked_sources.length} linked ${repo.linked_sources.length === 1 ? 'root' : 'roots'}`
- : null
- return (
- <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.5 px-4 py-3 text-left outline-none focus-visible:ring-3 focus-visible:ring-inset',
- repo.id === repoId
- ? 'bg-row-selected'
- : 'hover:bg-row-hover',
- )}
- >
- <GithubMark className="size-4 shrink-0" />
- <span className="min-w-0 flex-1">
- <span className="block truncate text-sm font-medium">
- {repo.full_name}
- </span>
- <span className="text-muted-foreground mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 text-xs">
- {repo.private == null
- ? null
- : repo.private
- ? 'Private'
- : 'Public'}
- {repo.default_branch ? (
- <span className="flex items-center gap-1">
- <GitBranch className="size-3" />
- {repo.default_branch}
- </span>
- ) : null}
- {linkedLabel ? (
- <span className="text-foreground font-medium">
- {linkedLabel}
- </span>
- ) : null}
- </span>
- </span>
- <Check
- className={cn(
- 'size-4 shrink-0',
- repo.id === repoId
- ? 'opacity-100'
- : 'opacity-0',
- )}
- aria-hidden
- />
- </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>
- </div>
- ) : null}
-
- {selectedRepo && !showRepoPicker ? (
- <div className="grid gap-5 border-t pt-5 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 of at most 1,024 characters without . or .. segments.'
- }
- description="Leave empty to review the repository root."
- >
- <Input
- ref={rootInput}
- id="import-root"
- value={root}
- onChange={(event) => {
- setRoot(event.target.value)
- setName('')
- clearInspection()
- }}
- placeholder="agents/support"
- aria-invalid={!rootValid}
- />
- </Field>
- </div>
- ) : null}
-
- {selectedRepo && !showRepoPicker && selectedLinkedSource ? (
- <Alert>
- <AlertTitle>Repository root already linked</AlertTitle>
- <AlertDescription>
- {normalizeRepositoryRoot(root)
- ? `${selectedRepo.full_name}/${normalizeRepositoryRoot(root)}`
- : selectedRepo.full_name}{' '}
- is linked to{' '}
- <Link
- className="font-medium underline underline-offset-4"
- to={`/agents/${selectedLinkedSource.agent.id}`}
- >
- {selectedLinkedSource.agent.name}
- </Link>
- . One agent can own this repository root for deploy-on-push.
- </AlertDescription>
- <div className="mt-3 flex flex-wrap gap-2">
- <Button size="sm" variant="outline" asChild>
- <Link to={`/agents/${selectedLinkedSource.agent.id}`}>
- Open agent
- </Link>
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={unlinkMutation.isPending}
- onClick={() => setUnlinkingSource(selectedLinkedSource)}
- >
- <Unplug className="size-4" />
- Unlink repository
- </Button>
- </div>
- </Alert>
- ) : null}
-
- {inspectMutation.isError ? (
- <FieldError>
- {agentReviewError(inspectMutation.error)}
- </FieldError>
- ) : null}
- </PanelContent>
-
- {selectedRepo && !showRepoPicker ? (
- <PanelFooter className="justify-end">
- <Button
- type="button"
- disabled={!canInspect}
- onClick={() => inspectMutation.mutate(undefined)}
- >
- {inspectMutation.isPending ? (
- <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
- ) : null}
- {inspectMutation.isPending
- ? 'Reviewing agent…'
- : inspectMutation.isError
- ? 'Review agent again'
- : 'Review agent'}
- </Button>
- </PanelFooter>
- ) : null}
- </>
- ) : null}
- </Panel>
-
- {inspection?.interpretation.disposition === 'exact' &&
- inspection.profile ? (
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>{reviewPresentation?.heading}</PanelTitle>
- <PanelDescription className="mt-1">
- {inspection.profile.manifest.entrypoint}
- {' · '}
- <span className="font-mono">
- {inspection.profile.manifest.model}
- </span>
- </PanelDescription>
- {inspection.profile.source_profile === 'flue-prompt-v1' ? (
- <p className="text-muted-foreground mt-2 text-xs">
- prompt.md
- {' · '}
- {inspection.profile.skills.count}{' '}
- {inspection.profile.skills.count === 1 ? 'skill' : 'skills'}
- {' · '}
- built as a Flue app on OpenComputer
- </p>
- ) : null}
- </div>
- </PanelHeader>
- <PanelContent className="space-y-4">
- <Field
- label="Agent name"
- htmlFor="import-agent-name"
- description="Used in the dashboard and API."
- >
- <Input
- ref={nameInput}
- id="import-agent-name"
- value={name}
- onChange={(event) => {
- setName(event.target.value)
- importMutation.reset()
- }}
- placeholder="Support triage"
- />
- </Field>
- <p className="text-muted-foreground flex items-center gap-2 text-xs">
- <KeyRound className="size-3.5 shrink-0" aria-hidden />
- Model access is managed by OpenComputer.
- </p>
- {inspection.profile.warnings.map((warning) => (
- <Alert key={`${warning.code}:${warning.message}`}>
- <AlertTitle>Compatibility warning</AlertTitle>
- <AlertDescription>{warning.message}</AlertDescription>
- </Alert>
- ))}
- {selectedLinkedSource ? (
- <Alert>
- <AlertTitle>Repository root already linked</AlertTitle>
- <AlertDescription>
- This reviewed root is now linked to{' '}
- <Link
- className="font-medium underline underline-offset-4"
- to={`/agents/${selectedLinkedSource.agent.id}`}
- >
- {selectedLinkedSource.agent.name}
- </Link>
- . Unlink it before creating another agent from this root.
- </AlertDescription>
- <div className="mt-3 flex flex-wrap gap-2">
- <Button size="sm" variant="outline" asChild>
- <Link to={`/agents/${selectedLinkedSource.agent.id}`}>
- Open agent
- </Link>
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={unlinkMutation.isPending}
- onClick={() => setUnlinkingSource(selectedLinkedSource)}
- >
- <Unplug className="size-4" />
- Unlink repository
- </Button>
- </div>
- </Alert>
- ) : null}
- {importMutation.isError ? (
- <Alert
- variant={
- existingAgent || sourceChanged ? 'default' : 'destructive'
- }
- >
- <AlertTitle>
- {sourceChanged
- ? 'Repository changed since review'
- : existingAgent?.conflict === 'source'
- ? 'Repository already linked'
- : existingAgent
- ? 'Agent name already in use'
- : 'Agent could not be created'}
- </AlertTitle>
- <AlertDescription>
- {sourceChanged
- ? 'Nothing was created. Review the current commit before deploying it.'
- : existingAgent?.conflict === 'source'
- ? `This repository path is already linked to ${existingAgent.name}. Open the existing agent to deploy its latest commit.`
- : existingAgent
- ? `Another agent is already named ${existingAgent.name}. Choose a different name or open the existing agent.`
- : importMutation.error instanceof Error
- ? importMutation.error.message
- : 'The import request failed. You can retry without creating a duplicate.'}
- </AlertDescription>
- {sourceChanged ? (
- <div className="mt-3">
- <Button
- size="sm"
- onClick={reviewAgain}
- disabled={inspectMutation.isPending}
- >
- {inspectMutation.isPending ? (
- <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
- ) : null}
- Review agent again
- </Button>
- </div>
- ) : existingAgent ? (
- <div className="mt-3">
- <Button size="sm" asChild>
- <Link to={`/agents/${existingAgent.id}`}>Open agent</Link>
- </Button>
- </div>
- ) : null}
- </Alert>
- ) : null}
- </PanelContent>
- <PanelFooter className="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>
- </PanelFooter>
- </Panel>
- ) : inspection?.interpretation.disposition === 'invalid' ? (
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>{reviewPresentation?.heading}</PanelTitle>
- <PanelDescription className="mt-1">
- {reviewPresentation?.explanation}
- </PanelDescription>
- </div>
- </PanelHeader>
- <PanelContent className="space-y-3">
- {inspection.interpretation.issues.map((issue) => (
- <Alert
- key={`${issue.code}:${issue.path ?? ''}:${issue.message}`}
- variant="destructive"
- >
- <AlertTitle>{issue.path || issue.code}</AlertTitle>
- <AlertDescription>{issue.message}</AlertDescription>
- </Alert>
- ))}
- {inspection.interpretation.issues.length === 0 ? (
- <Alert variant="destructive">
- <AlertTitle>{inspection.interpretation.reason_code}</AlertTitle>
- <AlertDescription>
- {inspection.interpretation.summary}
- </AlertDescription>
- </Alert>
- ) : null}
- </PanelContent>
- <PanelFooter className="justify-between gap-2">
- <Button variant="ghost" onClick={changeSource}>
- Choose another folder
- </Button>
- <Button onClick={reviewAgain} disabled={inspectMutation.isPending}>
- {inspectMutation.isPending ? (
- <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
- ) : null}
- Review agent again
- </Button>
- </PanelFooter>
- </Panel>
- ) : inspection?.interpretation.disposition === 'unrecognized' ? (
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>{reviewPresentation?.heading}</PanelTitle>
- <PanelDescription className="mt-1">
- {reviewPresentation?.explanation}
- </PanelDescription>
- </div>
- </PanelHeader>
- <PanelContent className="space-y-4">
- {inspection.candidate_roots.length ? (
- <div
- className="divide-y overflow-hidden rounded-md border"
- aria-label="Candidate agent folders"
- >
- {inspection.candidate_roots.map((candidate) => {
- const linkedSource = linkedSourceFor(candidate.path)
- return (
- <div
- key={`${candidate.path}:${candidate.marker ?? ''}`}
- className="flex flex-col gap-3 px-3 py-3 sm:flex-row sm:items-center sm:justify-between"
- >
- <div className="min-w-0">
- <p className="truncate font-mono text-sm">
- {candidate.path || 'Repository root'}
- </p>
- <p className="text-muted-foreground mt-0.5 text-xs">
- {linkedSource
- ? `Already linked to ${linkedSource.agent.name}`
- : candidate.summary}
- </p>
- </div>
- {linkedSource ? (
- <div className="flex shrink-0 flex-wrap gap-1">
- <Button size="sm" variant="outline" asChild>
- <Link to={`/agents/${linkedSource.agent.id}`}>
- Open agent
- </Link>
- </Button>
- <Button
- size="sm"
- variant="ghost"
- disabled={unlinkMutation.isPending}
- onClick={() => setUnlinkingSource(linkedSource)}
- >
- Unlink
- </Button>
- </div>
- ) : (
- <Button
- size="sm"
- variant="outline"
- disabled={inspectMutation.isPending}
- onClick={() => chooseCandidate(candidate)}
- >
- {inspectMutation.isPending ? (
- <Loader2 className="size-4 animate-spin motion-reduce:animate-none" />
- ) : (
- <FolderSearch className="size-4" />
- )}
- Choose folder
- </Button>
- )}
- </div>
- )
- })}
- </div>
- ) : null}
- {inspection.candidate_roots_truncated ? (
- <Alert>
- <AlertTitle>More folders may match</AlertTitle>
- <AlertDescription>
- The bounded search was truncated. Choose a narrower root and
- review again.
- </AlertDescription>
- </Alert>
- ) : null}
- <div className="flex flex-wrap gap-2">
- {inspection.candidate_roots.length === 0 ? (
- <Button onClick={changeSource}>Choose another folder</Button>
- ) : null}
- <Button variant="outline" asChild>
- <a href={STARTER_FORK_URL} target="_blank" rel="noreferrer">
- Fork the Flue starter
- <ExternalLink className="size-3.5" />
- </a>
- </Button>
- <Button variant="ghost" asChild>
- <Link to="/agents/new?mode=manual">Configure manually</Link>
- </Button>
- </div>
- </PanelContent>
- </Panel>
- ) : null}
- <ConfirmDialog
- open={unlinkingSource != null}
- onOpenChange={(open) => {
- if (!open) setUnlinkingSource(null)
- }}
- title={`Unlink repository from ${unlinkingSource?.agent.name ?? 'this agent'}?`}
- description="Deploy-on-push from this repository root will stop. The existing agent, active revision, deployment history, and sessions will remain available. You can then import this root into the new agent."
- confirmLabel="Unlink repository"
- destructive
- pending={unlinkMutation.isPending}
- onConfirm={() => {
- if (unlinkingSource) unlinkMutation.mutate(unlinkingSource)
- }}
- />
- </div>
- )
-}
-
-export default function AgentNew() {
- const [searchParams, setSearchParams] = useSearchParams()
- const location = useLocation()
- const mode = resolveAgentCreationMode(searchParams.get('mode'))
- const setMode = (next: AgentCreationMode) =>
- setSearchParams(next === 'github' ? {} : { mode: 'manual' }, {
- replace: true,
- })
-
- return (
- <div className="mx-auto max-w-5xl">
- <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-7 max-w-2xl">
- <h1 className="text-xl font-semibold tracking-tight">Create agent</h1>
- <p className="text-muted-foreground mt-1 text-sm">
- Deploy an agent from an existing repository or configure one manually.
- </p>
- </div>
-
- <div
- className="mb-6 flex max-w-2xl gap-6 border-b"
- role="group"
- aria-label="Agent creation method"
- >
- <ModeButton
- active={mode === 'github'}
- onClick={() => setMode('github')}
- icon={GithubMark}
- title="Import from GitHub"
- />
- <ModeButton
- active={mode === 'manual'}
- onClick={() => setMode('manual')}
- icon={Bot}
- title="Configure manually"
- />
- </div>
-
- <div className="grid items-start gap-5 xl:grid-cols-[minmax(0,42rem)_17rem] xl:gap-8">
- <div className="order-2 min-w-0 xl:order-1">
- {mode === 'github' ? (
- <RepositoryImportPanel
- initialSource={repositorySeedFromState(location.state)}
- />
- ) : (
- <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>
- )}
- </div>
- <div className="order-1 xl:order-2">
- <RepositoryStarterGuide />
- </div>
- </div>
- </div>
- )
-}
diff --git a/web/src/pages/AgentSetup.tsx b/web/src/pages/AgentSetup.tsx
deleted file mode 100644
index aaf5e537..00000000
--- a/web/src/pages/AgentSetup.tsx
+++ /dev/null
@@ -1,811 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useParams, useSearchParams } from 'react-router-dom'
-import {
- CheckCircle2,
- ChevronRight,
- CircleAlert,
- ExternalLink,
- Loader2,
- MessageSquare,
- X,
-} from 'lucide-react'
-import {
- authorizeManagedSlack,
- getAgent,
- getAgentDeployment,
- getManagedSlackConnection,
- getSession,
- getSessionEvents,
- getSessions,
- type SessionEvent,
-} from '@/api/client'
-import {
- DeploymentLog,
- DeploymentPhases,
-} from '@/components/deployment-progress'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
-import { StatusBadge } from '@/components/status-badge'
-import { MessageBubble } from '@/components/session-conversation'
-import { ManagedSlackWorkspaceClaims } from '@/components/managed-slack-workspace-claims'
-import {
- Alert,
- AlertAction,
- AlertDescription,
- AlertTitle,
-} from '@/components/ui/alert'
-import { Button } from '@/components/ui/button'
-import { Skeleton } from '@/components/ui/skeleton'
-import { useAgentDeploymentLogs } from '@/hooks/use-agent-deployment-logs'
-import {
- RepositoryAccessPanel,
- RepositoryTaskSuggestion,
-} from '@/components/repository-access'
-import {
- agentSetupStage,
- agentSetupPresentation,
-} from '@/lib/agent-setup-presentation'
-import { agentDeploymentOutcome } from '@/lib/agent-deployment-outcome'
-import {
- agentCanStartNewSession,
- agentDeploymentDisplayStatus,
-} from '@/lib/agent-deployment-status'
-import { notifyError } from '@/lib/errors'
-import {
- managedSlackNotice,
- managedSlackOAuthPending,
-} from '@/lib/managed-slack-notice'
-import { useManagedSlackConnections } from '@/lib/managed-slack-connections'
-import { latestManagedSlackSession } from '@/lib/managed-slack-session'
-import { showRepositoryAccessDuringSetup } from '@/lib/repository-access'
-import {
- bodyText,
- isTerminalSessionStatus,
- isTurnInput,
-} from '@/lib/session-turns'
-import { cn } from '@/lib/utils'
-
-function previewText(text: string | null, max = 360): string | null {
- if (!text || text.length <= max) return text
- return `${text.slice(0, max).trimEnd()}…`
-}
-
-function conversationSettled(events: SessionEvent[] | undefined): boolean {
- return !!events?.some(
- (event) =>
- event.type === 'agent.message' ||
- event.type.toLowerCase().includes('error'),
- )
-}
-
-export default function AgentSetup() {
- const { agentId = '' } = useParams()
- const [searchParams, setSearchParams] = useSearchParams()
- const queryClient = useQueryClient()
- const [logsOpen, setLogsOpen] = useState(false)
- const deploymentId = searchParams.get('deployment') ?? ''
- const oauthResult = searchParams.get('slack')
- const connectedAgentId = searchParams.get('connected_agent')
- const sameOwnerConnectedAgentId =
- oauthResult === 'workspace_already_connected' &&
- connectedAgentId &&
- /^agt_[0-9a-f]{24}$/.test(connectedAgentId)
- ? connectedAgentId
- : null
-
- const agentQuery = useQuery({
- queryKey: ['agent', agentId],
- queryFn: () => getAgent(agentId),
- enabled: !!agentId,
- refetchInterval: (query) =>
- !deploymentId &&
- query.state.data &&
- !agentCanStartNewSession(query.state.data)
- ? 1500
- : false,
- })
- const deploymentQuery = useQuery({
- queryKey: ['agent-deployment', agentId, deploymentId],
- queryFn: () => getAgentDeployment(agentId, deploymentId),
- enabled: !!agentId && !!deploymentId,
- refetchInterval: (query) => {
- const deployment = query.state.data
- if (!deployment) return false
- if (
- deployment.state === 'ready' &&
- !deployment.allowed_actions.includes('start_session')
- ) {
- return 1500
- }
- return deployment.terminal ? false : 1500
- },
- })
- const managedSlackQuery = useQuery({
- queryKey: ['slack', 'managed', agentId],
- queryFn: () => getManagedSlackConnection(agentId),
- enabled: !!agentId,
- refetchInterval: (query) =>
- managedSlackOAuthPending(
- oauthResult,
- query.state.data?.status,
- query.state.data?.connected_at,
- )
- ? 1000
- : false,
- refetchOnWindowFocus: 'always',
- })
- const managedSlackConnectionsQuery = useManagedSlackConnections(!!agentId)
- const connectedAgentQuery = useQuery({
- queryKey: ['agent', sameOwnerConnectedAgentId],
- queryFn: () => getAgent(sameOwnerConnectedAgentId!),
- enabled: !!sameOwnerConnectedAgentId,
- })
- const deploymentCanStartSession =
- deploymentQuery.data?.allowed_actions.includes('start_session') ?? false
- const stage = agentSetupStage({
- hasDeployment: !!deploymentId,
- state: deploymentQuery.data?.state,
- terminal: deploymentQuery.data?.terminal,
- loadFailed: deploymentQuery.isError,
- canStartSession: deploymentCanStartSession,
- agentReady: agentQuery.data
- ? agentCanStartNewSession(agentQuery.data)
- : false,
- agentDeploymentState: agentQuery.data
- ? agentDeploymentDisplayStatus(agentQuery.data)
- : undefined,
- })
- const activationConnectedAt = managedSlackQuery.data?.connected_at ?? null
- const activationReady =
- stage === 'ready' &&
- managedSlackQuery.data?.status === 'active' &&
- !!activationConnectedAt
- const activationSessionsQuery = useQuery({
- queryKey: [
- 'agent-setup',
- 'managed-slack-sessions',
- agentId,
- activationConnectedAt,
- ],
- queryFn: () =>
- getSessions({
- agent: agentId,
- after: activationConnectedAt ?? undefined,
- limit: 100,
- }),
- enabled: !!agentId && activationReady,
- refetchInterval: (query) =>
- latestManagedSlackSession(query.state.data ?? [], activationConnectedAt)
- ? false
- : 1500,
- refetchOnWindowFocus: 'always',
- })
- const activationSession = latestManagedSlackSession(
- activationSessionsQuery.data ?? [],
- activationConnectedAt,
- )
- const activationEventsQuery = useQuery({
- queryKey: ['session-events', activationSession?.id],
- queryFn: () => getSessionEvents(activationSession!.id),
- enabled: !!activationSession,
- refetchInterval: (query) =>
- conversationSettled(query.state.data) ? false : 1000,
- refetchOnWindowFocus: 'always',
- })
- const activationEvents = activationEventsQuery.data ?? []
- const activationInput = activationEvents.find(isTurnInput)
- const activationReply = activationEvents.find(
- (event) => event.type === 'agent.message',
- )
- const activationError = activationEvents.find((event) =>
- event.type.toLowerCase().includes('error'),
- )
- const activationSessionQuery = useQuery({
- queryKey: ['session', activationSession?.id],
- queryFn: () => getSession(activationSession!.id),
- enabled: !!activationSession,
- refetchInterval: (query) =>
- conversationSettled(activationEvents) ||
- isTerminalSessionStatus(query.state.data?.status)
- ? false
- : 1500,
- refetchOnWindowFocus: 'always',
- })
- const logsQuery = useAgentDeploymentLogs({
- agentId,
- deploymentId,
- enabled: logsOpen,
- terminal: deploymentQuery.data?.terminal ?? false,
- })
- const authorizeManagedSlackMutation = useMutation({
- mutationFn: () => authorizeManagedSlack(agentId, deploymentId || undefined),
- onSuccess: (result) => {
- if ('authorize_url' in result) {
- window.location.assign(result.authorize_url)
- return
- }
- queryClient.setQueryData(['slack', 'managed', agentId], result)
- },
- onError: (error) =>
- notifyError("Couldn't start the Slack connection.", error),
- })
-
- if (agentQuery.isLoading || (deploymentId && deploymentQuery.isLoading)) {
- return (
- <div className="mx-auto max-w-3xl space-y-5">
- <Skeleton className="h-16 w-72 max-w-full" />
- <Skeleton className="h-64 w-full" />
- <Skeleton className="h-32 w-full" />
- </div>
- )
- }
-
- if (agentQuery.isError || !agentQuery.data) {
- return (
- <div className="mx-auto max-w-3xl space-y-5">
- <Alert variant="destructive">
- <AlertTitle>Agent setup could not be loaded</AlertTitle>
- <AlertDescription>
- {agentQuery.error instanceof Error
- ? agentQuery.error.message
- : 'Check that the agent exists and belongs to your account.'}
- </AlertDescription>
- </Alert>
- <Button variant="outline" asChild>
- <Link to="/agents">Back to agents</Link>
- </Button>
- </div>
- )
- }
-
- const agent = agentQuery.data
- const deployment = deploymentQuery.data
- const managedSlack = managedSlackQuery.data
- const managedSlackStatus = managedSlackQuery.isSuccess
- ? (managedSlack?.status ?? null)
- : undefined
- const presentation = agentSetupPresentation({
- agentName: agent.name,
- stage,
- managedStatus: managedSlackStatus,
- openUrl: managedSlack?.open_url,
- connecting: authorizeManagedSlackMutation.isPending,
- activated: !!activationSession,
- })
- const hasOtherManagedSlackConnections =
- managedSlackConnectionsQuery.data?.some(
- (connection) => connection.agent.id !== agentId,
- ) ?? false
- const checkingManagedSlackConnections =
- presentation.action === 'connect' && managedSlackConnectionsQuery.isLoading
- const managedWorkspace =
- managedSlack?.workspace?.name ?? managedSlack?.workspace?.id
- const waitingForConnectedState = managedSlackOAuthPending(
- oauthResult,
- managedSlack?.status,
- managedSlack?.connected_at,
- )
- const waitingForConnectedAgent =
- !!sameOwnerConnectedAgentId && connectedAgentQuery.isLoading
- const slackNotice =
- waitingForConnectedState || waitingForConnectedAgent
- ? null
- : managedSlackNotice(
- oauthResult,
- managedWorkspace,
- agent.name,
- connectedAgentQuery.data?.name,
- managedSlack?.status,
- )
- const connectedAgentHref =
- connectedAgentQuery.data && sameOwnerConnectedAgentId
- ? `/agents/${encodeURIComponent(sameOwnerConnectedAgentId)}`
- : null
- const dismissSlackNotice = () => {
- const next = new URLSearchParams(searchParams)
- next.delete('slack')
- next.delete('connected_agent')
- setSearchParams(next, { replace: true })
- }
- const deploymentHref = deploymentId
- ? `/agents/${agentId}/deployments/${deploymentId}`
- : null
- const deploymentOutcome = deployment
- ? agentDeploymentOutcome(deployment)
- : null
-
- return (
- <div className="mx-auto max-w-3xl space-y-4">
- <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
- <div className="space-y-1">
- <h1 className="text-lg font-semibold tracking-tight">
- Set up {agent.name}
- </h1>
- <p className="text-muted-foreground text-sm">
- Deploy the agent, connect Slack, and start the first conversation.
- </p>
- <div className="flex flex-wrap items-center gap-2 pt-1.5">
- <StatusBadge
- status={
- stage === 'preparing' ? (deployment?.state ?? 'pending') : stage
- }
- label={
- stage === 'ready'
- ? 'Agent ready'
- : stage === 'failed'
- ? 'Deployment failed'
- : 'Agent preparing'
- }
- />
- <StatusBadge
- status={managedSlackStatus === 'active' ? 'active' : 'stopped'}
- label={
- managedSlackStatus === 'active'
- ? 'Slack connected'
- : 'Slack not connected'
- }
- />
- </div>
- </div>
- <Button variant="ghost" size="sm" asChild>
- <Link to={`/agents/${agentId}`}>Finish later</Link>
- </Button>
- </header>
-
- {slackNotice ? (
- <Alert variant={slackNotice.destructive ? 'destructive' : 'default'}>
- <AlertTitle>{slackNotice.title}</AlertTitle>
- {slackNotice.description || connectedAgentHref ? (
- <AlertDescription>
- {slackNotice.description}{' '}
- {connectedAgentHref ? (
- <Link to={connectedAgentHref}>Open connected agent</Link>
- ) : null}
- </AlertDescription>
- ) : null}
- <AlertAction>
- <Button
- size="icon-sm"
- variant="ghost"
- aria-label="Dismiss Slack notice"
- onClick={dismissSlackNotice}
- >
- <X aria-hidden />
- </Button>
- </AlertAction>
- </Alert>
- ) : null}
-
- <Panel>
- <PanelContent className="px-5 py-5 sm:px-6 sm:py-6">
- <div className="flex max-w-2xl items-start gap-3">
- <div
- className={cn(
- 'flex size-9 shrink-0 items-center justify-center rounded-md',
- stage === 'failed'
- ? 'bg-status-error-bg text-status-error'
- : presentation.action === 'open'
- ? 'bg-status-running-bg text-status-running'
- : 'bg-muted text-foreground',
- )}
- >
- {stage === 'failed' ? (
- <CircleAlert className="size-5" aria-hidden />
- ) : presentation.action === 'open' ? (
- <CheckCircle2 className="size-5" aria-hidden />
- ) : (
- <MessageSquare className="size-5" aria-hidden />
- )}
- </div>
- <span className="sr-only" aria-live="polite" aria-atomic="true">
- {presentation.announcement}
- </span>
- <div className="min-w-0 flex-1">
- <h2 className="text-lg font-semibold tracking-tight">
- {presentation.title}
- </h2>
- <p className="text-muted-foreground mt-1.5 max-w-xl text-sm leading-relaxed">
- {presentation.description}
- </p>
-
- {presentation.action === 'connect' ? (
- <ManagedSlackWorkspaceClaims
- currentAgentId={agentId}
- currentAgentName={agent.name}
- query={managedSlackConnectionsQuery}
- className="mt-4"
- />
- ) : null}
-
- <div className="mt-4 flex flex-wrap items-center gap-3">
- {presentation.action === 'open' && managedSlack?.open_url ? (
- <>
- <Button asChild>
- <a
- href={managedSlack.open_url}
- target="_blank"
- rel="noreferrer"
- >
- {presentation.label}
- <ExternalLink className="size-4" />
- </a>
- </Button>
- {activationSession ? (
- <Button variant="outline" asChild>
- <Link to={`/agents/${agentId}`}>View agent</Link>
- </Button>
- ) : null}
- </>
- ) : presentation.action === 'connect' ||
- presentation.action === 'reconnect' ||
- presentation.action === 'connecting' ? (
- <Button
- disabled={
- authorizeManagedSlackMutation.isPending ||
- checkingManagedSlackConnections
- }
- onClick={() => authorizeManagedSlackMutation.mutate()}
- >
- {authorizeManagedSlackMutation.isPending ||
- checkingManagedSlackConnections ? (
- <Loader2
- className="size-4 animate-spin motion-reduce:animate-none"
- aria-hidden
- />
- ) : null}
- {checkingManagedSlackConnections
- ? 'Checking Slack…'
- : presentation.action === 'connect' &&
- hasOtherManagedSlackConnections
- ? 'Connect another workspace'
- : presentation.label}
- </Button>
- ) : stage === 'failed' && deploymentHref ? (
- <Button asChild>
- <Link to={deploymentHref}>
- Review deployment
- <ChevronRight className="size-4" />
- </Link>
- </Button>
- ) : managedSlackStatus === 'active' && stage === 'preparing' ? (
- <span className="text-muted-foreground inline-flex items-center gap-2 text-sm">
- <Loader2
- className="size-4 animate-spin motion-reduce:animate-none"
- aria-hidden
- />
- Finishing deployment…
- </span>
- ) : null}
- {presentation.action === 'connect' &&
- presentation.disclosure ? (
- <div className="max-w-sm text-xs leading-relaxed">
- <span className="text-muted-foreground">
- Anyone in this workspace who can message the app can use
- this agent.{' '}
- </span>
- <Link
- to={`/agents/${agentId}/settings?section=slack`}
- className="text-foreground underline underline-offset-4"
- >
- Use your own Slack app
- </Link>
- </div>
- ) : null}
- </div>
-
- {managedSlackQuery.isError && stage !== 'failed' ? (
- <div className="mt-3 flex items-center gap-2 text-xs">
- <span className="text-status-error">
- Slack status is unavailable.
- </span>
- <Button
- variant="ghost"
- size="sm"
- onClick={() => void managedSlackQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : presentation.status ? (
- <p className="text-muted-foreground mt-3 text-xs">
- {presentation.status}
- </p>
- ) : null}
- </div>
- </div>
- </PanelContent>
- {activationReady ? (
- <div
- className="border-t px-5 py-4 sm:px-6"
- aria-live="polite"
- aria-atomic="false"
- >
- <div className="flex flex-wrap items-start justify-between gap-2">
- <div>
- <p className="text-sm font-semibold">
- First Slack conversation
- </p>
- <p className="text-muted-foreground mt-0.5 text-xs">
- This page follows the same durable session shown elsewhere in
- OpenComputer.
- </p>
- </div>
- {activationSession ? (
- <StatusBadge
- status={
- activationSessionQuery.data?.status ??
- activationSession.status
- }
- />
- ) : null}
- </div>
-
- {activationSessionsQuery.isError ? (
- <div className="mt-4 flex flex-wrap items-center gap-2 text-sm">
- <span className="text-status-error">
- We couldn&apos;t check for your Slack message.
- </span>
- <Button
- size="sm"
- variant="outline"
- onClick={() => void activationSessionsQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : !activationSession ? (
- <div className="mt-4 flex items-start gap-3" role="status">
- <Loader2
- className="text-muted-foreground mt-0.5 size-4 shrink-0 animate-spin motion-reduce:animate-none"
- aria-hidden
- />
- <div>
- <p className="text-sm font-medium">
- Waiting for your first Slack message
- </p>
- <p className="text-muted-foreground mt-0.5 text-xs">
- Send a message to OpenComputer in Slack. The session and
- reply will appear here automatically.
- </p>
- </div>
- </div>
- ) : (
- <div className="mt-4">
- {activationEventsQuery.isError ? (
- <div className="flex flex-wrap items-center gap-2 text-sm">
- <span className="text-status-error">
- The session was created, but its messages could not be
- loaded.
- </span>
- <Button
- size="sm"
- variant="outline"
- onClick={() => void activationEventsQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : activationEventsQuery.isLoading ? (
- <div className="space-y-3">
- <Skeleton className="h-12 w-full" />
- <Skeleton className="h-12 w-4/5" />
- </div>
- ) : (
- <div className="space-y-4">
- {activationInput ? (
- <MessageBubble
- label="You"
- text={
- previewText(bodyText(activationInput)) ??
- 'Message received'
- }
- />
- ) : null}
- {activationReply ? (
- <MessageBubble
- label="Agent"
- text={
- previewText(bodyText(activationReply)) ??
- 'Reply available in the full session'
- }
- />
- ) : activationError ? (
- <div className="bg-status-error-bg/40 text-status-error rounded-md px-3 py-2 text-xs">
- {bodyText(activationError) ??
- 'The first turn needs attention. Open the session for details.'}
- </div>
- ) : (
- <div
- className="text-muted-foreground flex items-center gap-2 text-xs"
- role="status"
- >
- <Loader2
- className="size-3.5 animate-spin motion-reduce:animate-none"
- aria-hidden
- />
- Agent is replying…
- </div>
- )}
- </div>
- )}
- <div className="mt-4 flex flex-wrap items-center gap-2">
- <Button size="sm" variant="outline" asChild>
- <Link to={`/sessions/${activationSession.id}`}>
- Open session
- <ChevronRight className="size-4" />
- </Link>
- </Button>
- <Button size="sm" variant="ghost" asChild>
- <Link to={`/agents/${agentId}/sessions`}>
- All agent sessions
- </Link>
- </Button>
- </div>
- </div>
- )}
- </div>
- ) : null}
- </Panel>
-
- {showRepositoryAccessDuringSetup(agent.runtime, managedSlackStatus) ? (
- <div className="space-y-3">
- <RepositoryAccessPanel agentId={agentId} context="setup" />
- {stage === 'ready' && managedSlackStatus === 'active' ? (
- <RepositoryTaskSuggestion agentId={agentId} />
- ) : null}
- </div>
- ) : null}
-
- {deployment ? (
- <Panel>
- <PanelHeader className="flex-col gap-3 sm:flex-row sm:items-center">
- <div className="min-w-0">
- <PanelTitle>
- {stage === 'preparing'
- ? 'Preparing your agent'
- : stage === 'ready'
- ? 'Agent deployed'
- : 'Deployment failed'}
- </PanelTitle>
- <PanelDescription className="mt-1">
- {stage === 'preparing'
- ? 'Build and deployment continue in the background.'
- : deploymentOutcome?.description}
- </PanelDescription>
- </div>
- <DeploymentPhases deployment={deployment} />
- </PanelHeader>
- <PanelContent className="space-y-4">
- {stage === 'failed' && deploymentOutcome ? (
- <Alert variant="destructive">
- <AlertTitle>{deploymentOutcome.title}</AlertTitle>
- <AlertDescription>
- {deploymentOutcome.description}
- </AlertDescription>
- </Alert>
- ) : null}
-
- <details
- className="group rounded-md border"
- onToggle={(event) => setLogsOpen(event.currentTarget.open)}
- >
- <summary className="hover:bg-muted focus-visible:ring-ring/50 flex cursor-pointer list-none items-center gap-2 rounded-md px-3 py-2.5 text-sm font-medium focus-visible:ring-2 focus-visible:outline-none [&::-webkit-details-marker]:hidden">
- <ChevronRight
- className="text-muted-foreground size-4 transition-transform group-open:rotate-90 motion-reduce:transition-none"
- aria-hidden
- />
- Build and deploy logs
- </summary>
- <div className="border-t p-3">
- {logsQuery.isError ? (
- <Alert variant="destructive">
- <AlertTitle>Logs 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 logs
- </Button>
- </div>
- </Alert>
- ) : logsQuery.isLoading ? (
- <Skeleton className="h-52 w-full" />
- ) : (
- <DeploymentLog
- logs={logsQuery.data?.data ?? []}
- terminal={deployment.terminal}
- />
- )}
- </div>
- </details>
-
- <div className="flex justify-end">
- <Button variant="ghost" size="sm" asChild>
- <Link to={deploymentHref!}>
- View deployment details
- <ChevronRight className="size-4" />
- </Link>
- </Button>
- </div>
- </PanelContent>
- </Panel>
- ) : deploymentQuery.isError ? (
- <Alert variant="destructive">
- <AlertTitle>Deployment status could not be loaded</AlertTitle>
- <AlertDescription>
- {deploymentQuery.error instanceof Error
- ? deploymentQuery.error.message
- : 'Open the agent to review its current deployment.'}
- </AlertDescription>
- <div className="mt-2 flex flex-wrap gap-2">
- <Button
- variant="outline"
- size="sm"
- onClick={() => void deploymentQuery.refetch()}
- >
- Retry status
- </Button>
- {deploymentHref ? (
- <Button variant="ghost" size="sm" asChild>
- <Link to={deploymentHref}>Open deployment</Link>
- </Button>
- ) : null}
- </div>
- </Alert>
- ) : stage === 'ready' ? (
- <div className="bg-panel flex items-center gap-3 rounded-lg border px-4 py-3">
- <CheckCircle2
- className="text-status-running size-5 shrink-0"
- aria-hidden
- />
- <div className="min-w-0">
- <p className="text-sm font-medium">Agent ready</p>
- <p className="text-muted-foreground text-xs">
- Your agent is ready to use.
- </p>
- </div>
- </div>
- ) : stage === 'preparing' ? (
- <div className="bg-panel flex items-center gap-3 rounded-lg border px-4 py-3">
- <Loader2
- className="text-status-pending size-5 shrink-0 animate-spin motion-reduce:animate-none"
- aria-hidden
- />
- <div className="min-w-0">
- <p className="text-sm font-medium">Preparing your agent</p>
- <p className="text-muted-foreground text-xs">
- Setup is following the latest deployment in the background.
- </p>
- </div>
- </div>
- ) : (
- <Alert variant="destructive">
- <AlertTitle>The latest deployment needs attention</AlertTitle>
- <AlertDescription>
- Open the agent to review its deployment history and recovery
- actions.
- </AlertDescription>
- <div className="mt-2">
- <Button variant="outline" size="sm" asChild>
- <Link to={`/agents/${agentId}/deployments`}>
- Open deployments
- </Link>
- </Button>
- </div>
- </Alert>
- )}
- </div>
- )
-}
diff --git a/web/src/pages/Agents.tsx b/web/src/pages/Agents.tsx
deleted file mode 100644
index 97bddbdd..00000000
--- a/web/src/pages/Agents.tsx
+++ /dev/null
@@ -1,155 +0,0 @@
-import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useNavigate } from 'react-router-dom'
-import { Bot, Plus } from 'lucide-react'
-import { getAgents, getDeployApp, type Agent } from '@/api/client'
-import { EmptyState } from '@/components/empty-state'
-import { PageHeader } from '@/components/page-header'
-import { Panel } from '@/components/panel'
-import { ResourceTable, type Column } from '@/components/resource-table'
-import { StatusBadge } from '@/components/status-badge'
-import { Button } from '@/components/ui/button'
-import { agentDeploymentDisplayStatus } from '@/lib/agent-deployment-status'
-
-export default function Agents() {
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const { data: agents, isLoading } = useQuery({
- queryKey: ['agents'],
- queryFn: getAgents,
- })
-
- const columns: Column<Agent>[] = [
- {
- key: 'name',
- header: 'Name',
- cell: (agent) => (
- <Link
- to={`/agents/${agent.id}`}
- className="text-foreground font-medium underline-offset-4 hover:underline"
- >
- {agent.name}
- </Link>
- ),
- },
- {
- key: 'model',
- header: 'Model',
- cell: (agent) => (
- <code className="text-muted-foreground font-mono text-xs">
- {agent.model}
- </code>
- ),
- },
- {
- key: 'runtime',
- header: 'Runtime',
- cell: (agent) => (
- <span className="text-muted-foreground text-xs capitalize">
- {agent.runtime}
- </span>
- ),
- },
- {
- key: 'deployment',
- header: 'Deployment',
- cell: (agent) => {
- const status = agentDeploymentDisplayStatus(agent)
- const deploymentId = agent.deployment_status?.deployment_id
- if (!deploymentId) return <StatusBadge status={status} />
- return (
- <Link
- to={`/agents/${agent.id}/deployments/${deploymentId}`}
- aria-label={`Open latest deployment for ${agent.name}: ${status.replace(/_/g, ' ')}`}
- className="focus-visible:ring-ring/50 inline-flex rounded-md outline-none focus-visible:ring-3"
- >
- <StatusBadge status={status} />
- </Link>
- )
- },
- },
- {
- key: 'revision',
- header: 'Active revision',
- align: 'right',
- cell: (agent) => (
- <span className="text-muted-foreground font-mono text-xs">
- {agent.active_revision
- ? `#${agent.active_revision.number}`
- : agent.revision && agent.revision > 0
- ? `#${agent.revision}`
- : 'Not deployed'}
- </span>
- ),
- },
- {
- key: 'created',
- header: 'Created',
- cell: (agent) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(agent.created_at).toLocaleDateString()}
- </span>
- ),
- },
- ]
-
- const prefetchCreate = () => {
- void import('@/pages/AgentNew')
- void queryClient.prefetchQuery({
- queryKey: ['deploy-app'],
- queryFn: getDeployApp,
- staleTime: 30_000,
- })
- }
- const openCreate = () => {
- prefetchCreate()
- void navigate('/agents/new')
- }
-
- const createIntentProps = {
- onPointerEnter: prefetchCreate,
- onFocus: prefetchCreate,
- }
-
- return (
- <div>
- <PageHeader
- title="Agents"
- description="Reusable agents, from built-in prompts to Flue code deployed from a repository."
- api={{
- method: 'POST',
- path: '/v3/agents',
- sdk: 'oc.agents.create()',
- docs: 'https://docs.opencomputer.dev/agent-sessions/agents',
- }}
- actions={
- <Button onClick={openCreate} {...createIntentProps}>
- <Plus className="size-4" />
- Create agent
- </Button>
- }
- />
-
- <Panel className="overflow-hidden">
- <ResourceTable
- columns={columns}
- rows={agents ?? []}
- rowKey={(agent) => agent.id}
- loading={isLoading}
- empty={
- <EmptyState
- icon={Bot}
- title="No agents yet"
- description="Import an agent from a repository, or configure one manually."
- action={
- <Button size="sm" onClick={openCreate} {...createIntentProps}>
- <Plus className="size-4" />
- Create agent
- </Button>
- }
- />
- }
- />
- </Panel>
- </div>
- )
-}
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx
index 8104b4c1..58b9dc1a 100644
--- a/web/src/pages/Dashboard.tsx
+++ b/web/src/pages/Dashboard.tsx
@@ -1,38 +1,18 @@
-import { useEffect, useRef, type KeyboardEvent } from 'react'
+import { useEffect, useRef } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useLocation, useSearchParams } from 'react-router-dom'
-import {
- Bot,
- Boxes,
- Check,
- Code2,
- Copy,
- ExternalLink,
- KeyRound,
- MessagesSquare,
-} from 'lucide-react'
+import { Link, useLocation } from 'react-router-dom'
+import { Boxes, Check, Copy, ExternalLink, KeyRound } from 'lucide-react'
import {
createAPIKey,
getAPIKeys,
getSandboxes,
- getSessions,
- getAgents,
type Sandbox,
} from '@/api/client'
-import type { Session } from '@/api/schemas'
import { usePrefetchSandbox } from '@/hooks/use-prefetch'
import { PageHeader } from '@/components/page-header'
-import {
- Panel,
- PanelContent,
- PanelDescription,
- PanelHeader,
- PanelTitle,
-} from '@/components/panel'
+import { Panel, PanelHeader, PanelTitle } from '@/components/panel'
import { MetricCard } from '@/components/metric-card'
import { CopyRow } from '@/components/copy-row'
-import { GithubMark } from '@/components/github-mark'
-import { ManualAgentForm } from '@/components/manual-agent-form'
import { StatusBadge } from '@/components/status-badge'
import { EmptyState } from '@/components/empty-state'
import { ResourceTable, type Column } from '@/components/resource-table'
@@ -40,7 +20,6 @@ import { Button } from '@/components/ui/button'
import { notifyError } from '@/lib/errors'
import { useTransientFlag } from '@/lib/use-transient-flag'
import { cn } from '@/lib/utils'
-import { RepositoryImportPanel, RepositoryStarterGuide } from './AgentNew'
const SANDBOX_API_CODE = `const sandbox = await Sandbox.create();
const result =
@@ -49,40 +28,6 @@ const result =
console.log(result.stdout);
await sandbox.kill();`
-const SESSION_API_CODE = `const oc = new OpenComputer({ apiKey });
-const session = await oc.sessions.create({
- agent: "agt_...",
- input: "Triage support requests.",
-});
-console.log(session.id);`
-
-type StartDirection = 'github' | 'prompt' | 'api'
-
-const START_DIRECTIONS = [
- {
- id: 'github',
- title: 'Agent from GitHub',
- description: 'Deploy a Flue repository.',
- icon: GithubMark,
- },
- {
- id: 'prompt',
- title: 'Agent from a prompt',
- description: 'Claude Code, Codex, or Pi.',
- icon: Bot,
- },
- {
- id: 'api',
- title: 'Build with the API',
- description: 'Durable sessions & sandboxes.',
- icon: Code2,
- },
-] as const
-
-function startDirection(value: string | null): StartDirection {
- return value === 'prompt' || value === 'api' ? value : 'github'
-}
-
function formatDuration(sandbox: Sandbox): string {
const start = new Date(sandbox.startedAt).getTime()
const end = sandbox.stoppedAt
@@ -94,24 +39,6 @@ function formatDuration(sandbox: Sandbox): string {
return `${Math.round((secs / 3600) * 10) / 10}h`
}
-// A session is "live" until it reaches a terminal state. Excluding terminal
-// states (rather than allow-listing live ones) keeps new/unknown live statuses
-// counted as active.
-const TERMINAL_SESSION = new Set([
- 'archived',
- 'failed',
- 'completed',
- 'complete',
- 'canceled',
- 'cancelled',
- 'error',
- 'errored',
- 'done',
- 'expired',
-])
-const isLiveSession = (s: Session) =>
- !TERMINAL_SESSION.has(s.status.toLowerCase())
-
export default function Dashboard() {
const prefetch = usePrefetchSandbox()
const location = useLocation()
@@ -128,79 +55,23 @@ export default function Dashboard() {
queryKey: ['sandboxes', ''],
queryFn: () => getSandboxes(),
})
- const { data: sessionsData, isLoading: loadingSessions } = useQuery({
- queryKey: ['sessions'],
- queryFn: () => getSessions(),
- })
- const { data: agentsData } = useQuery({
- queryKey: ['agents'],
- queryFn: getAgents,
- })
const activeSandboxes = runningSandboxesData ?? []
const allSandboxes = allSandboxesData ?? []
- const sessions = sessionsData ?? []
- const agents = agentsData ?? []
const today = new Date().toISOString().slice(0, 10)
const isToday = (iso: string) =>
new Date(iso).toISOString().slice(0, 10) === today
const sandboxesToday = allSandboxes.filter((s) => isToday(s.startedAt)).length
- const activeSessions = sessions.filter(isLiveSession)
- const sessionsToday = sessions.filter((s) => isToday(s.created_at)).length
-
- const agentName = (id?: string | null) =>
- agents.find((a) => a.id === id)?.name ?? id ?? '—'
- // First-run only when the org has neither sessions nor sandboxes — an org that
- // already runs agent sessions (but no raw sandboxes) is not a new user.
- const isFirstRun =
- !loadingSandboxes &&
- !loadingSessions &&
- allSandboxes.length === 0 &&
- sessions.length === 0
+ // First-run only when the org has no sandboxes yet.
+ const isFirstRun = !loadingSandboxes && allSandboxes.length === 0
// Genuine first-run auto-shows onboarding; returning users reach it via the
// left-nav "Getting started" item (/getting-started).
const showOnboarding = isFirstRun || onGettingStartedRoute
- const sessionColumns: Column<Session>[] = [
- {
- key: 'id',
- header: 'Session',
- cell: (s) => (
- <Link
- to={`/sessions/${s.id}`}
- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"
- >
- {s.id}
- </Link>
- ),
- },
- {
- key: 'agent',
- header: 'Agent',
- cell: (s) => (
- <span className="text-muted-foreground">{agentName(s.agent_id)}</span>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (s) => <StatusBadge status={s.status} />,
- },
- {
- key: 'created',
- header: 'Created',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(s.created_at).toLocaleString()}
- </span>
- ),
- },
- ]
-
const sandboxColumns: Column<Sandbox>[] = [
{
key: 'id',
@@ -253,7 +124,7 @@ export default function Dashboard() {
{!showOnboarding && (
<PageHeader
title="Dashboard"
- description="Overview of your agent sessions and sandboxes"
+ description="Overview of your sandboxes"
/>
)}
@@ -261,17 +132,7 @@ export default function Dashboard() {
<GettingStarted />
) : (
<div className="space-y-6">
- <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
- <MetricCard
- label="Active agent sessions"
- value={
- loadingSessions ? '—' : activeSessions.length.toLocaleString()
- }
- />
- <MetricCard
- label="Agent sessions today"
- value={loadingSessions ? '—' : sessionsToday.toLocaleString()}
- />
+ <div className="grid grid-cols-2 gap-4">
<MetricCard
label="Active sandboxes"
value={
@@ -286,31 +147,6 @@ export default function Dashboard() {
/>
</div>
- <Panel className="overflow-hidden">
- <PanelHeader>
- <PanelTitle>Recent agent sessions</PanelTitle>
- <Link
- to="/sessions"
- className="text-muted-foreground hover:text-foreground text-xs underline-offset-4 hover:underline"
- >
- View all
- </Link>
- </PanelHeader>
- <ResourceTable
- columns={sessionColumns}
- rows={sessions.slice(0, 10)}
- rowKey={(s) => s.id}
- loading={loadingSessions}
- empty={
- <EmptyState
- icon={MessagesSquare}
- title="No sessions yet"
- description="Start a session from an agent to give it a durable task."
- />
- }
- />
- </Panel>
-
<Panel className="overflow-hidden">
<PanelHeader>
<PanelTitle>Recent sandboxes</PanelTitle>
@@ -344,9 +180,6 @@ export default function Dashboard() {
/* ── First-run onboarding ─────────────────────────────────────────────────── */
export function GettingStarted() {
const queryClient = useQueryClient()
- const [searchParams, setSearchParams] = useSearchParams()
- const selectedDirection = startDirection(searchParams.get('start'))
- const directionRefs = useRef<Array<HTMLButtonElement | null>>([])
const keysQuery = useQuery({
queryKey: ['api-keys'],
queryFn: getAPIKeys,
@@ -372,231 +205,90 @@ export function GettingStarted() {
}
}, [keysQuery.isSuccess, hasKeys, createdKey, createMutation])
- const selectDirection = (direction: StartDirection) => {
- setSearchParams(direction === 'github' ? {} : { start: direction }, {
- replace: true,
- })
- }
-
- const onDirectionKeyDown = (
- event: KeyboardEvent<HTMLButtonElement>,
- index: number,
- ) => {
- let nextIndex: number | null = null
- if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
- nextIndex = (index + 1) % START_DIRECTIONS.length
- } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
- nextIndex =
- (index - 1 + START_DIRECTIONS.length) % START_DIRECTIONS.length
- } else if (event.key === 'Home') {
- nextIndex = 0
- } else if (event.key === 'End') {
- nextIndex = START_DIRECTIONS.length - 1
- }
- if (nextIndex == null) return
-
- event.preventDefault()
- selectDirection(START_DIRECTIONS[nextIndex].id)
- requestAnimationFrame(() => directionRefs.current[nextIndex]?.focus())
- }
-
return (
<div className="mx-auto max-w-5xl pb-12">
- <div
- className="bg-border grid gap-px overflow-hidden rounded-lg border sm:grid-cols-3"
- role="tablist"
- aria-label="Choose how to start"
- >
- {START_DIRECTIONS.map((direction, index) => {
- const active = selectedDirection === direction.id
- const Icon = direction.icon
- return (
- <button
- key={direction.id}
- ref={(node) => {
- directionRefs.current[index] = node
- }}
- id={`start-tab-${direction.id}`}
- type="button"
- role="tab"
- aria-selected={active}
- aria-controls={`start-panel-${direction.id}`}
- tabIndex={active ? 0 : -1}
- onClick={() => selectDirection(direction.id)}
- onKeyDown={(event) => onDirectionKeyDown(event, index)}
- className={cn(
- 'focus-visible:ring-ring/50 bg-background flex min-h-24 items-start gap-3 p-4 text-left transition-colors outline-none focus-visible:z-10 focus-visible:ring-3 focus-visible:ring-inset',
- active ? 'bg-row-selected' : 'hover:bg-row-hover',
- )}
- >
- <div aria-hidden>
- <Icon
- className={cn(
- 'mt-0.5 size-4 shrink-0',
- active ? 'text-foreground' : 'text-muted-foreground',
- )}
- />
- </div>
- <span className="min-w-0">
- <span className="block text-sm font-semibold">
- {direction.title}
- </span>
- <span className="text-muted-foreground mt-1 block text-xs leading-5">
- {direction.description}
- </span>
- </span>
- </button>
- )
- })}
- </div>
-
- {selectedDirection === 'github' ? (
- <section
- id="start-panel-github"
- role="tabpanel"
- aria-labelledby="start-tab-github"
- className="mt-8"
- >
- <div className="grid items-start gap-6 xl:grid-cols-3">
- <div className="min-w-0 xl:col-span-2">
- <RepositoryImportPanel />
+ <Panel className="p-5">
+ <div className="grid gap-4 sm:grid-cols-[11rem_minmax(0,1fr)] sm:items-start">
+ <div className="flex items-center gap-2">
+ <KeyRound className="text-muted-foreground size-4" aria-hidden />
+ <div>
+ <h2 className="text-sm font-semibold">Your API key</h2>
+ <p className="text-muted-foreground mt-0.5 text-xs">
+ OPENCOMPUTER_API_KEY
+ </p>
</div>
- <RepositoryStarterGuide />
</div>
- </section>
- ) : null}
- {selectedDirection === 'prompt' ? (
- <section
- id="start-panel-prompt"
- role="tabpanel"
- aria-labelledby="start-tab-prompt"
- className="mt-8"
- >
- <Panel>
- <PanelHeader>
- <div>
- <PanelTitle>Define the agent</PanelTitle>
- <PanelDescription className="mt-1">
- Create a durable agent from its system prompt. You can connect
- Slack after creation.
- </PanelDescription>
+ <div className="min-w-0">
+ {keysQuery.isLoading || createMutation.isPending ? (
+ <p className="text-muted-foreground py-2 text-sm">
+ Preparing your API key…
+ </p>
+ ) : null}
+
+ {createdKey ? (
+ <div className="space-y-2">
+ <CopyRow value={createdKey} maskable />
+ <p className="text-muted-foreground text-xs">
+ Copy it now. For security, it cannot be shown again.
+ </p>
</div>
- </PanelHeader>
- <PanelContent>
- <ManualAgentForm
- layout="wide"
- onCancel={() => selectDirection('github')}
- />
- </PanelContent>
- </Panel>
- </section>
- ) : null}
-
- {selectedDirection === 'api' ? (
- <section
- id="start-panel-api"
- role="tabpanel"
- aria-labelledby="start-tab-api"
- className="mt-8"
- >
- <Panel className="p-5">
- <div className="grid gap-4 sm:grid-cols-[11rem_minmax(0,1fr)] sm:items-start">
- <div className="flex items-center gap-2">
- <KeyRound
- className="text-muted-foreground size-4"
- aria-hidden
- />
- <div>
- <h2 className="text-sm font-semibold">Your API key</h2>
- <p className="text-muted-foreground mt-0.5 text-xs">
- OPENCOMPUTER_API_KEY
- </p>
- </div>
+ ) : null}
+
+ {!createdKey && !createMutation.isPending && hasKeys ? (
+ <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
+ <p className="text-muted-foreground text-sm">
+ API key ready. Existing secret values cannot be displayed.
+ </p>
+ <Button size="sm" variant="outline" asChild>
+ <Link to="/api-keys">Manage keys</Link>
+ </Button>
</div>
+ ) : null}
- <div className="min-w-0">
- {keysQuery.isLoading || createMutation.isPending ? (
- <p className="text-muted-foreground py-2 text-sm">
- Preparing your API key…
- </p>
- ) : null}
-
- {createdKey ? (
- <div className="space-y-2">
- <CopyRow value={createdKey} maskable />
- <p className="text-muted-foreground text-xs">
- Copy it now. For security, it cannot be shown again.
- </p>
- </div>
- ) : null}
-
- {!createdKey && !createMutation.isPending && hasKeys ? (
- <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
- <p className="text-muted-foreground text-sm">
- API key ready. Existing secret values cannot be displayed.
- </p>
- <Button size="sm" variant="outline" asChild>
- <Link to="/api-keys">Manage keys</Link>
- </Button>
- </div>
- ) : null}
-
- {keysQuery.isError ? (
- <div className="flex flex-wrap items-center gap-3">
- <span className="text-status-error text-sm">
- Couldn&apos;t load your API keys.
- </span>
- <Button
- size="sm"
- variant="outline"
- onClick={() => void keysQuery.refetch()}
- >
- Retry
- </Button>
- </div>
- ) : null}
-
- {createMutation.isError ? (
- <div className="flex flex-wrap items-center gap-3">
- <span className="text-status-error text-sm">
- Couldn&apos;t create your API key.
- </span>
- <Button
- size="sm"
- variant="outline"
- onClick={() => createMutation.mutate()}
- >
- Retry
- </Button>
- </div>
- ) : null}
+ {keysQuery.isError ? (
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="text-status-error text-sm">
+ Couldn&apos;t load your API keys.
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => void keysQuery.refetch()}
+ >
+ Retry
+ </Button>
</div>
- </div>
- </Panel>
+ ) : null}
- <div className="mt-8 grid gap-10 md:grid-cols-2 md:gap-0 md:divide-x">
- <ApiExample
- icon={MessagesSquare}
- title="Durable agent sessions"
- description="Start and steer a durable agent run."
- code={SESSION_API_CODE}
- docs="https://docs.opencomputer.dev/agent-sessions/quickstart"
- docsLabel="Open sessions quickstart"
- className="md:pr-8"
- />
- <ApiExample
- icon={Boxes}
- title="Sandboxes"
- description="Run commands in an isolated computer."
- code={SANDBOX_API_CODE}
- docs="https://docs.opencomputer.dev/quickstart"
- docsLabel="Open sandbox quickstart"
- className="md:pl-8"
- />
+ {createMutation.isError ? (
+ <div className="flex flex-wrap items-center gap-3">
+ <span className="text-status-error text-sm">
+ Couldn&apos;t create your API key.
+ </span>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => createMutation.mutate()}
+ >
+ Retry
+ </Button>
+ </div>
+ ) : null}
</div>
- </section>
- ) : null}
+ </div>
+ </Panel>
+
+ <div className="mt-8">
+ <ApiExample
+ icon={Boxes}
+ title="Sandboxes"
+ description="Run commands in an isolated computer."
+ code={SANDBOX_API_CODE}
+ docs="https://docs.opencomputer.dev/quickstart"
+ docsLabel="Open sandbox quickstart"
+ />
+ </div>
</div>
)
}
diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsx
deleted file mode 100644
index c73dc3bd..00000000
--- a/web/src/pages/SessionDetail.tsx
+++ /dev/null
@@ -1,942 +0,0 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
-import { Link, useParams, useLocation } from 'react-router-dom'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import {
- ArrowLeft,
- Send,
- Wrench,
- CircleAlert,
- Brain,
- CheckCircle2,
- XCircle,
- Sparkles,
-} from 'lucide-react'
-import { GuidedTour, type GuideStep } from '@/components/guided-tour'
-import { notifyError } from '@/lib/errors'
-import { useHalted } from '@/hooks/useHalted'
-import { WORK_PAUSED, WORK_PAUSED_TITLE } from '@/lib/billing-onramp'
-import {
- getSession,
- getSessionSources,
- getSessionEvents,
- sendMessage,
- cancelSession,
- archiveSession,
- ApiError,
- type SessionEvent,
- type SessionSource,
-} from '@/api/client'
-import { SessionEventSchema } from '@/api/schemas'
-import { Panel } from '@/components/panel'
-import { Button } from '@/components/ui/button'
-import { ChatTextarea } from '@/components/chat-textarea'
-import { Skeleton } from '@/components/ui/skeleton'
-import { StatusBadge } from '@/components/status-badge'
-import { RuntimeBadge } from '@/components/runtime-badge'
-import { MetricCard } from '@/components/metric-card'
-import { SessionTurns } from '@/components/session-turns'
-import { EmptyState } from '@/components/empty-state'
-import { ConfirmDialog } from '@/components/confirm-dialog'
-import { SessionWebhooks } from '@/components/session-webhooks'
-import { ApiHint } from '@/components/api-hint'
-import { MessagesSquare } from 'lucide-react'
-import { cn } from '@/lib/utils'
-import { GithubMark } from '@/components/github-mark'
-import {
- formatUsageCost,
- formatUsageDuration,
- formatUsageTokens,
- usageDisclosure,
-} from '@/lib/usage'
-import {
- HttpRequestCard,
- MessageBubble,
- TurnConversation,
-} from '@/components/session-conversation'
-import {
- bodyText,
- groupIntoTurns,
- httpRequestPayloadText,
- isOutOfCredits,
- isTurnInput,
-} from '@/lib/session-turns'
-import {
- canSessionChangeFlueSources,
- isFlueSession,
- sessionSourcesRefetchInterval,
-} from '@/lib/session-source-polling'
-
-function toolSummary(ev: SessionEvent): string {
- const b = (ev.body ?? {}) as Record<string, unknown>
- const tool = typeof b.tool === 'string' ? b.tool : 'tool'
- const input = typeof b.input === 'string' ? b.input : ''
- return input ? `${tool} · ${input}` : tool
-}
-// A tool RESULT — brain-box emits `exec.completed`, the flue tailer emits `tool.result`;
-// both land here so flue + brain-box render identically.
-function isToolResult(ev: SessionEvent): boolean {
- return ev.type === 'exec.completed' || ev.type === 'tool.result'
-}
-function toolResult(ev: SessionEvent): { text: string; isError: boolean } {
- const b = (ev.body ?? {}) as Record<string, unknown>
- const tool = typeof b.tool === 'string' ? b.tool : 'tool'
- const isError = b.is_error === true || b.error != null
- const summary =
- (typeof b.summary === 'string' && b.summary) ||
- (typeof b.output === 'string' && b.output) ||
- (typeof b.text === 'string' && b.text) ||
- ''
- const dur = typeof b.duration_ms === 'number' ? ` · ${b.duration_ms}ms` : ''
- return {
- text: summary ? `${tool} → ${summary}${dur}` : `${tool} →${dur}`,
- isError,
- }
-}
-// The body spilled to blob storage (event > 32KB) — surface an affordance instead of
-// rendering an empty bubble.
-function truncationNote(ev: SessionEvent): string | null {
- if (!ev.body_truncated && !ev.content_ref) return null
- const kb = ev.body_bytes ? ` (${Math.round(ev.body_bytes / 1024)} KB)` : ''
- return `Output too large to inline${kb} — stored in blob`
-}
-function humanizeType(t: string): string {
- return t.replace(/[._]/g, ' ').replace(/^\w/, (c) => c.toUpperCase())
-}
-
-function turnCompletionLabel(ev: SessionEvent): string | null {
- if (ev.type !== 'turn.completed' || !ev.body) return null
- const body = ev.body as Record<string, unknown>
- if (typeof body.outcome === 'string') return humanizeType(body.outcome)
- if (typeof body.yield_reason === 'string') {
- return humanizeType(body.yield_reason)
- }
- return null
-}
-
-interface TurnStartInfo {
- from: number | null
- to: number | null
- preview: string | null
-}
-
-const LEVELS = [
- { value: 'all', label: 'All' },
- { value: 'user', label: 'Conversation' },
-] as const
-type LevelFilter = (typeof LEVELS)[number]['value']
-
-export default function SessionDetail() {
- const { sessionId = '' } = useParams()
- const queryClient = useQueryClient()
- const halted = useHalted() // top-level: must run before any early return (Rules of Hooks)
- const [draft, setDraft] = useState('')
- const [level, setLevel] = useState<LevelFilter>('user')
- const [confirmCancel, setConfirmCancel] = useState(false)
- const [liveStream, setLiveStream] = useState<{
- sessionId: string
- events: SessionEvent[]
- connected: boolean
- }>(() => ({ sessionId, events: [], connected: false }))
- const streamOk = liveStream.sessionId === sessionId && liveStream.connected
-
- // Guided first-run overlay: the chip launch passes { guide: 'agent' } via nav
- // state; the "How it works" button reopens it any time. Anchors point at the
- // real regions below (header / event stream / composer).
- const location = useLocation()
- const headerRef = useRef<HTMLDivElement>(null)
- const eventsRef = useRef<HTMLDivElement>(null)
- const composerRef = useRef<HTMLFormElement>(null)
- const [guideOpen, setGuideOpen] = useState(
- () => (location.state as { guide?: string } | null)?.guide === 'agent',
- )
- const guideSteps: GuideStep[] = useMemo(
- () => [
- {
- target: headerRef,
- title: 'This session came from two API calls',
- body: 'Clicking the example created a managed agent, then started a session on it — the dashboard just called the public API on your behalf.',
- api: 'POST /v3/agents · POST /v3/sessions',
- code: [
- {
- label: 'SDK',
- code: `import { OpenComputer } from "@opencomputer/sdk";
-const oc = new OpenComputer({ apiKey: process.env.OPENCOMPUTER_API_KEY });
-
-const agent = await oc.agents.create({
- runtime: "claude",
- model: "anthropic/claude-opus-4-8",
- credential: "managed",
-});
-
-const session = await oc.sessions.create({
- agent: agent.id,
- input: "Give me a quick tour of this sandbox.",
-});`,
- },
- {
- label: 'CLI',
- code: `oc agent create my-agent \\
- --runtime claude --model anthropic/claude-opus-4-8 --credential managed
-
-oc session create --agent my-agent \\
- --input "Give me a quick tour of this sandbox."`,
- },
- {
- label: 'API',
- code: `# 1. Create a managed agent
-curl -X POST https://api.opencomputer.dev/v3/agents \\
- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"runtime":"claude","model":"anthropic/claude-opus-4-8","credential":"managed"}'
-
-# 2. Start a session on that agent
-curl -X POST https://api.opencomputer.dev/v3/sessions \\
- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"agent":"agt_...","input":"Give me a quick tour of this sandbox."}'`,
- },
- ],
- docs: 'https://docs.opencomputer.dev/agent-sessions/quickstart',
- },
- {
- target: eventsRef,
- title: "This is the session's live event log",
- body: 'Every turn the agent takes streams here over SSE — the same feed you consume in code, no polling.',
- api: 'GET /v3/sessions/:id/events',
- code: [
- {
- label: 'SDK',
- code: `// session is the handle returned by oc.sessions.create()
-for await (const event of session.events()) {
- console.log(event.type, event.body);
-}`,
- },
- { label: 'CLI', code: `oc session logs $SESSION_ID` },
- {
- label: 'API',
- code: `curl -N https://api.opencomputer.dev/v3/sessions/$SESSION_ID/events?stream=sse \\
- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY"
-# server-sent events stream: one event per line`,
- },
- ],
- docs: 'https://docs.opencomputer.dev/agent-sessions/sessions',
- },
- {
- target: composerRef,
- title: 'Steer it from here',
- body: 'Sending a message posts more input to the same session — the agent picks it up on its next turn.',
- api: 'POST /v3/sessions/:id/messages',
- code: [
- {
- label: 'SDK',
- code: `await session.steer("Also add a dark mode toggle.");`,
- },
- {
- label: 'CLI',
- code: `oc session steer $SESSION_ID "Also add a dark mode toggle."`,
- },
- {
- label: 'API',
- code: `curl -X POST https://api.opencomputer.dev/v3/sessions/$SESSION_ID/messages \\
- -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \\
- -H "Content-Type: application/json" \\
- -d '{"text":"Also add a dark mode toggle."}'`,
- },
- ],
- docs: 'https://docs.opencomputer.dev/agent-sessions/messaging',
- },
- ],
- [],
- )
-
- const { data: session, isLoading } = useQuery({
- queryKey: ['session', sessionId],
- queryFn: () => getSession(sessionId),
- refetchInterval: 5000,
- })
- // Initial history, plus a polling fallback while the live stream is down.
- const { data: eventData } = useQuery({
- queryKey: ['session-events', sessionId],
- queryFn: () => getSessionEvents(sessionId),
- refetchInterval: streamOk ? false : 5000,
- })
- const sourcesEnabled = isFlueSession(session)
- const sourcesCanChange = canSessionChangeFlueSources(session)
- const sourcesQuery = useQuery({
- queryKey: ['session-sources', sessionId],
- queryFn: () => getSessionSources(sessionId),
- enabled: sourcesEnabled,
- staleTime: 15_000,
- refetchInterval: sourcesCanChange
- ? (query) => sessionSourcesRefetchInterval(query.state.data)
- : false,
- refetchIntervalInBackground: false,
- refetchOnWindowFocus: sourcesCanChange ? 'always' : false,
- })
-
- // Live events over SSE through the dashboard proxy (the proxy injects auth;
- // EventSource can't set headers). It replays history then streams live, and
- // auto-reconnects with Last-Event-ID. Skipped under the preview mock (no
- // backend) — the query renders there.
- useEffect(() => {
- if (!sessionId || import.meta.env.VITE_PREVIEW === '1') return
- const es = new EventSource(
- `/api/dashboard/v3/sessions/${sessionId}/events?stream=sse`,
- { withCredentials: true },
- )
- es.onopen = () =>
- setLiveStream((prev) => ({
- sessionId,
- events: prev.sessionId === sessionId ? prev.events : [],
- connected: true,
- }))
- es.onmessage = (e) => {
- let raw: unknown
- try {
- raw = JSON.parse(e.data as string)
- } catch {
- return
- }
- const parsed = SessionEventSchema.safeParse(raw)
- if (!parsed.success) return
- const ev = parsed.data
- setLiveStream((prev) => {
- const events = prev.sessionId === sessionId ? prev.events : []
- return {
- sessionId,
- connected: prev.sessionId === sessionId && prev.connected,
- // Cap the in-memory live buffer (older events remain in query history).
- events: events.some((x) => x.id === ev.id)
- ? events
- : [...events, ev].slice(-2000),
- }
- })
- }
- es.onerror = () =>
- setLiveStream((prev) =>
- prev.sessionId === sessionId ? { ...prev, connected: false } : prev,
- ) // EventSource retries on its own
- return () => es.close()
- }, [sessionId])
-
- const invalidate = () => {
- void queryClient.invalidateQueries({ queryKey: ['session', sessionId] })
- void queryClient.invalidateQueries({
- queryKey: ['session-events', sessionId],
- })
- }
-
- const steerMutation = useMutation({
- mutationFn: () => sendMessage(sessionId, draft.trim(), crypto.randomUUID()),
- onSuccess: () => {
- setDraft('')
- invalidate()
- },
- onError: (e) => {
- // Race/stale-state fallback: if the server refused on credits, refresh the halt
- // state so the banner + composer gating appear at once (don't wait for the poll).
- if (e instanceof ApiError && e.type === 'insufficient_credits') {
- void queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })
- }
- notifyError("Couldn't send the message.", e)
- },
- })
- const cancelMutation = useMutation({
- mutationFn: () => cancelSession(sessionId),
- onSettled: invalidate,
- onError: (e) => notifyError("Couldn't cancel the session.", e),
- })
- const archiveMutation = useMutation({
- mutationFn: () => archiveSession(sessionId),
- onSettled: invalidate,
- onError: (e) => notifyError("Couldn't archive the session.", e),
- })
-
- // History (query) ∪ this session's live SSE events, deduped by id, by seq.
- const allEvents = useMemo(() => {
- const liveEvents =
- liveStream.sessionId === sessionId ? liveStream.events : []
- const byId = new Map<string, SessionEvent>()
- for (const e of eventData ?? []) byId.set(e.id, e)
- for (const e of liveEvents) {
- if (e.session && e.session !== sessionId) continue
- byId.set(e.id, e)
- }
- const sorted = [...byId.values()].sort((a, b) => a.seq - b.seq)
- // Collapse the safety-net twin: the runtime emits a turn's final assistant text as
- // BOTH agent.message@progress (streamed) and agent.message@user (the answer), so it
- // would render twice in the "all" view. Drop the @progress copy when an identical-text
- // @user message exists in the same turn.
- const userAnswers = new Set(
- sorted
- .filter((e) => e.type === 'agent.message' && e.level === 'user')
- .map((e) => `${e.turn_id ?? ''} ${bodyText(e) ?? ''}`),
- )
- return sorted.filter(
- (e) =>
- !(
- e.type === 'agent.message' &&
- e.level === 'progress' &&
- bodyText(e) &&
- userAnswers.has(`${e.turn_id ?? ''} ${bodyText(e) ?? ''}`)
- ),
- )
- }, [eventData, liveStream, sessionId])
-
- // Group the (unfiltered) stream by turn: turn.started is level:progress, so it
- // must be read from allEvents, never the level==='user' filter.
- const grouped = useMemo(() => groupIntoTurns(allEvents), [allEvents])
- // Inputs whose neutral turn has not crossed the durable start boundary.
- const pendingSeqs = useMemo(
- () =>
- new Set([
- ...grouped.pending.map((event) => event.seq),
- ...grouped.groups
- .filter((group) => group.state === 'queued')
- .flatMap((group) =>
- group.events.filter(isTurnInput).map((event) => event.seq),
- ),
- ]),
- [grouped],
- )
- // Per-turn seq range + input preview, so the All log's turn.started row is
- // self-describing instead of a bare orphan marker.
- const turnStartInfo = useMemo(() => {
- const m = new Map<string, TurnStartInfo>()
- for (const g of grouped.groups) {
- const firstInput = g.events.find(isTurnInput)
- const raw = firstInput
- ? (bodyText(firstInput) ?? httpRequestPayloadText(firstInput))
- : null
- const compact = raw?.replace(/\s+/g, ' ') ?? null
- const preview =
- compact && compact.length > 40 ? `${compact.slice(0, 40)}…` : compact
- m.set(g.turnId, { from: g.fromSeq, to: g.toSeq, preview })
- }
- return m
- }, [grouped])
-
- if (isLoading) {
- return (
- <div className="space-y-4">
- <Skeleton className="h-20 w-full" />
- <Skeleton className="h-96 w-full" />
- </div>
- )
- }
-
- const status = session?.status ?? 'unknown'
- const archived = status === 'archived'
- const canSteer = !archived
- const canCancel = status === 'running' || status === 'awaiting_input'
-
- const isEmpty =
- level === 'user'
- ? grouped.groups.length === 0 && grouped.pending.length === 0
- : allEvents.length === 0
-
- return (
- <div className="max-w-4xl">
- <GuidedTour
- steps={guideSteps}
- open={guideOpen}
- onClose={() => setGuideOpen(false)}
- />
- <Link
- to="/sessions"
- className="text-muted-foreground hover:text-foreground mb-4 inline-flex items-center gap-1.5 text-sm"
- >
- <ArrowLeft className="size-4" />
- Sessions
- </Link>
-
- {/* Header */}
- <Panel ref={headerRef} className="mb-4 p-5">
- <div className="flex flex-wrap items-start justify-between gap-4">
- <div className="min-w-0 space-y-1.5">
- <div className="flex flex-wrap items-center gap-2.5">
- <code className="text-foreground font-mono text-sm">
- {sessionId}
- </code>
- <StatusBadge status={status} />
- {session?.agent_snapshot?.runtime ? (
- <RuntimeBadge runtime={session.agent_snapshot.runtime} />
- ) : null}
- </div>
- <p className="text-muted-foreground text-xs">
- {session?.head ?? 0} events · created{' '}
- {session?.created_at
- ? new Date(session.created_at).toLocaleString()
- : '—'}
- </p>
- {session?.sandboxes?.brain || session?.sandboxes?.hands ? (
- <p className="text-muted-foreground flex flex-wrap items-center gap-x-1.5 text-xs">
- <span>Sandboxes:</span>
- {session.sandboxes.brain ? (
- <Link
- to={`/sandboxes/${session.sandboxes.brain}`}
- className="hover:text-foreground font-mono underline-offset-4 hover:underline"
- >
- brain
- </Link>
- ) : null}
- {session.sandboxes.brain && session.sandboxes.hands ? (
- <span>·</span>
- ) : null}
- {session.sandboxes.hands ? (
- <Link
- to={`/sandboxes/${session.sandboxes.hands}`}
- className="hover:text-foreground font-mono underline-offset-4 hover:underline"
- >
- hands
- </Link>
- ) : null}
- </p>
- ) : null}
- <ApiHint
- method="GET"
- path="/v3/sessions/:id"
- sdk="oc.sessions.get()"
- docs="https://docs.opencomputer.dev/agent-sessions/sessions"
- />
- </div>
- <div className="flex items-center gap-2">
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground"
- onClick={() => setGuideOpen(true)}
- >
- <Sparkles className="size-3.5" />
- How it works
- </Button>
- {canCancel ? (
- <Button
- variant="outline"
- size="sm"
- onClick={() => setConfirmCancel(true)}
- >
- Cancel run
- </Button>
- ) : null}
- {!archived ? (
- <Button
- variant="ghost"
- size="sm"
- className="text-muted-foreground hover:text-status-error"
- onClick={() => archiveMutation.mutate()}
- disabled={archiveMutation.isPending}
- >
- Archive
- </Button>
- ) : null}
- </div>
- </div>
- </Panel>
-
- <SessionSourcesPanel
- sources={sourcesQuery.data}
- loading={sourcesQuery.isLoading}
- error={sourcesQuery.isError}
- onRetry={() => void sourcesQuery.refetch()}
- />
-
- {/* Usage is the durable rollup of terminal turns. Missing turn observations stay
- unknown, and incomplete totals are visibly lower bounds. */}
- <div className="mb-4 grid grid-cols-2 gap-4 sm:grid-cols-4">
- <MetricCard
- label="Tokens"
- value={formatUsageTokens(session?.usage)}
- hint={usageDisclosure(session?.usage)}
- />
- <MetricCard
- label="Active time"
- value={formatUsageDuration(session?.usage)}
- />
- <MetricCard
- label="Cost"
- value={formatUsageCost(session?.usage)}
- hint="Runtime-reported"
- />
- <MetricCard
- label="Events"
- value={(session?.head ?? 0).toLocaleString()}
- />
- </div>
-
- {/* Event stream */}
- <Panel ref={eventsRef} className="overflow-hidden">
- <div className="flex items-center justify-between border-b px-4 py-2.5">
- <div className="flex items-center gap-2">
- <h2 className="text-sm font-semibold">Events</h2>
- {streamOk ? (
- // mt-[3px] drops the label to optically sit with "Events"; the dot stays
- // line-centered with the "LIVE" text (values dialed in against the browser).
- <span className="text-status-running mt-[3px] flex items-center gap-1 text-[10px] leading-none font-medium tracking-wide uppercase">
- <span className="bg-status-running size-1.5 rounded-full" />
- Live
- </span>
- ) : null}
- </div>
- <div className="flex gap-1">
- {LEVELS.map((l) => (
- <button
- key={l.value}
- onClick={() => setLevel(l.value)}
- className={cn(
- 'rounded-sm px-2 py-1 text-xs transition-colors',
- level === l.value
- ? 'bg-secondary text-foreground font-medium'
- : 'text-muted-foreground hover:text-foreground',
- )}
- >
- {l.label}
- </button>
- ))}
- </div>
- </div>
-
- {isEmpty ? (
- <EmptyState
- icon={MessagesSquare}
- title="No events yet"
- description="Events from the agent's turns will stream in here."
- />
- ) : level === 'user' ? (
- <TurnConversation
- grouped={grouped}
- halted={halted}
- sessionStatus={status}
- />
- ) : (
- <ul className="divide-y">
- {allEvents.map((ev) => (
- <EventRow
- key={ev.id}
- ev={ev}
- pending={pendingSeqs}
- bounds={turnStartInfo}
- />
- ))}
- </ul>
- )}
-
- {/* Steer */}
- <div className="border-t p-3">
- {halted && !archived && (
- <div className="text-destructive mb-2 flex items-center gap-1.5 text-xs">
- <CircleAlert className="size-3.5 shrink-0" />
- <span>
- {WORK_PAUSED}{' '}
- <Link
- to="/billing"
- className="font-medium underline underline-offset-2"
- >
- Open Billing
- </Link>{' '}
- to resume.
- </span>
- </div>
- )}
- <form
- ref={composerRef}
- className="flex items-end gap-2"
- onSubmit={(e) => {
- e.preventDefault()
- if (draft.trim() && canSteer && !halted) steerMutation.mutate()
- }}
- >
- <ChatTextarea
- value={draft}
- onChange={(e) => setDraft(e.target.value)}
- onSend={() => {
- if (
- draft.trim() &&
- canSteer &&
- !halted &&
- !steerMutation.isPending
- ) {
- steerMutation.mutate()
- }
- }}
- placeholder={
- halted
- ? WORK_PAUSED_TITLE
- : canSteer
- ? 'Send a message to steer the session…'
- : 'Session archived'
- }
- disabled={!canSteer || halted}
- className="min-h-10 flex-1"
- />
- <Button
- type="submit"
- title="Enter to send · Shift+Enter for newline"
- disabled={
- !draft.trim() || !canSteer || halted || steerMutation.isPending
- }
- >
- <Send className="size-4" />
- Send
- </Button>
- </form>
- {status === 'running' && !halted && !archived ? (
- <p className="text-muted-foreground mt-2 text-xs">
- Agent is working — your message will run in the next turn.
- </p>
- ) : null}
- </div>
- </Panel>
-
- <SessionTurns
- sessionId={sessionId}
- active={
- status === 'running' ||
- status === 'awaiting_input' ||
- status === 'queued'
- }
- />
-
- <SessionWebhooks sessionId={sessionId} />
-
- <ConfirmDialog
- open={confirmCancel}
- onOpenChange={setConfirmCancel}
- title="Cancel this run?"
- description="The current turn stops. You can steer the session again afterward."
- confirmLabel="Cancel run"
- destructive
- pending={cancelMutation.isPending}
- onConfirm={() =>
- cancelMutation.mutate(undefined, {
- onSuccess: () => setConfirmCancel(false),
- })
- }
- />
- </div>
- )
-}
-
-export function SessionSourcesPanel({
- sources,
- loading,
- error,
- onRetry,
-}: {
- sources?: SessionSource[]
- loading: boolean
- error: boolean
- onRetry: () => void
-}) {
- if (!loading && !error && !sources?.length) return null
- return (
- <Panel className="mb-4 min-w-0 overflow-hidden">
- <div className="flex min-w-0 flex-wrap items-center justify-between gap-2 border-b px-4 py-2.5">
- <h2 className="flex items-center gap-2 text-sm font-semibold">
- <GithubMark className="size-3.5" /> Working sources
- </h2>
- <span className="text-muted-foreground text-xs">
- {sources?.length ?? 0}{' '}
- {sources?.length === 1 ? 'repository' : 'repositories'}
- </span>
- </div>
- {loading ? (
- <div className="space-y-2 p-4">
- <Skeleton className="h-10 w-full" />
- </div>
- ) : error ? (
- <div className="flex items-center justify-between gap-3 px-4 py-3 text-sm">
- <span className="text-muted-foreground">
- Couldn’t load working sources.
- </span>
- <Button size="sm" variant="outline" onClick={onRetry}>
- Retry
- </Button>
- </div>
- ) : (
- <ul className="divide-y">
- {sources?.map((source) => {
- const observedDiffers =
- source.resolved_sha && source.resolved_sha !== source.sha
- return (
- <li
- key={source.name}
- className="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-4 gap-y-1 px-4 py-3 text-xs sm:grid-cols-[minmax(0,1fr)_auto_minmax(0,auto)]"
- >
- <div className="min-w-48 flex-1">
- <p
- className="truncate text-sm font-medium"
- title={source.full_name ?? source.repo_id ?? source.name}
- >
- {source.full_name ?? source.repo_id ?? source.name}
- </p>
- <p
- className="text-muted-foreground mt-0.5 truncate font-mono"
- title={`Pinned commit ${source.sha}`}
- >
- {source.requested_ref ? `${source.requested_ref} · ` : ''}
- {source.sha.slice(0, 8)}
- </p>
- {observedDiffers ? (
- <p
- className="text-status-error mt-0.5 font-mono text-[11px]"
- title={`Observed commit ${source.resolved_sha}`}
- >
- observed {source.resolved_sha?.slice(0, 8)}
- </p>
- ) : null}
- </div>
- <StatusBadge status={source.status} />
- <code
- className="text-muted-foreground col-span-2 min-w-0 truncate sm:col-span-1 sm:max-w-52"
- title={source.path}
- >
- {source.path}
- </code>
- {source.error_message ? (
- <p className="text-status-error col-span-2 w-full sm:col-span-3">
- {source.error_message}
- </p>
- ) : null}
- </li>
- )
- })}
- </ul>
- )}
- </Panel>
- )
-}
-
-function EventRow({
- ev,
- pending,
- bounds,
-}: {
- ev: SessionEvent
- pending: Set<number>
- bounds: Map<string, TurnStartInfo>
-}) {
- const text = bodyText(ev)
- const trunc = truncationNote(ev)
- const completion = turnCompletionLabel(ev)
-
- // Reasoning — muted, set apart from the answer. (flue tailer + brain-box both emit this.)
- if (ev.type === 'agent.thinking') {
- if (!text && !trunc) return null
- return (
- <li className="text-muted-foreground flex gap-2 px-4 py-2 text-xs italic">
- <Brain className="mt-0.5 size-3.5 shrink-0 opacity-60" />
- <span className="whitespace-pre-wrap">{text ?? trunc}</span>
- </li>
- )
- }
-
- if (ev.type === 'http.request') {
- return (
- <li className="px-4 py-3">
- <HttpRequestCard
- event={ev}
- seq={ev.seq}
- meta={
- pending.has(ev.seq) ? (
- <span className="text-muted-foreground text-[10px]">
- · queued
- </span>
- ) : undefined
- }
- />
- </li>
- )
- }
-
- // Conversation messages — the signal.
- if (ev.type === 'user.message' || ev.type === 'agent.message') {
- const isUser = ev.type === 'user.message'
- return (
- <li className="px-4 py-3">
- <MessageBubble
- label={ev.actor?.display ?? (isUser ? 'You' : 'Agent')}
- text={text ?? trunc}
- seq={ev.seq}
- // Input typed while a turn was running but not yet claimed by a turn.
- meta={
- isUser && pending.has(ev.seq) ? (
- <span className="text-muted-foreground text-[10px]">
- · queued
- </span>
- ) : undefined
- }
- outOfCredits={isOutOfCredits(ev)}
- />
- </li>
- )
- }
-
- // Turn started — de-orphaned: self-describing with its seq range + input preview.
- if (ev.type === 'turn.started') {
- const info = bounds.get(ev.turn_id ?? '')
- const range =
- info && info.from != null
- ? ` · running #${info.from}${info.to != null && info.to > info.from ? `–#${info.to}` : ''}`
- : ''
- const preview = info?.preview ? ` : "${info.preview}"` : ''
- return (
- <li className="text-muted-foreground flex items-center gap-2 px-4 py-1.5 text-xs">
- <span className="bg-border h-px w-4 shrink-0" />
- {`Turn started${range}${preview}`}
- </li>
- )
- }
-
- // Tool calls — compact mono.
- if (ev.type === 'tool.call') {
- return (
- <li className="text-muted-foreground flex items-center gap-2 px-4 py-1.5 font-mono text-xs">
- <Wrench className="size-3.5 shrink-0 opacity-60" />
- <span className="truncate">{toolSummary(ev)}</span>
- </li>
- )
- }
-
- // Tool results — `exec.completed` (brain-box) or `tool.result` (flue). Error results
- // get the error tone; success stays quiet. Body-spill falls back to the truncation note.
- if (isToolResult(ev)) {
- const { text: rtext, isError } = toolResult(ev)
- const Icon = isError ? XCircle : CheckCircle2
- return (
- <li
- className={cn(
- 'flex items-center gap-2 px-4 py-1.5 font-mono text-xs',
- isError ? 'text-status-error' : 'text-muted-foreground',
- )}
- >
- <Icon className="size-3.5 shrink-0 opacity-70" />
- <span className="truncate">{trunc ?? rtext}</span>
- </li>
- )
- }
-
- // Failures — turn.failed + any error* event.
- if (ev.type === 'turn.failed' || ev.type.startsWith('error')) {
- const reason =
- typeof (ev.body as Record<string, unknown> | null | undefined)
- ?.yield_reason === 'string'
- ? String((ev.body as Record<string, unknown>).yield_reason)
- : null
- return (
- <li className="bg-status-error-bg/40 text-status-error flex items-center gap-2 px-4 py-2 text-xs">
- <CircleAlert className="size-3.5 shrink-0" />
- <span>{text ?? reason ?? humanizeType(ev.type)}</span>
- </li>
- )
- }
-
- // Turn markers + everything else — quiet context line.
- return (
- <li className="text-muted-foreground flex items-center gap-2 px-4 py-1.5 text-xs">
- <span className="bg-border h-px w-4 shrink-0" />
- {humanizeType(ev.type)}
- {completion ? ` · ${completion}` : ''}
- </li>
- )
-}
diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsx
deleted file mode 100644
index 8ff119a5..00000000
--- a/web/src/pages/Sessions.tsx
+++ /dev/null
@@ -1,359 +0,0 @@
-import { useState } from 'react'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import { Link, useNavigate } from 'react-router-dom'
-import { MessagesSquare, Plus } from 'lucide-react'
-import { notifyError } from '@/lib/errors'
-import { useHalted } from '@/hooks/useHalted'
-import { WORK_PAUSED_TITLE } from '@/lib/billing-onramp'
-import { getSessions, getAgents, createSession, ApiError } from '@/api/client'
-import type { Session } from '@/api/client'
-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, Label, Select } from '@/components/form'
-import { Input } from '@/components/ui/input'
-import {
- WorkingRepoField,
- type WorkingRepo,
-} from '@/components/working-repo-field'
-import { ChatTextarea } from '@/components/chat-textarea'
-import { StatusBadge } from '@/components/status-badge'
-import { RuntimeBadge } from '@/components/runtime-badge'
-import { EmptyState } from '@/components/empty-state'
-import { ResourceTable, type Column } from '@/components/resource-table'
-import {
- formatUsageCost,
- formatUsageDuration,
- formatUsageTokens,
- usageDisclosure,
-} from '@/lib/usage'
-
-const HALTED_TITLE = WORK_PAUSED_TITLE
-export default function Sessions() {
- const navigate = useNavigate()
- const queryClient = useQueryClient()
- const halted = useHalted() // out of credits → gate starting a session (out-of-credits doc, B3)
- const { data, isLoading } = useQuery({
- queryKey: ['sessions'],
- queryFn: () => getSessions(),
- })
- const { data: agents } = useQuery({
- queryKey: ['agents'],
- queryFn: getAgents,
- })
- const agentName = (id?: string | null) =>
- agents?.find((a) => a.id === id)?.name ?? id ?? '—'
-
- const [showStart, setShowStart] = useState(false)
- const [agentId, setAgentId] = useState('')
- const [message, setMessage] = useState('')
- // Optional per-session model override — empty inherits the agent's model
- // (cleared when the agent changes, since a model is runtime-specific).
- const [model, setModel] = useState('')
- // Optional working repo — explicitly chosen, per-agent (cleared when the agent changes).
- const [workingRepo, setWorkingRepo] = useState<WorkingRepo | null>(null)
-
- const selectedAgent = agents?.find((a) => a.id === agentId)
- // flue agents pin their model in the deployed artifact — no per-session override.
- const isFlueAgent = selectedAgent?.runtime === 'flue'
-
- const openStart = () => {
- setAgentId(agents?.[0]?.id ?? '')
- setMessage('')
- setModel('')
- setWorkingRepo(null)
- setShowStart(true)
- }
-
- const startMutation = useMutation({
- mutationFn: () =>
- createSession(
- {
- agent: agentId,
- input: message.trim(),
- // Only send a model when overridden — omitting it inherits the agent's.
- ...(model.trim() && !isFlueAgent ? { model: model.trim() } : {}),
- ...(workingRepo
- ? { sources: [{ repo: workingRepo.repo, ref: workingRepo.ref }] }
- : {}),
- },
- crypto.randomUUID(),
- ),
- onSuccess: (session) => {
- setShowStart(false)
- void queryClient.invalidateQueries({ queryKey: ['sessions'] })
- void navigate(`/sessions/${session.id}`)
- },
- onError: (e) => {
- if (e instanceof ApiError && e.type === 'insufficient_credits') {
- void queryClient.invalidateQueries({ queryKey: ['autumn-billing'] })
- }
- notifyError("Couldn't start the session.", e)
- },
- })
-
- const sessions = data ?? []
- const hasAgents = (agents?.length ?? 0) > 0
-
- const columns: Column<Session>[] = [
- {
- key: 'id',
- header: 'Session',
- cell: (s) => (
- <Link
- to={`/sessions/${s.id}`}
- className="text-foreground font-mono text-[13px] underline-offset-4 hover:underline"
- >
- {s.id}
- </Link>
- ),
- },
- {
- key: 'status',
- header: 'Status',
- cell: (s) => <StatusBadge status={s.status} />,
- },
- {
- key: 'agent',
- header: 'Agent',
- cell: (s) => (
- <span className="text-muted-foreground text-sm">
- {agentName(s.agent_id)}
- </span>
- ),
- },
- {
- key: 'runtime',
- header: 'Runtime',
- cell: (s) => <RuntimeBadge runtime={s.agent_snapshot?.runtime} />,
- },
- {
- key: 'events',
- header: 'Events',
- align: 'right',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs">
- {s.head ?? 0}
- </span>
- ),
- },
- {
- key: 'tokens',
- header: 'Tokens',
- align: 'right',
- cell: (s) => (
- <span
- className="text-muted-foreground font-mono text-xs tabular-nums"
- title={usageDisclosure(s.usage) ?? undefined}
- >
- {formatUsageTokens(s.usage)}
- </span>
- ),
- },
- {
- key: 'active',
- header: 'Active',
- align: 'right',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs tabular-nums">
- {formatUsageDuration(s.usage)}
- </span>
- ),
- },
- {
- key: 'cost',
- header: 'Cost',
- align: 'right',
- cell: (s) => (
- <span
- className="text-muted-foreground font-mono text-xs tabular-nums"
- title={usageDisclosure(s.usage) ?? 'Runtime-reported when available'}
- >
- {formatUsageCost(s.usage)}
- </span>
- ),
- },
- {
- key: 'created',
- header: 'Created',
- cell: (s) => (
- <span className="text-muted-foreground font-mono text-xs">
- {new Date(s.created_at).toLocaleString()}
- </span>
- ),
- },
- ]
-
- return (
- <div>
- <PageHeader
- title="Agent sessions"
- description="Durable agent runs — an append-only event log you can steer."
- api={{
- method: 'POST',
- path: '/v3/sessions',
- sdk: 'oc.sessions.create()',
- docs: 'https://docs.opencomputer.dev/agent-sessions/sessions',
- }}
- actions={
- <Button
- onClick={openStart}
- disabled={halted}
- title={halted ? HALTED_TITLE : undefined}
- >
- <Plus className="size-4" />
- Start session
- </Button>
- }
- />
-
- <Panel className="overflow-hidden">
- <ResourceTable
- columns={columns}
- rows={sessions}
- rowKey={(s) => s.id}
- loading={isLoading}
- empty={
- <EmptyState
- icon={MessagesSquare}
- title="No sessions yet"
- description="Start a session from an agent to give it a task; it runs durably and streams events here."
- action={
- <Button
- size="sm"
- onClick={openStart}
- disabled={halted}
- title={halted ? HALTED_TITLE : undefined}
- >
- <Plus className="size-4" />
- Start session
- </Button>
- }
- />
- }
- />
- </Panel>
-
- <Dialog open={showStart} onOpenChange={setShowStart}>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Start session</DialogTitle>
- <DialogDescription>
- Pick an agent and give it a first task. The session runs durably
- and you can steer it as it goes.
- </DialogDescription>
- </DialogHeader>
-
- {!hasAgents ? (
- <p className="text-muted-foreground py-2 text-sm">
- You need an agent first.{' '}
- <Link
- to="/agents"
- className="text-foreground font-medium underline underline-offset-4"
- >
- Create an agent
- </Link>
- .
- </p>
- ) : (
- <form
- className="space-y-4"
- onSubmit={(e) => {
- e.preventDefault()
- if (agentId && message.trim()) startMutation.mutate()
- }}
- >
- <div className="space-y-1.5">
- <Label htmlFor="start-agent">Agent</Label>
- <Select
- id="start-agent"
- value={agentId}
- onValueChange={(v) => {
- setAgentId(v)
- setModel('') // a model override is per-agent (runtime-specific)
- setWorkingRepo(null) // a working repo is per-agent
- }}
- options={(agents ?? []).map((a) => ({
- value: a.id,
- label: a.name,
- }))}
- />
- </div>
- <Field
- label="First task"
- htmlFor="start-message"
- description="What should the agent do? (required)"
- >
- <ChatTextarea
- id="start-message"
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- onSend={() => {
- if (agentId && message.trim() && !startMutation.isPending) {
- startMutation.mutate()
- }
- }}
- placeholder="Review PR #412 and open a follow-up if anything needs fixing."
- className="min-h-24"
- />
- </Field>
- {agentId && !isFlueAgent ? (
- <Field
- label="Model"
- htmlFor="start-model"
- description={
- selectedAgent?.model
- ? `Optional — overrides just this session. Defaults to the agent's model (${selectedAgent.model}).`
- : "Optional — overrides just this session. Defaults to the agent's model."
- }
- >
- <Input
- id="start-model"
- value={model}
- onChange={(e) => setModel(e.target.value)}
- placeholder={selectedAgent?.model ?? 'provider/model'}
- autoComplete="off"
- spellCheck={false}
- />
- </Field>
- ) : null}
- {agentId ? (
- <WorkingRepoField
- agentId={agentId}
- runtime={selectedAgent?.runtime}
- value={workingRepo}
- onChange={setWorkingRepo}
- />
- ) : null}
- <DialogFooter className="mt-2">
- <Button
- type="button"
- variant="ghost"
- onClick={() => setShowStart(false)}
- >
- Cancel
- </Button>
- <Button
- type="submit"
- disabled={
- startMutation.isPending || !agentId || !message.trim()
- }
- >
- {startMutation.isPending ? 'Starting…' : 'Start session'}
- </Button>
- </DialogFooter>
- </form>
- )}
- </DialogContent>
- </Dialog>
- </div>
- )
-}
diff --git a/web/src/pages/agent-deployment-slack.test.tsx b/web/src/pages/agent-deployment-slack.test.tsx
deleted file mode 100644
index 0ff804ac..00000000
--- a/web/src/pages/agent-deployment-slack.test.tsx
+++ /dev/null
@@ -1,223 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter, Route, Routes } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import type { AgentDeployment as AgentDeploymentRecord } from '@/api/client'
-import AgentDeployment from './AgentDeployment'
-import { managedSlackConnectionsQueryKey } from '@/lib/managed-slack-connections'
-
-const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const deploymentId = 'dep_aaaaaaaaaaaaaaaaaaaaaaaa'
-const connectedAgentId = 'agt_bbbbbbbbbbbbbbbbbbbbbbbb'
-
-const deployment: AgentDeploymentRecord = {
- id: deploymentId,
- state: 'building',
- phase: 'build',
- terminal: false,
- result: null,
- input_type: 'github',
- revision_id: null,
- revision: null,
- source: null,
- source_relation: {
- repo: {
- id: 'repo_aaaaaaaaaaaaaaaaaaaaaaaa',
- full_name: 'example/support-agent',
- },
- path: '',
- production_ref: 'main',
- status: 'active',
- ref: 'main',
- sha: 'a'.repeat(40),
- commit_url: null,
- },
- actor: null,
- ref: 'main',
- sha: 'a'.repeat(40),
- error: null,
- error_class: null,
- build: null,
- configuration: null,
- log_bytes: 0,
- log_truncated: false,
- live_touched: false,
- agent_live: null,
- restore_eligibility: 'none',
- redeploy_of: null,
- allowed_actions: ['open_agent'],
- active: false,
- timing: {
- accepted_at: '2026-07-16T18:00:00Z',
- started_at: '2026-07-16T18:00:01Z',
- finished_at: null,
- cancel_requested_at: null,
- queue_ms: 1_000,
- run_ms: null,
- total_ms: null,
- },
- created_at: '2026-07-16T18:00:00Z',
- updated_at: '2026-07-16T18:00:02Z',
- started_at: '2026-07-16T18:00:01Z',
- finished_at: null,
-}
-
-function renderDeployment(
- managed: Record<string, unknown> | null | undefined,
- search = '',
- connectedAgentName?: string,
- managedConnections: Array<Record<string, unknown>> = [],
- deploymentRecord: AgentDeploymentRecord = deployment,
-) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(
- ['agent-deployment', agentId, deploymentId],
- deploymentRecord,
- )
- queryClient.setQueryData(['agent', agentId], {
- id: agentId,
- name: 'Support triage',
- })
- queryClient.setQueryData(['agent-deployment-logs', agentId, deploymentId], {
- data: [],
- cursor: null,
- })
- if (managed !== undefined) {
- queryClient.setQueryData(['slack', 'managed', agentId], managed)
- }
- queryClient.setQueryData(managedSlackConnectionsQueryKey, managedConnections)
- if (connectedAgentName) {
- queryClient.setQueryData(['agent', connectedAgentId], {
- id: connectedAgentId,
- name: connectedAgentName,
- })
- }
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter
- initialEntries={[
- `/agents/${agentId}/deployments/${deploymentId}${search}`,
- ]}
- >
- <Routes>
- <Route
- path="/agents/:agentId/deployments/:deploymentId"
- element={<AgentDeployment />}
- />
- </Routes>
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-describe('deployment managed Slack composition', () => {
- it('waits for authoritative active state before showing OAuth success', () => {
- expect(renderDeployment(undefined, '?slack=connected')).not.toContain(
- 'Slack connected',
- )
- expect(renderDeployment(null, '?slack=connected')).not.toContain(
- 'Slack connected',
- )
-
- const connected = renderDeployment(
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:00:00Z',
- },
- '?slack=connected',
- )
- expect(connected).toContain('Slack connected')
- expect(connected).toContain(
- 'OpenComputer will send messages in Acme to Support triage.',
- )
- })
-
- it('does not open Slack for a ready deployment that cannot start sessions', () => {
- const markup = renderDeployment(
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:00:00Z',
- },
- '',
- undefined,
- [],
- {
- ...deployment,
- state: 'ready',
- phase: 'verify',
- terminal: true,
- active: true,
- allowed_actions: ['open_agent'],
- },
- )
-
- expect(markup).not.toContain('>Open Slack<')
- expect(markup).toContain(
- 'Slack connected. Open Slack when this deployment is ready.',
- )
- })
-
- it('explains a terminal non-active OAuth return', () => {
- const markup = renderDeployment(
- {
- mode: 'managed',
- status: 'revoked',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: null,
- connected_at: null,
- },
- '?slack=connected',
- )
-
- expect(markup).toContain('Slack authorization was revoked')
- expect(markup).toContain('Reconnect Slack to authorize OpenComputer again.')
- })
-
- it('names and links only an authoritative same-owner conflict', () => {
- const connected = renderDeployment(
- null,
- `?slack=workspace_already_connected&connected_agent=${connectedAgentId}`,
- 'Docs writer',
- )
- expect(connected).toContain('This workspace sends messages to Docs writer.')
- expect(connected).toContain(`href="/agents/${connectedAgentId}"`)
-
- const malformed = renderDeployment(
- null,
- '?slack=workspace_already_connected&connected_agent=agt_not-an-id',
- )
- expect(malformed).toContain(
- 'Connect a different workspace or use your own Slack app for this agent.',
- )
- expect(malformed).not.toContain('Open connected agent')
- })
-
- it('surfaces a known workspace claim before starting OAuth', () => {
- const markup = renderDeployment(null, '', undefined, [
- {
- mode: 'managed',
- status: 'active',
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- connected_at: '2026-07-16T18:00:00Z',
- agent: { id: connectedAgentId, name: 'Docs writer' },
- },
- ])
-
- expect(markup).toContain('Slack workspaces already in use')
- expect(markup).toContain('Sends messages to Docs writer')
- expect(markup).toContain('Connect another workspace')
- })
-})
diff --git a/web/src/pages/agent-detail-source-chip.test.ts b/web/src/pages/agent-detail-source-chip.test.ts
deleted file mode 100644
index e4f37b7b..00000000
--- a/web/src/pages/agent-detail-source-chip.test.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { createElement } from 'react'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { describe, expect, it } from 'vitest'
-import { SourceChip } from '@/pages/AgentDetail'
-
-describe('agent source status', () => {
- it('makes a changed Flue source visible from the normal overview header', () => {
- const html = renderToStaticMarkup(
- createElement(SourceChip, {
- source: {
- full_name: 'example/support',
- path: 'agents/support',
- production_ref: 'main',
- status: 'source_profile_changed',
- },
- }),
- )
-
- expect(html).toContain('example/support@main')
- expect(html).toContain('Source needs attention')
- expect(html).toContain('text-status-error')
- })
-})
diff --git a/web/src/pages/agent-new-linked-repository.test.tsx b/web/src/pages/agent-new-linked-repository.test.tsx
deleted file mode 100644
index bb4c0490..00000000
--- a/web/src/pages/agent-new-linked-repository.test.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter, Route, Routes } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import type { DeployApp } from '@/api/client'
-import AgentNew from './AgentNew'
-
-const repoId = 'repo_0123456789abcdef01234567'
-const agentId = 'agt_0123456789abcdef01234567'
-
-function renderLinkedRepository() {
- const app: DeployApp = {
- installed: true,
- install_url: null,
- configure_url: 'https://github.com/settings/installations/1',
- account: 'example',
- repository_selection: 'selected',
- repositories: [
- {
- id: repoId,
- full_name: 'example/flue-starter',
- default_branch: 'main',
- private: false,
- linked_sources: [
- {
- path: '',
- production_ref: 'main',
- status: 'active',
- agent: { id: agentId, name: 'Support triage' },
- },
- ],
- },
- ],
- }
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(['deploy-app'], app)
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter
- initialEntries={[
- {
- pathname: '/agents/new',
- state: {
- repositoryImport: {
- repo: repoId,
- path: '',
- productionRef: 'main',
- },
- },
- },
- ]}
- >
- <Routes>
- <Route path="/agents/new" element={<AgentNew />} />
- </Routes>
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-describe('repository import conflict discovery', () => {
- it('marks a linked root before review and offers open or confirmed unlink', () => {
- const markup = renderLinkedRepository()
-
- expect(markup).toMatch(/is linked to.*Support triage/s)
- expect(markup).toContain('Change repository')
- expect(markup).not.toContain('Search repositories')
- expect(markup).toContain('Repository root already linked')
- expect(markup).toContain(`href="/agents/${agentId}"`)
- expect(markup).toContain('Unlink repository')
- expect(markup).toMatch(
- /<button[^>]*disabled=""[^>]*>Review agent<\/button>/,
- )
- })
-})
diff --git a/web/src/pages/agent-setup.test.tsx b/web/src/pages/agent-setup.test.tsx
deleted file mode 100644
index 0941b45f..00000000
--- a/web/src/pages/agent-setup.test.tsx
+++ /dev/null
@@ -1,432 +0,0 @@
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { renderToStaticMarkup } from 'react-dom/server'
-import { MemoryRouter, Route, Routes } from 'react-router-dom'
-import { describe, expect, it } from 'vitest'
-import type {
- AgentDeployment,
- ManagedSlackWorkspaceConnection,
- Session,
- SessionEvent,
-} from '@/api/client'
-import { managedSlackConnectionsQueryKey } from '@/lib/managed-slack-connections'
-import { repositoryAccessQueryKey } from '@/lib/repository-access'
-import AgentSetup from './AgentSetup'
-
-const agentId = 'agt_aaaaaaaaaaaaaaaaaaaaaaaa'
-const deploymentId = 'dep_aaaaaaaaaaaaaaaaaaaaaaaa'
-
-const buildingDeployment: AgentDeployment = {
- id: deploymentId,
- state: 'building',
- phase: 'build',
- terminal: false,
- result: null,
- input_type: 'github',
- revision_id: null,
- revision: null,
- source: null,
- source_relation: {
- repo: {
- id: 'repo_aaaaaaaaaaaaaaaaaaaaaaaa',
- full_name: 'example/support-agent',
- },
- path: '',
- production_ref: 'main',
- status: 'active',
- ref: 'main',
- sha: 'a'.repeat(40),
- commit_url: null,
- },
- actor: null,
- ref: 'main',
- sha: 'a'.repeat(40),
- error: null,
- error_class: null,
- build: null,
- configuration: null,
- log_bytes: 0,
- log_truncated: false,
- live_touched: false,
- agent_live: null,
- restore_eligibility: 'none',
- redeploy_of: null,
- allowed_actions: ['open_agent'],
- active: false,
- timing: {
- accepted_at: '2026-07-16T18:00:00Z',
- started_at: '2026-07-16T18:00:01Z',
- finished_at: null,
- cancel_requested_at: null,
- queue_ms: 1_000,
- run_ms: null,
- total_ms: null,
- },
- created_at: '2026-07-16T18:00:00Z',
- updated_at: '2026-07-16T18:00:02Z',
- started_at: '2026-07-16T18:00:01Z',
- finished_at: null,
-}
-
-const activeSlack = {
- mode: 'managed' as const,
- status: 'active' as const,
- workspace: { id: 'T1', name: 'Acme' },
- app: { id: 'A1', handle: 'OpenComputer' },
- open_url: 'https://slack.com/app_redirect?app=A1&team=T1',
- connected_at: '2026-07-16T18:00:00Z',
-}
-
-function renderSetup(input: {
- deployment?: AgentDeployment
- managed?: Record<string, unknown> | null
- search?: string
- agent?: Record<string, unknown>
- sessions?: Session[]
- events?: { sessionId: string; data: SessionEvent[] }
- managedConnections?: ManagedSlackWorkspaceConnection[]
-}) {
- const queryClient = new QueryClient({
- defaultOptions: { queries: { retry: false, staleTime: Infinity } },
- })
- queryClient.setQueryData(
- ['agent', agentId],
- input.agent ?? {
- id: agentId,
- name: 'Support triage',
- runtime: 'claude',
- revision: 1,
- active_revision_id: 'rev_aaaaaaaaaaaaaaaaaaaaaaaa',
- },
- )
- if (input.agent?.runtime === 'flue') {
- queryClient.setQueryData(repositoryAccessQueryKey(agentId), {
- policy: { mode: 'selected', repository_ids: ['repo_1'] },
- grant: {
- status: 'active',
- account: 'acme',
- repository_selection: 'selected',
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- truncated: false,
- },
- effective_repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/support-agent',
- default_branch: 'main',
- private: true,
- },
- ],
- unavailable_selected_repositories: [],
- })
- queryClient.setQueryData(['deploy-app'], {
- installed: true,
- install_url: 'https://github.test/install',
- configure_url: 'https://github.test/configure',
- account: 'acme',
- repository_selection: 'selected',
- repositories: [
- {
- id: 'repo_1',
- full_name: 'acme/support-agent',
- default_branch: 'main',
- private: true,
- linked_sources: [],
- },
- ],
- })
- }
- if (input.deployment) {
- queryClient.setQueryData(
- ['agent-deployment', agentId, deploymentId],
- input.deployment,
- )
- }
- if ('managed' in input) {
- queryClient.setQueryData(['slack', 'managed', agentId], input.managed)
- }
- queryClient.setQueryData(
- managedSlackConnectionsQueryKey,
- input.managedConnections ?? [],
- )
- if (input.sessions) {
- queryClient.setQueryData(
- [
- 'agent-setup',
- 'managed-slack-sessions',
- agentId,
- input.managed?.connected_at ?? null,
- ],
- input.sessions,
- )
- }
- if (input.events) {
- queryClient.setQueryData(
- ['session-events', input.events.sessionId],
- input.events.data,
- )
- }
-
- return renderToStaticMarkup(
- <QueryClientProvider client={queryClient}>
- <MemoryRouter
- initialEntries={[`/agents/${agentId}/setup${input.search ?? ''}`]}
- >
- <Routes>
- <Route path="/agents/:agentId/setup" element={<AgentSetup />} />
- </Routes>
- </MemoryRouter>
- </QueryClientProvider>,
- )
-}
-
-describe('agent setup', () => {
- it('keeps the deployment in the background and makes Slack primary', () => {
- const markup = renderSetup({
- deployment: buildingDeployment,
- managed: null,
- search: `?deployment=${deploymentId}`,
- })
-
- expect(markup).toContain('Connect Slack while we prepare Support triage')
- expect(markup).toContain('>Connect Slack</button>')
- expect(markup).toContain('Preparing your agent')
- expect(markup).toContain('<details')
- expect(markup).not.toContain('<details open=""')
- })
-
- it('does not let optional Flue repository setup compete with Connect Slack', () => {
- const html = renderSetup({
- agent: {
- id: agentId,
- name: 'Support triage',
- runtime: 'flue',
- revision: 1,
- active_revision_id: 'rev_aaaaaaaaaaaaaaaaaaaaaaaa',
- },
- deployment: buildingDeployment,
- managed: null,
- search: `?deployment=${deploymentId}`,
- })
-
- expect(html).toContain('Connect Slack while we prepare Support triage')
- expect(html).not.toContain('Choose working repositories')
- })
-
- it('keeps Slack first and offers an exact Flue repository task when ready', () => {
- const html = renderSetup({
- agent: {
- id: agentId,
- name: 'Support triage',
- runtime: 'flue',
- revision: 1,
- active_revision_id: 'rev_aaaaaaaaaaaaaaaaaaaaaaaa',
- },
- deployment: {
- ...buildingDeployment,
- state: 'ready',
- phase: 'verify',
- terminal: true,
- active: true,
- allowed_actions: ['open_agent', 'start_session'],
- },
- managed: activeSlack,
- search: `?deployment=${deploymentId}`,
- })
-
- expect(html.indexOf('Send your first message')).toBeLessThan(
- html.indexOf('Choose working repositories'),
- )
- expect(html).toContain(
- 'In <span class="text-foreground font-mono">acme/support-agent,</span> add a setup note and open a pull request.',
- )
- })
-
- it('waits visibly after Slack connects and promotes chat when ready', () => {
- const building = renderSetup({
- deployment: buildingDeployment,
- managed: activeSlack,
- search: `?deployment=${deploymentId}`,
- })
- expect(building).toContain('Slack is connected')
- expect(building).toContain('Finishing deployment…')
- expect(building).not.toContain('>Open Slack<')
-
- const ready = renderSetup({
- deployment: {
- ...buildingDeployment,
- state: 'ready',
- phase: 'verify',
- terminal: true,
- active: true,
- allowed_actions: ['open_agent', 'start_session'],
- },
- managed: activeSlack,
- search: `?deployment=${deploymentId}`,
- })
- expect(ready).toContain('Send your first message')
- expect(ready).toContain('>Open Slack<')
- expect(ready).toContain('Waiting for your first Slack message')
- expect(ready).toContain(
- 'href="https://slack.com/app_redirect?app=A1&amp;team=T1"',
- )
- })
-
- it('does not promote chat until the deployment admits sessions', () => {
- const markup = renderSetup({
- deployment: {
- ...buildingDeployment,
- state: 'ready',
- phase: 'verify',
- terminal: true,
- active: true,
- allowed_actions: ['open_agent'],
- },
- managed: activeSlack,
- search: `?deployment=${deploymentId}`,
- })
-
- expect(markup).toContain('Finishing deployment…')
- expect(markup).not.toContain('>Open Slack<')
- expect(markup).not.toContain('Waiting for your first Slack message')
- })
-
- it('turns a real managed Slack session into a conversation preview', () => {
- const sessionId = 'ses_aaaaaaaaaaaaaaaaaaaaaaaa'
- const readyDeployment: AgentDeployment = {
- ...buildingDeployment,
- state: 'ready',
- phase: 'verify',
- terminal: true,
- active: true,
- allowed_actions: ['open_agent', 'start_session'],
- }
- const session: Session = {
- id: sessionId,
- status: 'running',
- agent_id: agentId,
- metadata: { slack: { mode: 'managed', team_id: 'T1' } },
- created_at: '2026-07-16T18:00:01Z',
- }
- const events: SessionEvent[] = [
- {
- id: 'evt_input',
- seq: 1,
- type: 'user.message',
- level: 'user',
- body: { text: 'Hello from Slack' },
- source: 'client',
- },
- {
- id: 'evt_reply',
- seq: 2,
- type: 'agent.message',
- level: 'user',
- body: { text: 'Hello! Your agent is ready.' },
- source: 'runtime',
- },
- ]
-
- const markup = renderSetup({
- deployment: readyDeployment,
- managed: activeSlack,
- sessions: [session],
- events: { sessionId, data: events },
- search: `?deployment=${deploymentId}`,
- })
-
- expect(markup).toContain('Support triage is live in Slack')
- expect(markup).toContain('Continue in Slack')
- expect(markup).toContain('Hello from Slack')
- expect(markup).toContain('Hello! Your agent is ready.')
- expect(markup).toContain(`href="/sessions/${sessionId}"`)
- expect(markup).toContain(`href="/agents/${agentId}/sessions"`)
- expect(markup).toContain(`href="/agents/${agentId}"`)
- expect(markup).toContain('>View agent<')
- })
-
- it('shows an existing workspace claim before OAuth', () => {
- const connectedAgentId = 'agt_bbbbbbbbbbbbbbbbbbbbbbbb'
- const markup = renderSetup({
- deployment: buildingDeployment,
- managed: null,
- managedConnections: [
- {
- ...activeSlack,
- agent: { id: connectedAgentId, name: 'Docs writer' },
- },
- ],
- search: `?deployment=${deploymentId}`,
- })
-
- expect(markup).toContain('Slack workspaces already in use')
- expect(markup).toContain('Sends messages to Docs writer')
- expect(markup).toContain(`href="/agents/${connectedAgentId}"`)
- expect(markup).toContain('>Disconnect</button>')
- expect(markup).toContain('>Connect another workspace</button>')
- })
-
- it('uses the same activation flow for a manually created agent', () => {
- const markup = renderSetup({ managed: null })
-
- expect(markup).toContain('Support triage is ready')
- expect(markup).toContain('Your agent is ready to use.')
- expect(markup).toContain('>Connect Slack</button>')
- })
-
- it('does not invent readiness when setup has no deployment query', () => {
- const markup = renderSetup({
- managed: null,
- agent: {
- id: agentId,
- name: 'Support triage',
- runtime: 'flue',
- revision: 0,
- active_revision_id: null,
- deployment_status: {
- deployment_id: deploymentId,
- state: 'building',
- result: null,
- error_class: null,
- live_touched: false,
- live_status: null,
- updated_at: '2026-07-16T18:00:02Z',
- },
- },
- })
-
- expect(markup).toContain('Connect Slack while we prepare Support triage')
- expect(markup).toContain(
- 'Setup is following the latest deployment in the background.',
- )
- expect(markup).not.toContain('Support triage is ready')
- })
-
- it('does not trust an OAuth success query without active Slack state', () => {
- const unconfirmed = renderSetup({
- deployment: buildingDeployment,
- managed: null,
- search: `?deployment=${deploymentId}&slack=connected`,
- })
-
- expect(unconfirmed).not.toContain(
- 'OpenComputer will send messages in Acme to Support triage.',
- )
- })
-
- it('stops waiting and explains a terminal OAuth result', () => {
- const markup = renderSetup({
- deployment: buildingDeployment,
- managed: {
- ...activeSlack,
- status: 'error',
- connected_at: null,
- },
- search: `?deployment=${deploymentId}&slack=connected`,
- })
-
- expect(markup).toContain('Slack couldn&#x27;t finish connecting')
- expect(markup).toContain('Reconnect Slack and try again.')
- expect(markup).toContain('>Reconnect Slack</button>')
- })
-})
diff --git a/web/src/pages/getting-started.test.tsx b/web/src/pages/getting-started.test.tsx
index db27e619..0f982b3d 100644
--- a/web/src/pages/getting-started.test.tsx
+++ b/web/src/pages/getting-started.test.tsx
@@ -2,26 +2,10 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { renderToStaticMarkup } from 'react-dom/server'
import { MemoryRouter } from 'react-router-dom'
import { describe, expect, it } from 'vitest'
-import type { APIKey, DeployApp } from '@/api/client'
+import type { APIKey } from '@/api/client'
import { GettingStarted } from './Dashboard'
function renderGettingStarted(path = '/') {
- const app: DeployApp = {
- installed: true,
- install_url: null,
- configure_url: 'https://github.com/settings/installations/1',
- account: 'example',
- repository_selection: 'selected',
- repositories: [
- {
- id: 'repo_0123456789abcdef01234567',
- full_name: 'example/flue-starter',
- default_branch: 'main',
- private: false,
- linked_sources: [],
- },
- ],
- }
const keys: APIKey[] = [
{
id: 'key_0123456789abcdef01234567',
@@ -35,9 +19,7 @@ function renderGettingStarted(path = '/') {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
})
- queryClient.setQueryData(['deploy-app'], app)
queryClient.setQueryData(['api-keys'], keys)
- queryClient.setQueryData(['credentials'], [])
return renderToStaticMarkup(
<QueryClientProvider client={queryClient}>
@@ -49,55 +31,15 @@ function renderGettingStarted(path = '/') {
}
describe('getting started', () => {
- it('shows three self-explanatory directions and defaults to GitHub', () => {
+ it('shows the API key and the sandbox quickstart', () => {
const markup = renderGettingStarted()
- expect(markup).toContain('Agent from GitHub')
- expect(markup).toContain('Deploy a Flue repository.')
- expect(markup).toContain('Agent from a prompt')
- expect(markup).toContain('Claude Code, Codex, or Pi.')
- expect(markup).toContain('Build with the API')
- expect(markup).toContain('Durable sessions &amp; sandboxes.')
- expect(markup).toMatch(/id="start-tab-github"[^>]*aria-selected="true"/)
- expect(markup).toContain('example/flue-starter')
- expect(markup).toContain('Choose repository')
- expect(markup).not.toContain('API key ready')
- expect(markup).not.toContain(
- 'Create a durable agent from its system prompt',
- )
- expect(markup).not.toContain('Get started')
- expect(markup).not.toContain('free credits')
- expect(markup).not.toContain('Claude Opus')
- expect(markup).not.toContain('Analyze a CSV')
- })
-
- it('keeps both API paths concise and puts durable sessions first', () => {
- const markup = renderGettingStarted('/?start=api')
-
expect(markup).toContain('API key ready')
expect(markup).toContain('Sandboxes')
- expect(markup).toContain('Durable agent sessions')
expect(markup).toContain('Sandbox.create()')
- expect(markup).toContain('oc.sessions.create')
- expect(markup).not.toContain('oc.agents.create')
- expect(markup).toContain('console.log(session.id)')
- expect(markup).toContain('Open sessions quickstart')
expect(markup).toContain('Open sandbox quickstart')
- expect(markup).toContain('Start and steer a durable agent run.')
expect(markup).toContain('Run commands in an isolated computer.')
- expect(markup.indexOf('oc.sessions.create')).toBeLessThan(
- markup.indexOf('Sandbox.create()'),
- )
- })
-
- it('offers direct prompt-based agent creation as a peer direction', () => {
- const markup = renderGettingStarted('/?start=prompt')
-
- expect(markup).toContain('Define the agent')
- expect(markup).toContain('Create a durable agent from its system prompt')
- expect(markup).toContain('Instructions')
- expect(markup).toContain('Runtime')
- expect(markup).toContain('Create agent')
- expect(markup).not.toContain('Choose repository')
+ expect(markup).not.toContain('oc.sessions.create')
+ expect(markup).not.toContain('Durable agent sessions')
})
})
diff --git a/web/src/pages/session-sources.test.tsx b/web/src/pages/session-sources.test.tsx
deleted file mode 100644
index 3cdaa859..00000000
--- a/web/src/pages/session-sources.test.tsx
+++ /dev/null
@@ -1,151 +0,0 @@
-import { renderToStaticMarkup } from 'react-dom/server'
-import { describe, expect, it } from 'vitest'
-import {
- canSessionChangeFlueSources,
- isFlueSession,
- sessionSourcesRefetchInterval,
-} from '@/lib/session-source-polling'
-import { SessionSourcesPanel } from './SessionDetail'
-
-describe('session working sources', () => {
- it('shows stable identity, requested ref, pinned SHA, status, and path', () => {
- const html = renderToStaticMarkup(
- <SessionSourcesPanel
- sources={[
- {
- name: 'app',
- repo_id: 'repo_1',
- full_name: 'acme/app',
- requested_ref: 'main',
- status: 'resolved',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- resolved_sha: 'b'.repeat(40),
- },
- {
- name: 'docs',
- repo_id: 'repo_2',
- full_name: 'acme/docs',
- requested_ref: 'main',
- status: 'materializing',
- path: '/workspace/sources/docs',
- sha: 'c'.repeat(40),
- },
- {
- name: 'pending',
- status: 'pending',
- path: '/workspace/sources/pending',
- sha: 'd'.repeat(40),
- },
- {
- name: 'failed',
- status: 'failed',
- path: '/workspace/sources/failed',
- sha: 'e'.repeat(40),
- },
- {
- name: 'unavailable',
- status: 'unavailable',
- path: '/workspace/sources/unavailable',
- sha: 'f'.repeat(40),
- },
- {
- name: 'auth',
- status: 'auth_required',
- path: '/workspace/sources/auth',
- sha: '0'.repeat(40),
- },
- ]}
- loading={false}
- error={false}
- onRetry={() => {}}
- />,
- )
- expect(html).toContain('acme/app')
- expect(html).toContain('main · aaaaaaaa')
- expect(html).toContain('observed bbbbbbbb')
- expect(html).toContain(`title="Pinned commit ${'a'.repeat(40)}"`)
- expect(html).toContain('Resolved')
- expect(html).toContain('Materializing')
- expect(html).toContain('Pending')
- expect(html).toContain('Failed')
- expect(html).toContain('Unavailable')
- expect(html).toContain('Auth required')
- expect(html).toContain('/workspace/sources/app')
- })
-
- it('stays absent when the session has no sources', () => {
- expect(
- renderToStaticMarkup(
- <SessionSourcesPanel
- sources={[]}
- loading={false}
- error={false}
- onRetry={() => {}}
- />,
- ),
- ).toBe('')
- })
-
- it('watches for new sources and accelerates while materialization is active', () => {
- expect(sessionSourcesRefetchInterval([])).toBe(5_000)
- expect(
- sessionSourcesRefetchInterval([
- {
- name: 'app',
- status: 'pending',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- },
- ]),
- ).toBe(1_500)
- expect(
- sessionSourcesRefetchInterval([
- {
- name: 'app',
- status: 'materializing',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- },
- ]),
- ).toBe(1_500)
- expect(
- sessionSourcesRefetchInterval([
- {
- name: 'app',
- status: 'resolved',
- path: '/workspace/sources/app',
- sha: 'a'.repeat(40),
- resolved_sha: 'a'.repeat(40),
- },
- ]),
- ).toBe(5_000)
- })
-
- it('loads only Flue sources and polls only while the session can change', () => {
- for (const status of ['queued', 'running', 'awaiting_input', 'idle']) {
- const session = {
- status,
- agent_snapshot: { runtime: 'flue' },
- }
- expect(isFlueSession(session)).toBe(true)
- expect(canSessionChangeFlueSources(session)).toBe(true)
- }
- expect(isFlueSession(undefined)).toBe(false)
- expect(canSessionChangeFlueSources(undefined)).toBe(false)
- const builtIn = {
- status: 'running',
- agent_snapshot: { runtime: 'claude' },
- }
- expect(isFlueSession(builtIn)).toBe(false)
- expect(canSessionChangeFlueSources(builtIn)).toBe(false)
- for (const status of ['failed', 'archived']) {
- const terminalFlue = {
- status,
- agent_snapshot: { runtime: 'flue' },
- }
- expect(isFlueSession(terminalFlue)).toBe(true)
- expect(canSessionChangeFlueSources(terminalFlue)).toBe(false)
- }
- })
-})