open-swe/ui/src/lib/agents/api.ts
seahaven-openswe[bot] f87847baa4
Some checks are pending
CI / Lint (push) Waiting to run
CI / Format check (push) Waiting to run
CI / Unit tests (push) Waiting to run
CI / Playwright E2E (push) Waiting to run
CI / Docker build smoke (push) Waiting to run
CI / Triage ledger up to date (push) Waiting to run
CI / ui bun.lock in sync (push) Waiting to run
feat: port plan-review & workflow-approval UX (#159)
* feat: port plan-review & workflow-approval UX (#135)

Port six upstream commits onto dev:

- c03a6be7 (already ported): keep plan guidance high-level
- 546042a4: add workflow approval UI with diff preview, approval URLs,
  web review links, and polling for approval status during active runs
- 216cf181: remove workflow token elevation; approved pushes pass
  through directly without proxy token rewriting
- 3dbc0282: preserve plan redirects after login by accepting relative
  same-origin redirect_to values and rejecting blocked paths
- bb104d93: submit plan comments with cmd+enter
- 90cb6caa: terse Slack replies, shared content via save_plan outside
  plan mode (PLAN_STATUS_SHARED), reject shared-content mutations

Refs: #135

* fix: restore login page render and clear CI lint/format

The plan-review port removed the authRedirectUrl import from login.tsx
but left its call site, crashing the login page at runtime (blank page,
no 'Sign in to open-swe'). Pass the relative path straight to loginUrl,
matching the plan route and the backend relative-redirect handling.

Also drop an unused os import in the guard test and reformat
workflow_push_guard.py to satisfy ruff.

* fix: carry workflows:write on the standing proxy token

Complete the half-ported upstream 216cf181 cascade. The port dropped
_run_with_workflow_token from the guard but missed the paired github_app
change, so an approved .github/workflows push ran with the base token
(no workflows:write) and GitHub 403'd it.

Add workflows:write to BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS and delete the
now-orphaned WORKFLOW_RUNTIME_PROXY_TOKEN_PERMISSIONS constant; update the
github_app and proxy_auth tests to match. The HITL approval gate in
workflow_push_guard.py is unchanged — this only lets the standing token
push once a human approves.

* fix: restore transient workflow-token elevation (revert standing workflows:write)

The standing GitHub-App proxy token (BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS) is
ALWAYS-ON, so carrying workflows:write on it made the fork's HITL workflow-push
guard the sole control over unapproved workflow pushes. The guard's git-push
parser has gaps (obfuscated-expansion push, `gh api` REST contents PUT,
fully-qualified cross-branch refspecs); with a permanently workflows-scoped
token those gaps become live unapproved-workflow-push exploits (1 critical, 2
high — security review BLOCK on #159).

Restore dev's transient-elevation model:
- Drop workflows:write from BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS; re-add the
  WORKFLOW_RUNTIME_PROXY_TOKEN_PERMISSIONS constant (base + workflows:write).
- Re-introduce _run_with_workflow_token in the guard: it mints the
  workflows-scoped token via refresh_proxy_token around the approved,
  guard-normalized fixed_command, then downscopes to RUNTIME then BASE in a
  finally. Route the approval branch through it.
- Restore the dev token/elevation tests.

The standing token no longer carries workflows:write, so the three parser
bypasses hit GitHub 403 again; an approved push still succeeds because the
elevation grants workflows:write only around the normalized command. Keeps all
of #159's diff-preview / approval-URL / Slack-card guard additions.

* fix: reject protocol-relative path from sanitizeAuthRedirect (open redirect)

sanitizeAuthRedirect returned parsed.pathname+search+hash, which `new URL` can
resolve to a protocol-relative `//host` (e.g. input `/..//evil.com` normalizes
same-origin, passing the origin check, but yields a path starting with `//`).
ClientRedirect / login.tsx feed that path to window.location.replace, so it
navigates cross-origin — an open redirect. Reject any resolved path that is not
a single-leading-slash path (`^/[^/]`), falling back to the default. Adds
coverage for `/..//evil.com`, `/.//evil.com`, and `//evil.com`.

* fix: log SECURITY error when workflow-token downscope fails

The elevate->push->downscope finally block was silent on failure. If both
refresh_proxy_token calls fail, the sandbox retains workflows:write for the
rest of the run with no signal. Log a SECURITY error on the partial and full
downscope-failure paths so the retention is observable.

Addresses the GPT-4.1 cross-family review of the token-scope remediation.

---------

Co-authored-by: amoussa1229 <166072409+amoussa1229@users.noreply.github.com>
Co-authored-by: Adam Moussa <adam@seahavenind.com>
2026-07-09 16:03:13 -04:00

360 lines
9.6 KiB
TypeScript

import type { AgentSchedule, AgentThread, ImageChunk, Message } from "./types"
export type { AgentSchedule, AgentThread, Message }
export class AgentsApiError extends Error {
constructor(
public readonly status: number,
message: string
) {
super(message)
this.name = "AgentsApiError"
}
}
export interface ThreadMessageRequest {
content: string
images?: Array<ImageChunk>
model_id?: string | null
effort?: string | null
plan_mode?: boolean
}
export interface ScheduleCreateRequest {
prompt: string
schedule: string
name?: string | null
repo?: string | null
model_id?: string | null
effort?: string | null
slack_report_channel?: string | null
}
export interface ScheduleUpdateRequest {
prompt?: string | null
schedule?: string | null
name?: string | null
repo?: string | null
model_id?: string | null
effort?: string | null
enabled?: boolean | null
slack_report_channel?: string | null
}
export interface ThreadPrDiffFile {
path: string
previousPath: string | null
status: "added" | "removed" | "modified" | "renamed" | string
additions: number
deletions: number
originalContent: string | null
modifiedContent: string | null
unrenderable: boolean
}
export interface ThreadPrDiff {
prNumber: number
baseSha: string
headSha: string
truncated: boolean
files: Array<ThreadPrDiffFile>
}
export interface ThreadRecoveryPatch {
blob: Blob
filename: string
}
export type WorkflowApprovalStatus = "pending" | "approved" | "rejected"
export interface WorkflowDiffStats {
files: number
additions: number
deletions: number
}
export interface WorkflowPushApproval {
fingerprint: string
status: WorkflowApprovalStatus
repo: string
branch: string
baseSha: string
headSha: string
files: Array<string>
diffStats: WorkflowDiffStats
diffPreview: string
diffPreviewTruncated: boolean
approvalUrl: string | null
requestedAt: string | null
decidedAt: string | null
decidedBy: string | null
}
export interface WorkflowPushApprovalsResponse {
threadId: string
isOwner: boolean
approvals: Array<WorkflowPushApproval>
}
export interface WorkflowApprovalDecision {
status: string
fingerprint: string
}
// Legacy alias kept for backward-compatible prop typing.
export type WorkflowApproval = WorkflowPushApproval
export interface WorkflowApprovalsPayload {
approvals: Array<WorkflowPushApproval>
}
export interface ThreadsPageParams {
limit?: number
offset?: number
resolved?: boolean
viewed?: boolean
source?: string
status?: string
q?: string
}
export interface ThreadsPage {
items: Array<AgentThread>
total?: number
limit: number
offset: number
hasMore?: boolean
}
export interface SidebarThreadsGroup {
items: Array<AgentThread>
limit: number
hasMore: boolean
}
export interface SidebarThreads {
active: SidebarThreadsGroup
resolved: SidebarThreadsGroup
}
const API_BASE = (import.meta.env.VITE_DASHBOARD_API_BASE_URL ?? "").replace(
/\/$/,
""
)
export const agentsLangGraphApiUrl = `${API_BASE}/dashboard/api`
async function agentsRequest<T>(
path: string,
init: RequestInit = {}
): Promise<T> {
const res = await fetch(`${API_BASE}/dashboard/api${path}`, {
...init,
credentials: "include",
headers: {
"Content-Type": "application/json",
...(init.headers ?? {}),
},
})
if (!res.ok) {
let message = res.statusText
try {
const body = await res.json()
if (body?.detail) {
message =
typeof body.detail === "string"
? body.detail
: JSON.stringify(body.detail)
}
} catch {
/* ignore */
}
throw new AgentsApiError(res.status, message)
}
if (res.status === 204) return undefined as T
return (await res.json()) as T
}
function filenameFromContentDisposition(value: string | null): string | null {
const match = /filename="([^"]+)"/.exec(value ?? "")
return match?.[1] ?? null
}
async function agentsBlobRequest(path: string): Promise<ThreadRecoveryPatch> {
const res = await fetch(`${API_BASE}/dashboard/api${path}`, {
credentials: "include",
headers: { Accept: "text/x-diff" },
})
if (!res.ok) {
let message = res.statusText
try {
const body = await res.json()
if (body?.detail) {
message =
typeof body.detail === "string"
? body.detail
: JSON.stringify(body.detail)
}
} catch {
/* ignore */
}
throw new AgentsApiError(res.status, message)
}
return {
blob: await res.blob(),
filename:
filenameFromContentDisposition(res.headers.get("content-disposition")) ??
"open-swe-recovery.patch",
}
}
function buildThreadsPageQuery(params: ThreadsPageParams): string {
const search = new URLSearchParams()
if (params.limit != null) search.set("limit", String(params.limit))
if (params.offset != null) search.set("offset", String(params.offset))
if (params.resolved != null) search.set("resolved", String(params.resolved))
if (params.viewed != null) search.set("viewed", String(params.viewed))
if (params.source) search.set("source", params.source)
if (params.status) search.set("status", params.status)
if (params.q) search.set("q", params.q)
const query = search.toString()
return query ? `?${query}` : ""
}
function buildSidebarThreadsQuery(params: {
activeLimit?: number
resolvedLimit?: number
}): string {
const search = new URLSearchParams()
if (params.activeLimit != null) {
search.set("active_limit", String(params.activeLimit))
}
if (params.resolvedLimit != null) {
search.set("resolved_limit", String(params.resolvedLimit))
}
const query = search.toString()
return query ? `?${query}` : ""
}
export const agentsApi = {
langGraphApiUrl: agentsLangGraphApiUrl,
listSidebarThreads: (params: {
activeLimit?: number
resolvedLimit?: number
}) =>
agentsRequest<SidebarThreads>(
`/threads/sidebar${buildSidebarThreadsQuery(params)}`
),
listThreadsPage: (params: ThreadsPageParams = {}) =>
agentsRequest<ThreadsPage>(`/threads/page${buildThreadsPageQuery(params)}`),
resolveThread: (threadId: string, resolved: boolean) =>
agentsRequest<AgentThread>(
`/threads/${encodeURIComponent(threadId)}/resolve`,
{
method: "POST",
body: JSON.stringify({ resolved }),
}
),
listSchedules: () => agentsRequest<Array<AgentSchedule>>("/schedules"),
createSchedule: (body: ScheduleCreateRequest) =>
agentsRequest<AgentSchedule>("/schedules", {
method: "POST",
body: JSON.stringify(body),
}),
updateSchedule: (scheduleId: string, body: ScheduleUpdateRequest) =>
agentsRequest<AgentSchedule>(
`/schedules/${encodeURIComponent(scheduleId)}`,
{
method: "PATCH",
body: JSON.stringify(body),
}
),
deleteSchedule: (scheduleId: string) =>
agentsRequest<void>(`/schedules/${encodeURIComponent(scheduleId)}`, {
method: "DELETE",
}),
getThread: (threadId: string, options?: { markViewed?: boolean }) =>
agentsRequest<AgentThread>(
`/threads/${encodeURIComponent(threadId)}${
options?.markViewed === false ? "?mark_viewed=false" : ""
}`
),
queueMessage: (threadId: string, body: ThreadMessageRequest) =>
agentsRequest<AgentThread>(
`/threads/${encodeURIComponent(threadId)}/messages`,
{
method: "POST",
body: JSON.stringify(body),
}
),
cancelThread: (threadId: string) =>
agentsRequest<AgentThread>(
`/threads/${encodeURIComponent(threadId)}/cancel`,
{
method: "POST",
}
),
deleteThread: (threadId: string) =>
agentsRequest<void>(`/threads/${encodeURIComponent(threadId)}`, {
method: "DELETE",
}),
getThreadPrDiff: (threadId: string) =>
agentsRequest<ThreadPrDiff>(
`/threads/${encodeURIComponent(threadId)}/pr-diff`
),
downloadThreadRecoveryPatch: (threadId: string) =>
agentsBlobRequest(
`/threads/${encodeURIComponent(threadId)}/recovery.patch`
),
streamUrl: (threadId: string) =>
`${API_BASE}/dashboard/api/threads/${encodeURIComponent(threadId)}/stream`,
listWorkflowApprovals: (threadId: string) =>
agentsRequest<WorkflowPushApprovalsResponse>(
`/workflow-approval/${encodeURIComponent(threadId)}`
),
approveWorkflowPush: (threadId: string, fingerprint: string) =>
agentsRequest<WorkflowApprovalDecision>(
`/workflow-approval/${encodeURIComponent(threadId)}/${encodeURIComponent(
fingerprint
)}/approve`,
{ method: "POST" }
),
rejectWorkflowPush: (threadId: string, fingerprint: string) =>
agentsRequest<WorkflowApprovalDecision>(
`/workflow-approval/${encodeURIComponent(threadId)}/${encodeURIComponent(
fingerprint
)}/reject`,
{ method: "POST" }
),
}
export type ThreadGroup = "today" | "last7" | "last30" | "older"
export function groupThreads(
threads: Array<AgentThread>
): Record<ThreadGroup, Array<AgentThread>> {
const todayStart = new Date()
todayStart.setHours(0, 0, 0, 0)
const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
const thirtyDaysAgo = Date.now() - 30 * 24 * 60 * 60 * 1000
const groups: Record<ThreadGroup, Array<AgentThread>> = {
today: [],
last7: [],
last30: [],
older: [],
}
for (const thread of [...threads].sort((a, b) => b.updatedAt - a.updatedAt)) {
if (thread.updatedAt >= todayStart.getTime()) {
groups.today.push(thread)
} else if (thread.updatedAt >= sevenDaysAgo) {
groups.last7.push(thread)
} else if (thread.updatedAt >= thirtyDaysAgo) {
groups.last30.push(thread)
} else {
groups.older.push(thread)
}
}
return groups
}