open-swe/agent/dashboard/routes.py
Adam Moussa 1f060f2a1d
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
chore: sync upstream/main, defer #1621 modular webhooks (#81)
* chore: bake sfw binary into sandbox image (#1611)

sfw only ships a launcher that fetches its real binary at first run and does a
daily update check against api.github.com/repos/SocketDev/sfw-free. Both fail in
the sandbox (restricted egress; the proxy injects the GitHub App installation
token, which lacks access to that repo), so `sfw yarn install` errors with
"could not fetch its binary". Pin sfw 2.0.6, warm + verify the binary cache at
build, and set SFW_SKIP_UPDATE_CHECK=1 so runs use the baked binary offline.

* feat: editable plan mode + fix review-plan banner overlap (#1610)

* feat: editable plan mode + fix review-plan banner overlap

Lets the thread owner edit the plan markdown by hand from the plan-review
page (Edit -> textarea -> Save) via a new PUT /dashboard/api/plan/{id}
endpoint that re-publishes the plan and mirrors it into the sandbox
plan.md, so approve hands the edited plan to the agent as the source of
truth. Also fixes the collapsed git-panel's floating expand button
covering the "Review plan ->" banner by reserving space for it.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: abort plan approval when the published plan read fails

get_plan_content() swallowed store errors and returned None, so a
transient failure during approve would still mark the plan approved and
dispatch the generic fallback text — silently dropping an owner's edited
plan. Read the plan strictly (raise_on_error=True) so approval aborts
instead, matching the comment read.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: show message timestamps (#1609)

* feat: show message timestamps

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: suppress fallback message timestamps

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: stable message + tool-call hover timestamps

Stamp a stable client-side arrival time per message and tool call (keyed
by id, persisted to localStorage). Messages render the timestamp inline;
tool rows reveal a dim timestamp chip on hover. Real backend created_at
still takes precedence when present.

* fix: hide client-stamped message timestamps

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: add PR trace resolution (#1612)

* feat: add PR trace resolution

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: inject reviewer trace context as JSON

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: address review on PR trace resolution

Use the documented LangSmith metadata filter syntax
(and(eq(metadata_key,...), eq(metadata_value,...))) instead of
has(metadata, '{...}'), which does not match runs — _list_thread_runs
was silently returning nothing. Bound full-text searches to a 90-day
window so they don't hit LangSmith's large-window rate limit.

Also folds in the best-effort branch->head-sha resolver (dropping the
weighted scoring/threshold + repo/file evidence + GitHub hydration),
sandbox JSON injection, and the admin "Resolve trace" dry-run endpoint.

The IDOR findings are moot: resolve_pr_to_threads/summarize_agent_session
were removed; resolution now runs deterministically from the trusted run
config with no model-controlled pr_url or thread_id.

* fix: scope branch trace search to the repo

Branch names like fix-tests aren't unique across repos (or older PRs) in
a shared tracing project, so an unscoped branch hit could resolve to an
unrelated thread and write its runs into the reviewer sandbox. Require
the repo slug to co-occur with the branch in matched runs; the full head
SHA stays unscoped since it is globally unique. Addresses open-swe review
on PR #1612.

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: include plan links in PR descriptions (#1613)

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: gate workflow pushes with approval (#1614)

* feat: gate workflow pushes with approval

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: preserve proxy refresh test compatibility

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: bind workflow approvals to pushed ref

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: recover thread work as patch (#1615)

* feat: recover thread work as patch

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: search sandbox cwd for recovery patches

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: omit plan link in PR description when no plan exists (#1618)

Plan links in PR descriptions were always built from the thread id, so
runs that never produced a plan linked to an empty plan-review page.
Now the plan content store is consulted first; the link is only added
when a plan with non-empty markdown actually exists. A transient store
failure degrades gracefully (no link) rather than blocking PR creation.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: add filter & grouping menu to agents threads sidebar (#1617)

Add a Cursor-style control to the agents sidebar that groups (None/Date/
Status/Project), filters (ownership, status, source, pull request, model,
repo, include-resolved), and compacts the threads list. All client-side over
already-fetched sidebar threads; preferences persist in localStorage.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: update langsmith sdk to 0.9.3 (#1616)

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: clickable shared PR header in git panel and reviews (#1620)

* feat: clickable shared PR header in git panel and reviews

Replace the standalone "View PR" button in the agent git panel with a
clickable PR title, matching the reviews view. Extract a shared PrHeader
component reused by both the git panel and the review main body.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* refactor: drop PrHeader wrapper, use shared component directly

The review-side PrHeader was just a thin adapter mapping detail -> the
shared component's props. Inline it at the call site and use the shared
PrHeader directly so there's a single component.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* refactor: durable interrupt dispatch + completion webhook (#1621)

* wip(rebuild): core reliability spine

- remove PR-babysitting (ci_autofix + ci_monitor graph + webhook wiring)
- dispatch core: agent/dispatch.py with multitask_strategy=interrupt +
  durability=sync + completion webhook; reroute all webhook + plan triggers;
  drop the racy in-process lock + is_thread_active busy-check
- completion webhook: agent/completion.py + /webhooks/run-complete loopback
  route for failure/timeout replies (idempotent)

Co-authored-by: open-swe[bot]

* feat(rebuild): async tools, reconcile, shared http timeouts, assembly tuning

Parallel batch on top of the reliability spine:
- async-ify all 24 tools (drop asyncio.run; requests->httpx); re-implement the
  http_request/fetch_url SSRF + DNS-rebinding defense httpx-natively and harden
  the IP check to 'not is_global' (+ IPv4-mapped unwrap)
- reconcile.py: stale pending-run sweep (threads.search -> per-thread runs.list
  -> cancel_many), wired into the scheduler graph via task='reconcile'
- shared DEFAULT_HTTP_TIMEOUT (agent/utils/http.py) on every bare
  httpx.AsyncClient() across utils/dashboard/webapp/middleware
- run budget: MODEL_CALL_RECURSION_LIMIT 5000->250
- fix stale OpenAI->Anthropic fallback id (claude-opus-4-5 -> 4-8)
- drop redundant custom repair middleware (deepagents auto-adds PatchToolCalls)
- confirm tool-result eviction + summarization auto-wired via backend
- slim system prompt ~8% (full harness-profile rewrite deferred)

Co-authored-by: open-swe[bot]

* feat(rebuild): harness-profile prompt + split webhooks out of webapp

- prompt.py: own the system prompt via a registered harness profile
  (OPEN_SWE_SHARED_BASE, kept neutral so the read-only reviewer/analyzer that
  share it stay safe), registered across all 4 providers; per-thread values
  stay in construct_system_prompt. Assembled main-agent prompt ~6.8k -> ~3.1k
  tokens (~55% smaller); de-duped PR/commit/suite/force-push guidance; dropped
  ALL-CAPS markers.
- webapp.py 3325 -> 1890 LOC: moved 14 per-source handlers into
  agent/webhooks/{linear,slack,github}.py; webapp re-exports them for the
  routes + tests; moved handlers reach shared helpers via the webapp namespace
  to preserve the test suite's monkeypatch targets.

Full suite: 1168 passing, lint clean.

Co-authored-by: open-swe[bot]

* Restore MODEL_CALL_RECURSION_LIMIT to 5000 for long-running tasks

Reverts the 250 cap from the run-budget change — long-running tasks legitimately
need many model calls. The notify_step_limit_reached safety net still fires if a
run does hit the cap, so runs end with a signal either way.

Co-authored-by: open-swe[bot]

* fix: address PR review (auth, SSRF, interrupted status, redirect headers)

- completion.py: drop `interrupted` from failure statuses — with
  multitask_strategy=interrupt a follow-up ends the prior run as interrupted,
  which is healthy, not a failure to report. [open-swe]
- /webhooks/run-complete: shared-secret auth — dispatch appends ?token= when
  RUN_COMPLETE_WEBHOOK_SECRET is set; route verifies via hmac.compare_digest.
  [corridor-security]
- SSRF: extract the URL validator to agent/utils/url_safety.py and apply it
  before server-side image fetches in multimodal.fetch_image_block.
  [corridor-security]
- http_request: preserve caller headers/extensions across redirect hops instead
  of dropping them on the first hop. [open-swe]

Co-authored-by: open-swe[bot]

* chore: remove REBUILD_PLAN.md (planning doc, not needed in the repo)

Co-authored-by: open-swe[bot]

* fix: fail closed on run-complete webhook auth when secret unset

Corridor follow-up: verify_run_complete_token returns False (not True) when
RUN_COMPLETE_WEBHOOK_SECRET is unset, so the public route is never
unauthenticated. Logs a startup warning when the secret is absent, and dispatch
skips registering the webhook when there's no secret (no rejected callbacks).

Co-authored-by: open-swe[bot]

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: restore forced tool call to prevent premature run stops (#1622)

Restore the ensure_no_empty_msg middleware and the always-call-a-tool system-prompt instruction that #1535 removed. When the model emits a message with no tool call (and hasn't already messaged the user or confirmed completion), the middleware re-injects a no_op / confirming_completion tool call so the run continues instead of ending mid-task.

Shipping to test whether it fixes runs that stop halfway through.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore(deps): bump langgraph-checkpoint from 4.1.0 to 4.1.1 (#1619)

Bumps [langgraph-checkpoint](https://github.com/langchain-ai/langgraph) from 4.1.0 to 4.1.1.
- [Release notes](https://github.com/langchain-ai/langgraph/releases)
- [Commits](https://github.com/langchain-ai/langgraph/compare/checkpoint==4.1.0...checkpoint==4.1.1)

---
updated-dependencies:
- dependency-name: langgraph-checkpoint
  dependency-version: 4.1.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* fix: post reviewer resolution notes verbatim (#1624)

* fix: post reviewer resolution notes verbatim

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: stabilize dashboard follow-up e2e

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: preserve dashboard attribution in e2e

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: make e2e attribution marker durable

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: only echo found e2e attribution

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: check live dashboard attribution in e2e

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* hotfix: stop prompting agent/reviewer to wrap installs in sfw (#1625)

Installs hung when prefixed with sfw inside the sandbox (trace 019f0608
stalled on a pending `sfw npm install` execute, never returned). Strip the
Socket Firewall guidance from the agent and reviewer prompts so installs run
through the project's package manager directly. sfw stays in the Docker image;
nothing invokes it now.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: make plan view mobile friendly (#1636)

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: fall back to vision model for image threads (#1626)

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: surface Slack thread errors (#1627)

* fix: surface Slack thread errors

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: don't set failure_reply_posted on Slack preprocessing errors

The preprocessing error handler was setting failure_reply_posted=True,
the same idempotency flag handle_run_completion checks to suppress
duplicate run-failure replies. Since preprocessing failures happen
before any run exists but the flag persists on the thread, a subsequent
run failure on the same thread would be silently ignored.

The preprocessing handler already posts its own Slack reply, so the
run-completion idempotency flag should not be set here.

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: avoid recapping Slack replies (#1629)

* chore: avoid recapping Slack replies

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: simplify Slack reply prompt wording

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: update Slack trace reply on web handoff (#1630)

* fix: update Slack trace reply on web handoff

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: trigger web handoff on dashboard starts

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: format web handoff as contextual fragment

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: preserve trace_message_ts when overwriting Slack run mapping

When store_slack_run_mapping is called without trace_message_ts (e.g. on
follow-up Slack mentions), it was unconditionally overwriting the
thread-level mapping and clobbering the timestamp captured from the
initial trace reply. After that, _notify_slack_web_handoff could not find
the original message, so a subsequent move to Web silently skipped the
Slack trace update.

Now, when trace_message_ts is not passed, the existing thread mapping is
read first and its trace_message_ts is preserved.

* style: ruff format

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Johannes du Plessis <51395795+johannes117@users.noreply.github.com>
Co-authored-by: Johannes du Plessis <johannes@langchain.dev>

* fix: pre-bundle shiki/@pierre deps to stop dev dynamic-import failures (#1643)

* fix(ui): pre-bundle shiki/@pierre deps to stop dev dynamic-import failures

shiki lazy-imports a grammar per language and these libs only live inside
lazy route components, so Vite's startup scanner never sees them. They get
discovered on first thread navigation, triggering a dep re-optimize +
force-reload that aborts the in-flight route-chunk import, surfacing as
"Failed to fetch dynamically imported module: .../$threadId.tsx".

Pre-bundle them (and the github themes + common code-block languages) via
optimizeDeps.include so the optimize happens once at startup. Dev-only;
production bundles are unaffected.

* fix: pre-bundle canonical shiki docker/make langs instead of aliases

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: show queued dashboard follow-ups (#1631)

* feat: show queued dashboard follow-ups

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: de-dupe queued follow-ups while streaming

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Johannes du Plessis <johannes@langchain.dev>

* feat: notify Slack on plan approval (#1632)

* feat: notify Slack on plan approval

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: post Slack approval notice after successful dispatch

Move the _maybe_post_plan_approved_to_slack call until after
_dispatch_followup succeeds so the Slack thread is not told
implementation is beginning before the LangGraph run is created.

Addresses PR review comment.

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Johannes du Plessis <johannes@langchain.dev>

* feat: include Slack channel context in prompts (#1633)

Add cached Slack channel metadata enrichment for Slack-triggered runs so prompts can include channel names and descriptions without duplicate conversations.info calls.\n\nCo-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>

* chore: keep plan guidance high-level (#1634)

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: publish plans from sandbox files (#1635)

* feat: publish plans from sandbox files

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: avoid fixed plan filenames

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: virtualize local sandbox file paths

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: preserve plan_file_path across set_plan_status

set_plan_status was rewriting the content record with only markdown
and status, dropping plan_file_path. After a reject, the owner's
dashboard edit would mirror to a different file than the agent's
original, and the next save_plan could republish the stale file.
Preserve plan_file_path when updating status.

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: return to thread after plan approval (#1637)

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: add Slack breakout thread tool (#1638)

* feat: add Slack breakout thread tool

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: make fake LLM scripts declarative

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: exclude slack_start_new_thread from plan mode

The breakout tool can dispatch a fresh agent run that starts outside the
current plan-mode state, bypassing the approval flow. Add it to
PLAN_MODE_EXCLUDED_TOOLS so it's hidden alongside the other mutating
tools while planning.

---------

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: require bun for ui agent work (#1639)

Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: request actions read for sandbox logs (#1642)

* fix: request actions read for sandbox logs

Request optional Actions read permission for sandbox proxy tokens, with fallback for installations that have not approved it yet. Update setup docs and prompt guidance for safe GitHub Actions log usage.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: restore actions:read scope after workflow push

After an approved workflow push, the guard was restoring the proxy with
BASE_RUNTIME_PROXY_TOKEN_PERMISSIONS, which excludes the actions: read
scope this PR adds. Restore with RUNTIME_PROXY_TOKEN_PERMISSIONS (which
includes actions: read) and fall back to BASE if the install hasn't
granted Actions read — mirroring the pattern in _create_sandbox_with_proxy.

Addresses review comment on PR #1642.

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* fix: widen split review diffs (#1647)

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: install missing deps before verification (#1646)

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: switch ui to pnpm (#1645)

* chore: require pnpm for ui agent work

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: switch ui to pnpm

Replace Bun and Yarn lockfiles with pnpm lockfile and update UI/Vercel commands to use pnpm.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* ci: use corepack for ui pnpm e2e build

Run pnpm through Corepack in the E2E global setup so CI can use the pinned package manager without a separate pnpm install step.

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* feat: add Sonnet 5 to model picker (#1651)

* chore: update Sonnet examples to Sonnet 5

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* chore: add Sonnet 5 to model picker

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

---------

Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>

* Remove dead breakout-thread e2e scenario after dropping the tool

The merge resolution deferred upstream's Slack breakout-thread tool
(slack_start_new_thread, #1638) since it depends on the #1621 dispatch
module, but the e2e harness still scripted it. Removing the tool name
from fake_llm.py's _tool_step call left a malformed scenario, crashing
the langgraph-dev web server at import (TypeError: _tool_step() missing
'call_id') and failing Playwright E2E.

Drop the "breakout" script scenario, its _is_breakout_request helper +
ScriptRule, and the corresponding full_flow.spec.ts test.

* Revert upstream pnpm switch; keep bun for the UI build

The merge auto-adopted upstream's pnpm switch (#1645) in tests/e2e/
global-setup.ts and ui/package.json, but our fork builds the UI with
bun (vercel.json + the E2E workflow's setup-bun). That left the
Playwright globalSetup running `corepack pnpm install --frozen-lockfile`
with no pnpm-lock.yaml, failing E2E at UI build time.

Revert global-setup.ts and ui/package.json to the dev (bun) baseline,
drop the merge-added ui/pnpm-lock.yaml, and remove the re-added
ui/AGENTS.md (our fork had deleted it).

* Align plan-review e2e + UI with the HEAD (pre-#1635) backend

The merge left a split plan vertical: the backend save_plan/plan_api are
HEAD (we deferred the editable-plan/sandbox-publish features #1610/#1635/
#1637 per #80), but the plan UI and e2e harness were upstream's. The
fake_llm scenario called save_plan(plan_file_path=...) — upstream's
file-based #1635 contract — while HEAD save_plan takes plan_markdown,
so the plan never saved and PlanReview never rendered (E2E failure on
the plan-review locator).

Pass plan_markdown to save_plan, and revert PlanReview.tsx / plan.ts /
$threadId_.plan.tsx / plan_review.spec.ts to the dev baseline so the
whole plan flow (save -> render -> approve -> implement) is consistent
with the HEAD backend.

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Johannes du Plessis <johannes@langchain.dev>
Co-authored-by: open-swe[bot] <open-swe@users.noreply.github.com>
Co-authored-by: Ramon Nogueira <ramon.nogueira@langchain.dev>
Co-authored-by: Ramon Nogueira <270434257+ramon-langchain@users.noreply.github.com>
Co-authored-by: Caroline di Vittorio <43390382+carolinedivittorio@users.noreply.github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Johannes du Plessis <51395795+johannes117@users.noreply.github.com>
Co-authored-by: Ankush Gola <9536492+agola11@users.noreply.github.com>
Co-authored-by: Mukil Loganathan <mukil@langchain.dev>
2026-06-30 16:45:19 -04:00

1755 lines
55 KiB
Python

"""FastAPI router for the dashboard backend."""
from __future__ import annotations
import hmac
import logging
import os
from typing import Any, Literal
import httpx
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request
from fastapi.responses import RedirectResponse, Response, StreamingResponse
from pydantic import BaseModel
from .admin import is_admin
from .agent_instructions import (
AgentInstructionsCreate,
AgentInstructionsUpdate,
create_agent_instructions,
delete_agent_instructions,
get_agent_instructions,
list_agent_instructions,
set_agent_instructions,
)
from .agent_usage import (
list_agent_usage_leaderboard,
refresh_reviewer_stats_cache,
refresh_usage_leaderboard_cache,
)
from .analyzer_cron import remove_continual_cron
from .enabled_repos import (
list_enabled_review_repos,
set_review_repo_enabled,
)
from .eval_jobs import (
get_reviewer_eval_status,
)
from .notion_oauth import (
NOTION_STATE_COOKIE_NAME,
NotionOAuthError,
exchange_notion_code,
pop_notion_oauth_flow,
store_notion_oauth_flow,
)
from .oauth import (
COOKIE_NAME,
SESSION_TTL_SECONDS,
STATE_COOKIE_NAME,
STATE_TTL_SECONDS,
decode_state,
enforce_org_login_gate,
exchange_code,
fetch_github_user,
hash_state_nonce,
issue_session,
issue_state,
new_state_nonce,
require_same_origin_for_mutations,
require_session,
sanitize_redirect_to,
)
from .options import SUPPORTED_MODELS
from .profiles import (
ProfileUpdate,
get_profile,
get_valid_access_token,
upsert_access_token_from_github_response,
upsert_profile,
)
from .repo_access import require_repo_access_for_user
from .repo_snapshots import (
RepoSnapshotConfigError,
RepoSnapshotCreate,
RepoSnapshotUpdate,
create_repo_snapshot,
delete_repo_snapshot,
generate_dockerfile_template,
get_repo_snapshot,
is_repo_snapshot_build_stale,
list_repo_snapshots,
mark_repo_snapshot_building,
run_snapshot_build,
update_repo_snapshot,
)
from .review_api import (
create_review_comment,
dry_run_trace_resolution,
get_review,
get_review_diff,
list_review_comments,
list_reviews,
proxy_pr_image,
trigger_re_review,
)
from .review_chat_api import (
delete_review_chat_thread,
get_review_chat,
list_review_chat_threads,
proxy_review_chat_commands,
proxy_review_chat_history,
proxy_review_chat_state,
proxy_review_chat_stream_events,
)
from .review_style_jobs import (
cancel_review_style_analysis,
start_bootstrap_analysis,
sync_review_style_run_status,
)
from .review_styles import (
ReviewStyleCreate,
ReviewStylePromptUpdate,
create_review_style,
delete_review_style,
get_review_style,
list_review_styles,
normalize_repo_full_name,
set_custom_prompt,
)
from .schedules import (
ScheduleCreateBody,
ScheduleUpdateBody,
create_agent_schedule,
delete_agent_schedule,
list_agent_schedules,
update_agent_schedule,
)
from .slack_oauth import (
SLACK_STATE_COOKIE_NAME,
build_authorize_url,
exchange_slack_code,
fetch_slack_identity,
slack_oauth_configured,
verify_team,
)
from .team_credentials import (
DatadogCredentialsUpdate,
LangSmithCredentialsUpdate,
connect_datadog,
connect_langsmith,
disconnect_datadog,
disconnect_langsmith,
get_team_credentials_status,
)
from .team_settings import (
TeamSettingsUpdate,
get_team_default_model,
get_team_default_subagent_model,
get_team_settings,
upsert_team_settings,
)
from .thread_api import (
ThreadMessageBody,
ThreadResolveBody,
cancel_dashboard_thread,
delete_dashboard_thread,
get_dashboard_thread,
get_dashboard_thread_pr_diff,
get_dashboard_thread_recovery_patch,
get_dashboard_thread_state,
list_dashboard_threads,
list_dashboard_threads_page,
list_dashboard_threads_sidebar,
proxy_dashboard_thread_commands,
proxy_dashboard_thread_history,
proxy_dashboard_thread_run_cancel,
proxy_dashboard_thread_stream_events,
resolve_dashboard_thread,
send_dashboard_message,
stream_dashboard_thread,
)
from .user_credentials import (
CurrentsCredentialsUpdate,
connect_currents,
connect_notion,
disconnect_currents,
disconnect_notion,
get_currents_status,
get_notion_status,
)
from .user_mappings import (
delete_mapping,
get_mapping,
list_mappings,
upsert_mapping,
)
logger = logging.getLogger(__name__)
router = APIRouter(
prefix="/dashboard/api",
tags=["dashboard"],
dependencies=[Depends(require_same_origin_for_mutations)],
)
_GITHUB_API_TIMEOUT = httpx.Timeout(10.0, connect=3.0)
_SKIPPABLE_INSTALLATION_REPO_STATUS_CODES = frozenset({403, 404})
def _session_is_admin(session: dict[str, Any]) -> bool:
return is_admin(session.get("email"), login=session.get("sub"))
def _require_admin(session: dict[str, Any]) -> dict[str, Any]:
if not _session_is_admin(session):
raise HTTPException(403, "admin only")
return session
_SESSION_DEP = Depends(require_session)
def _admin_session(session: dict[str, Any] = _SESSION_DEP) -> dict[str, Any]:
return _require_admin(session)
_ADMIN_DEP = Depends(_admin_session)
async def _filter_repo_records_for_user(
login: str,
records: list[dict[str, Any]],
) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for record in records:
full_name = record.get("full_name")
if not isinstance(full_name, str):
continue
try:
await require_repo_access_for_user(login, full_name)
except HTTPException as exc:
if exc.status_code in {403, 404}:
continue
raise
out.append(record)
return out
def _api_base_url() -> str:
v = os.environ.get("DASHBOARD_API_BASE_URL", "").rstrip("/")
if not v:
raise HTTPException(500, "DASHBOARD_API_BASE_URL not configured")
if not v.startswith(("http://", "https://")):
# A schemeless value (e.g. "open-swe-prod.us.langgraph.app") produces a
# schemeless OAuth redirect_uri, which GitHub rejects with
# "redirect_uri not associated with this application". Managed
# deployments are served over HTTPS, so default to https:// when the
# operator omitted the scheme.
v = f"https://{v}"
return v
def _frontend_base_url() -> str:
v = os.environ.get("DASHBOARD_BASE_URL", "").rstrip("/")
if not v:
raise HTTPException(500, "DASHBOARD_BASE_URL not configured")
return v
def _cookie_security() -> tuple[bool, str]:
"""Cookie ``secure``/``samesite`` flags derived from the API scheme.
Production serves the API over HTTPS and the dashboard is a separate
(cross-site) origin, so the session cookie must be ``Secure; SameSite=None``.
Local dev runs over ``http://localhost`` where ``Secure`` cookies are
rejected and the frontend/API are same-site, so fall back to
``SameSite=Lax`` without ``Secure``.
"""
api = os.environ.get("DASHBOARD_API_BASE_URL", "")
# Only an explicit ``http://`` (local dev) or an unconfigured value falls
# back to the insecure same-site cookie. ``https://`` *and* a schemeless
# managed host (which ``_api_base_url`` coerces to https) are cross-site
# over TLS and must use ``Secure; SameSite=None``.
if not api or api.startswith("http://"):
return False, "lax"
return True, "none"
def _set_session_cookie(response: Response, jwt_token: str) -> None:
secure, samesite = _cookie_security()
response.set_cookie(
key=COOKIE_NAME,
value=jwt_token,
max_age=SESSION_TTL_SECONDS,
httponly=True,
secure=secure,
samesite=samesite,
path="/",
)
def _set_state_cookie(response: Response, nonce: str) -> None:
# SameSite=Lax so GitHub's top-level redirect back to /auth/callback
# still presents this cookie; the cookie is single-purpose and lives
# only for the duration of one OAuth round-trip.
#
# This cookie is intentionally host-only (no Domain attribute): scoping it
# to a shared parent domain is not safe across Vercel's immutable per-deploy
# hostnames (``*.vercel.app`` is on the public-suffix list, so a Domain
# cookie there is rejected). The operational contract is therefore to
# *always start login on the stable alias / custom domain* so the host that
# sets this cookie is the same host GitHub redirects back to. Starting the
# flow on an immutable per-deploy URL and finishing on the alias (or vice
# versa) drops the cookie and surfaces as "oauth state mismatch".
secure, _ = _cookie_security()
response.set_cookie(
key=STATE_COOKIE_NAME,
value=nonce,
max_age=STATE_TTL_SECONDS,
httponly=True,
secure=secure,
samesite="lax",
path="/dashboard/api/auth",
)
def _clear_state_cookie(response: Response) -> None:
secure, _ = _cookie_security()
response.delete_cookie(
STATE_COOKIE_NAME, path="/dashboard/api/auth", samesite="lax", secure=secure
)
def _set_slack_state_cookie(response: Response, nonce: str) -> None:
secure, _ = _cookie_security()
response.set_cookie(
key=SLACK_STATE_COOKIE_NAME,
value=nonce,
max_age=STATE_TTL_SECONDS,
httponly=True,
secure=secure,
samesite="lax",
path="/dashboard/api/slack",
)
def _clear_slack_state_cookie(response: Response) -> None:
secure, _ = _cookie_security()
response.delete_cookie(
SLACK_STATE_COOKIE_NAME, path="/dashboard/api/slack", samesite="lax", secure=secure
)
def _set_notion_state_cookie(response: Response, nonce: str) -> None:
secure, _ = _cookie_security()
response.set_cookie(
key=NOTION_STATE_COOKIE_NAME,
value=nonce,
max_age=STATE_TTL_SECONDS,
httponly=True,
secure=secure,
samesite="lax",
path="/dashboard/api/notion",
)
def _clear_notion_state_cookie(response: Response) -> None:
secure, _ = _cookie_security()
response.delete_cookie(
NOTION_STATE_COOKIE_NAME, path="/dashboard/api/notion", samesite="lax", secure=secure
)
@router.get("/auth/login")
async def auth_login(
request: Request,
redirect_to: str | None = None,
) -> RedirectResponse:
client_id = os.environ.get("GITHUB_APP_CLIENT_ID", "")
if not client_id:
raise HTTPException(500, "GITHUB_APP_CLIENT_ID not configured")
safe_redirect = sanitize_redirect_to(redirect_to) or _frontend_base_url()
nonce = new_state_nonce()
state = issue_state(
redirect_to=safe_redirect,
nonce_hash=hash_state_nonce(nonce),
)
redirect_uri = f"{_api_base_url()}/dashboard/api/auth/callback"
url = (
"https://github.com/login/oauth/authorize"
f"?client_id={client_id}"
f"&redirect_uri={redirect_uri}"
f"&state={state}"
)
response = RedirectResponse(url, status_code=302)
_set_state_cookie(response, nonce)
return response
@router.get("/auth/callback")
async def auth_callback(request: Request, code: str, state: str) -> RedirectResponse:
state_payload = decode_state(state)
state_nonce_hash = state_payload.get("nonce_hash")
cookie_nonce = request.cookies.get(STATE_COOKIE_NAME)
if (
not isinstance(state_nonce_hash, str)
or not cookie_nonce
or not hmac.compare_digest(hash_state_nonce(cookie_nonce), state_nonce_hash)
):
# Either the cookie went missing (different browser, expired,
# cookies blocked) or the state was issued for a different session.
raise HTTPException(400, "oauth state mismatch — please retry login")
redirect_to = sanitize_redirect_to(state_payload.get("redirect_to")) or _frontend_base_url()
token_data = await exchange_code(code)
access_token = token_data.get("access_token")
if not isinstance(access_token, str):
raise HTTPException(400, "oauth exchange missing access_token")
user, email = await fetch_github_user(access_token)
login = user.get("login")
if not login:
raise HTTPException(400, "could not resolve GitHub login")
await enforce_org_login_gate(login)
await upsert_access_token_from_github_response(login, email or "", token_data)
session_jwt = issue_session(login=login, email=email, avatar_url=user.get("avatar_url"))
response = RedirectResponse(redirect_to, status_code=302)
_set_session_cookie(response, session_jwt)
_clear_state_cookie(response)
return response
@router.post("/auth/logout")
async def auth_logout() -> Response:
response = Response(status_code=204)
secure, samesite = _cookie_security()
response.delete_cookie(COOKIE_NAME, path="/", samesite=samesite, secure=secure)
return response
@router.get("/me")
async def me(session: dict[str, Any] = _SESSION_DEP) -> dict[str, Any]:
return {
"login": session["sub"],
"email": session.get("email"),
"avatar_url": session.get("avatar_url"),
"is_admin": _session_is_admin(session),
"slack_oauth_enabled": slack_oauth_configured(),
}
@router.get("/options")
async def options() -> dict[str, Any]:
agent_model, agent_effort = await get_team_default_model("agent")
subagent_model, subagent_effort = await get_team_default_subagent_model("agent")
return {
"models": SUPPORTED_MODELS,
"default_agent_model": agent_model,
"default_agent_reasoning_effort": agent_effort,
"default_agent_subagent_model": subagent_model,
"default_agent_subagent_reasoning_effort": subagent_effort,
}
@router.get("/profile")
async def get_my_profile(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
profile = await get_profile(session["sub"])
return profile or {}
@router.put("/profile")
async def put_my_profile(
update: ProfileUpdate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
update.validate_pairing()
return await upsert_profile(session["sub"], session.get("email") or "", update)
@router.get("/my-mapping")
async def get_my_mapping(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
"""Return the logged-in user's own GitHub↔Slack mapping (or empty)."""
mapping = await get_mapping(session["sub"])
return mapping or {}
@router.get("/my-credentials/currents")
async def get_my_currents_status(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
status = await get_currents_status(session["sub"])
return status.get("currents", {"connected": False})
@router.put("/my-credentials/currents")
async def connect_my_currents(
update: CurrentsCredentialsUpdate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
status = await connect_currents(session["sub"], update)
return status.get("currents", {"connected": False})
@router.delete("/my-credentials/currents")
async def disconnect_my_currents(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
status = await disconnect_currents(session["sub"])
return status.get("currents", {"connected": False})
@router.get("/my-credentials/notion")
async def get_my_notion_status(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
status = await get_notion_status(session["sub"])
return status.get("notion", {"connected": False})
@router.delete("/my-credentials/notion")
async def disconnect_my_notion(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
status = await disconnect_notion(session["sub"])
return status.get("notion", {"connected": False})
@router.get("/notion/login")
async def notion_login(
session: dict[str, Any] = _SESSION_DEP,
) -> RedirectResponse:
redirect_uri = f"{_api_base_url()}/dashboard/api/notion/callback"
nonce = new_state_nonce()
nonce_hash = hash_state_nonce(nonce)
state = issue_state(
redirect_to=f"{_frontend_base_url()}/my-settings",
nonce_hash=nonce_hash,
)
try:
url = await store_notion_oauth_flow(
session["sub"],
nonce_hash,
redirect_uri=redirect_uri,
state=state,
)
except NotionOAuthError as exc:
raise HTTPException(exc.status_code, exc.detail) from exc
response = RedirectResponse(url, status_code=302)
_set_notion_state_cookie(response, nonce)
return response
@router.get("/notion/callback")
async def notion_callback(
request: Request,
state: str,
code: str | None = None,
error: str | None = None,
error_description: str | None = None,
session: dict[str, Any] = _SESSION_DEP,
) -> RedirectResponse:
state_payload = decode_state(state)
nonce_hash = state_payload.get("nonce_hash")
cookie_nonce = request.cookies.get(NOTION_STATE_COOKIE_NAME)
if (
not isinstance(nonce_hash, str)
or not cookie_nonce
or not hmac.compare_digest(hash_state_nonce(cookie_nonce), nonce_hash)
):
raise HTTPException(400, "oauth state mismatch — please retry")
flow = await pop_notion_oauth_flow(session["sub"], nonce_hash)
if flow is None:
raise HTTPException(400, "oauth flow expired — please retry")
if error:
detail = error_description or error
raise HTTPException(400, f"Notion OAuth failed: {detail}")
if not code:
raise HTTPException(400, "Notion OAuth callback missing code")
try:
token_data = await exchange_notion_code(code, flow)
await connect_notion(session["sub"], token_data, flow)
except NotionOAuthError as exc:
raise HTTPException(exc.status_code, exc.detail) from exc
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
redirect_to = sanitize_redirect_to(state_payload.get("redirect_to")) or _frontend_base_url()
response = RedirectResponse(redirect_to, status_code=302)
_clear_notion_state_cookie(response)
return response
@router.get("/slack/login")
async def slack_login(
_session: dict[str, Any] = _SESSION_DEP,
) -> RedirectResponse:
"""Start the Sign in with Slack flow to link the current GitHub account."""
if not slack_oauth_configured():
raise HTTPException(500, "Slack OAuth is not configured")
redirect_uri = f"{_api_base_url()}/dashboard/api/slack/callback"
nonce = new_state_nonce()
state = issue_state(
redirect_to=f"{_frontend_base_url()}/my-settings",
nonce_hash=hash_state_nonce(nonce),
)
response = RedirectResponse(
build_authorize_url(redirect_uri=redirect_uri, state=state), status_code=302
)
_set_slack_state_cookie(response, nonce)
return response
@router.get("/slack/callback")
async def slack_callback(
request: Request,
code: str,
state: str,
session: dict[str, Any] = _SESSION_DEP,
) -> RedirectResponse:
"""Link the verified Slack identity to the logged-in GitHub user.
The Slack member id and email come from Slack's verified OIDC claims, so a
user can only ever link their own Slack account — no self-asserted values.
"""
state_payload = decode_state(state)
nonce_hash = state_payload.get("nonce_hash")
cookie_nonce = request.cookies.get(SLACK_STATE_COOKIE_NAME)
if (
not isinstance(nonce_hash, str)
or not cookie_nonce
or not hmac.compare_digest(hash_state_nonce(cookie_nonce), nonce_hash)
):
raise HTTPException(400, "oauth state mismatch — please retry")
redirect_to = sanitize_redirect_to(state_payload.get("redirect_to")) or _frontend_base_url()
redirect_uri = f"{_api_base_url()}/dashboard/api/slack/callback"
access_token = await exchange_slack_code(code, redirect_uri)
identity = await fetch_slack_identity(access_token)
verify_team(identity)
if not identity.email or not identity.email_verified:
raise HTTPException(400, "your Slack account has no verified email to link")
await upsert_mapping(
github_login=session["sub"],
work_email=identity.email,
slack_user_id=identity.user_id,
source="slack_oauth",
status="active",
)
response = RedirectResponse(redirect_to, status_code=302)
_clear_slack_state_cookie(response)
return response
@router.get("/team-settings")
async def api_get_team_settings(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await get_team_settings()
@router.put("/team-settings")
async def api_put_team_settings(
update: TeamSettingsUpdate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await upsert_team_settings(update)
@router.get("/team-credentials")
async def api_get_team_credentials(
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await get_team_credentials_status()
@router.put("/team-credentials/datadog")
async def api_connect_datadog(
update: DatadogCredentialsUpdate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await connect_datadog(update)
@router.delete("/team-credentials/datadog")
async def api_disconnect_datadog(
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await disconnect_datadog()
@router.put("/team-credentials/langsmith")
async def api_connect_langsmith(
update: LangSmithCredentialsUpdate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await connect_langsmith(update)
@router.delete("/team-credentials/langsmith")
async def api_disconnect_langsmith(
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await disconnect_langsmith()
class EnabledReviewRepoUpdate(BaseModel):
full_name: str
enabled: bool
@router.get("/enabled-review-repos")
async def api_list_enabled_review_repos(
_session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, list[str]]:
return {"repos": await list_enabled_review_repos()}
@router.put("/enabled-review-repos")
async def api_set_enabled_review_repo(
update: EnabledReviewRepoUpdate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, list[str]]:
repos = await set_review_repo_enabled(update.full_name, update.enabled)
return {"repos": repos}
@router.get("/repo-snapshots")
async def api_list_repo_snapshots(
_admin: dict[str, Any] = _ADMIN_DEP,
) -> list[dict[str, Any]]:
return await list_repo_snapshots()
@router.get("/repo-snapshots/template")
async def api_repo_snapshot_template(
full_name: str,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, str]:
try:
return {"dockerfile": generate_dockerfile_template(normalize_repo_full_name(full_name))}
except RepoSnapshotConfigError as e:
raise HTTPException(500, str(e)) from e
@router.post("/repo-snapshots")
async def api_create_repo_snapshot(
body: RepoSnapshotCreate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
try:
return await create_repo_snapshot(body.full_name, _admin["sub"])
except RepoSnapshotConfigError as e:
raise HTTPException(500, str(e)) from e
@router.get("/repo-snapshots/{full_name:path}")
async def api_get_repo_snapshot(
full_name: str,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
record = await get_repo_snapshot(normalize_repo_full_name(full_name))
if not record:
raise HTTPException(404, "repo snapshot not found")
return record
@router.put("/repo-snapshots/{full_name:path}")
async def api_update_repo_snapshot(
full_name: str,
body: RepoSnapshotUpdate,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
return await update_repo_snapshot(normalize_repo_full_name(full_name), body)
@router.post("/repo-snapshots/{full_name:path}/build")
async def api_build_repo_snapshot(
full_name: str,
background_tasks: BackgroundTasks,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
record = await get_repo_snapshot(full_name)
if not record:
raise HTTPException(404, "repo snapshot not found")
if not (record.get("dockerfile") or "").strip():
raise HTTPException(400, "dockerfile is empty")
if record.get("status") == "building" and not is_repo_snapshot_build_stale(record):
raise HTTPException(409, "a build is already in progress")
record = await mark_repo_snapshot_building(full_name)
background_tasks.add_task(run_snapshot_build, full_name)
return record
@router.delete("/repo-snapshots/{full_name:path}")
async def api_delete_repo_snapshot(
full_name: str,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> Response:
full_name = normalize_repo_full_name(full_name)
record = await get_repo_snapshot(full_name)
if not record:
raise HTTPException(404, "repo snapshot not found")
await delete_repo_snapshot(full_name)
return Response(status_code=204)
@router.get("/admin/user-mappings")
async def admin_list_user_mappings(
page: int = 1,
page_size: int = 20,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
page = max(page, 1)
page_size = max(1, min(page_size, 100))
records = await list_mappings()
total = len(records)
start = (page - 1) * page_size
items = records[start : start + page_size]
return {
"items": items,
"total": total,
"page": page,
"page_size": page_size,
}
class UserMappingUpsert(BaseModel):
github_login: str
work_email: str
slack_user_id: str | None = None
@router.post("/admin/user-mappings")
async def admin_upsert_user_mapping(
body: UserMappingUpsert,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
"""Create or update a GitHub↔work-email mapping from the admin dashboard.
Lets an admin set the ``work_email`` link directly instead of waiting for
the user to self-connect Slack (or doing a raw Store write).
"""
try:
return await upsert_mapping(
github_login=body.github_login,
work_email=body.work_email,
slack_user_id=body.slack_user_id or None,
source="admin",
)
except ValueError as e:
raise HTTPException(400, str(e)) from e
@router.delete("/admin/user-mappings/{github_login}")
async def admin_delete_user_mapping(
github_login: str,
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, bool]:
deleted = await delete_mapping(github_login)
return {"deleted": deleted}
@router.get("/admin/evals/reviewer")
async def admin_get_reviewer_eval(
_admin: dict[str, Any] = _ADMIN_DEP,
) -> dict[str, Any]:
"""Read-only status for the reviewer eval (triggered from the GitHub Action)."""
return await get_reviewer_eval_status()
def _next_link_url(link_header: str | None) -> str | None:
if not link_header:
return None
# GitHub Link header is comma-separated: '<url>; rel="next", <url>; rel="last"'
for part in link_header.split(","):
segments = [s.strip() for s in part.split(";")]
if len(segments) >= 2 and 'rel="next"' in segments[1] and segments[0].startswith("<"):
return segments[0][1:-1]
return None
def _github_api_http_exception(status_code: int) -> HTTPException:
if status_code == 401:
return HTTPException(401, "github token expired, re-login required")
if status_code == 403:
return HTTPException(403, "github API forbidden")
if status_code == 404:
return HTTPException(404, "github API resource not found")
return HTTPException(502, f"github API error ({status_code})")
async def _paginate(
client: httpx.AsyncClient,
url: str,
*,
headers: dict[str, str],
items_key: str | None,
cap: int = 1000,
) -> list[dict[str, Any]]:
"""Follow ``Link: rel="next"`` until exhausted (or cap reached).
``items_key`` is the JSON key holding the list when the endpoint returns
a wrapper object (e.g. ``/user/installations`` returns
``{"total_count": N, "installations": [...]}``). When ``None`` the
response body itself is treated as the list.
"""
out: list[dict[str, Any]] = []
next_url: str | None = url
first = True
while next_url and len(out) < cap:
params = {"per_page": "100"} if first else None
try:
r = await client.get(next_url, headers=headers, params=params)
except httpx.TimeoutException as exc:
logger.warning("GitHub API timed out while paginating %s", next_url)
raise HTTPException(503, "github API request timed out") from exc
except httpx.RequestError as exc:
logger.warning("GitHub API request failed while paginating %s: %s", next_url, exc)
raise HTTPException(502, "github API request failed") from exc
try:
r.raise_for_status()
except httpx.HTTPStatusError as exc:
logger.warning(
"GitHub API returned %s while paginating %s",
r.status_code,
next_url,
)
raise _github_api_http_exception(r.status_code) from exc
body = r.json()
page = body.get(items_key, []) if items_key else body
if isinstance(page, list):
out.extend(page)
next_url = _next_link_url(r.headers.get("Link"))
first = False
return out
async def _fetch_user_installations_and_repos(
login: str,
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""Resolve the installations and repos a user can access via the GitHub App.
Paginates both ``/user/installations`` and per-installation
``/user/installations/{id}/repositories`` so users with multiple
installations or >30 accessible repos get the complete set. Shared by the
``/repos`` endpoint and the reviews access filter.
"""
token = await get_valid_access_token(login)
if not token:
raise HTTPException(401, "github token unavailable, re-login required")
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
}
async with httpx.AsyncClient(timeout=_GITHUB_API_TIMEOUT) as client:
try:
installations = await _paginate(
client,
"https://api.github.com/user/installations",
headers=headers,
items_key="installations",
)
except HTTPException as exc:
if exc.status_code != 401:
raise
token = await get_valid_access_token(login, force_refresh=True)
if not token:
raise HTTPException(401, "github token expired, re-login required") from exc
headers["Authorization"] = f"Bearer {token}"
installations = await _paginate(
client,
"https://api.github.com/user/installations",
headers=headers,
items_key="installations",
)
repositories: list[dict[str, Any]] = []
for inst in installations:
inst_id = inst.get("id")
if inst_id is None:
continue
try:
repos = await _paginate(
client,
f"https://api.github.com/user/installations/{inst_id}/repositories",
headers=headers,
items_key="repositories",
)
except HTTPException as exc:
if exc.status_code in _SKIPPABLE_INSTALLATION_REPO_STATUS_CODES:
logger.warning(
"Skipping installation %s repository list: %s", inst_id, exc.detail
)
continue
raise
repositories.extend(repos)
return installations, repositories
async def accessible_repo_full_names(login: str) -> frozenset[str]:
"""Lowercased ``owner/name`` of repos the user can currently access.
Resolved fresh on every call (a fixed, repo-count-independent burst of
GitHub calls) rather than cached. ``/reviews`` uses this set to decide
which private PR metadata a user may see, so it's an authorization
boundary: a stale set would leak repo/PR titles, branches, authors and
finding counts for repos the user just lost access to.
"""
_, repositories = await _fetch_user_installations_and_repos(login)
return frozenset(
repo["full_name"].lower() for repo in repositories if isinstance(repo.get("full_name"), str)
)
@router.get("/repos")
async def list_repos(
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
"""List repos where open-swe is installed and the user has access."""
installations, repositories = await _fetch_user_installations_and_repos(session["sub"])
return {
"installations": [
{
"id": i.get("id"),
"account": (i.get("account") or {}).get("login"),
"account_type": (i.get("account") or {}).get("type"),
}
for i in installations
],
"repositories": [
{"full_name": r.get("full_name"), "private": r.get("private", False)}
for r in repositories
if r.get("full_name")
],
}
@router.get("/review-styles")
async def api_list_review_styles(
session: dict[str, Any] = _SESSION_DEP,
) -> list[dict[str, Any]]:
records = await _filter_repo_records_for_user(session["sub"], await list_review_styles())
out: list[dict[str, Any]] = []
for record in records:
if record.get("status") == "running":
synced = await sync_review_style_run_status(record["full_name"])
out.append(synced)
else:
out.append(record)
return out
REVIEWS_PAGE_SIZE = 20
@router.get("/reviews")
async def api_list_reviews(
page: int = 0,
mine: bool = True,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
login = session["sub"]
accessible = await accessible_repo_full_names(login)
async def is_accessible(summary: dict[str, Any]) -> bool:
return summary["full_name"].lower() in accessible
page = max(page, 0)
reviews, has_more = await list_reviews(
REVIEWS_PAGE_SIZE,
offset=page * REVIEWS_PAGE_SIZE,
author=login if mine else None,
is_accessible=is_accessible,
)
return {"reviews": reviews, "page": page, "has_more": has_more}
@router.get("/reviews/{owner}/{repo}/{pr_number}")
async def api_get_review(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await get_review(owner, repo, pr_number)
@router.get("/reviews/{owner}/{repo}/{pr_number}/diff")
async def api_get_review_diff(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await get_review_diff(owner, repo, pr_number)
@router.get("/reviews/{owner}/{repo}/{pr_number}/image")
async def api_get_review_image(
owner: str,
repo: str,
pr_number: int,
url: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await proxy_pr_image(owner, repo, pr_number, url)
@router.post("/reviews/{owner}/{repo}/{pr_number}/re-review")
async def api_re_review(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await trigger_re_review(owner, repo, pr_number, session["sub"])
@router.post("/reviews/{owner}/{repo}/{pr_number}/resolve-trace")
async def api_resolve_trace(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await dry_run_trace_resolution(owner, repo, pr_number)
class ReviewCommentCreate(BaseModel):
path: str
line: int
side: Literal["LEFT", "RIGHT"]
body: str
start_line: int | None = None
start_side: Literal["LEFT", "RIGHT"] | None = None
@router.get("/reviews/{owner}/{repo}/{pr_number}/comments")
async def api_list_review_comments(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await list_review_comments(owner, repo, pr_number)
@router.post("/reviews/{owner}/{repo}/{pr_number}/comments")
async def api_create_review_comment(
owner: str,
repo: str,
pr_number: int,
comment: ReviewCommentCreate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
body = comment.body.strip()
if not body:
raise HTTPException(422, "comment body is required")
# Post as the signed-in user (their user-to-server token), so the comment is
# attributed to them rather than the Open SWE app.
token = await get_valid_access_token(session["sub"])
if not token:
raise HTTPException(401, "GitHub re-auth required")
return await create_review_comment(
owner,
repo,
pr_number,
token=token,
path=comment.path,
line=comment.line,
side=comment.side,
body=body,
start_line=comment.start_line,
start_side=comment.start_side,
)
# --- PR chat (sandbox-less ``chat`` graph) -----------------------------------
# The frontend points a LangGraph StreamProvider at the base
# ``/reviews/{owner}/{repo}/{pr_number}/chat``; the SDK then issues the
# ``/threads/{id}/{commands,stream/events,state,history}`` calls proxied below.
@router.get("/reviews/{owner}/{repo}/{pr_number}/chat")
async def api_get_review_chat(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
return await get_review_chat(owner, repo, pr_number, session["sub"])
@router.get("/reviews/{owner}/{repo}/{pr_number}/chat/threads")
async def api_list_review_chat_threads(
owner: str,
repo: str,
pr_number: int,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
threads = await list_review_chat_threads(owner, repo, pr_number, session["sub"])
return {"threads": threads}
@router.delete("/reviews/{owner}/{repo}/{pr_number}/chat/threads/{thread_id}")
async def api_delete_review_chat_thread(
owner: str,
repo: str,
pr_number: int,
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
await delete_review_chat_thread(owner, repo, pr_number, session["sub"], thread_id)
return Response(status_code=204)
@router.post("/reviews/{owner}/{repo}/{pr_number}/chat/threads/{thread_id}/commands")
async def api_review_chat_commands(
owner: str,
repo: str,
pr_number: int,
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
body = await request.body()
status_code, content, media_type = await proxy_review_chat_commands(
owner,
repo,
pr_number,
session["sub"],
thread_id,
body,
content_type=request.headers.get("content-type", "application/json"),
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.post("/reviews/{owner}/{repo}/{pr_number}/chat/threads/{thread_id}/stream/events")
async def api_review_chat_stream_events(
owner: str,
repo: str,
pr_number: int,
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> StreamingResponse:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
body = await request.body()
stream = await proxy_review_chat_stream_events(
owner,
repo,
pr_number,
session["sub"],
thread_id,
body,
content_type=request.headers.get("content-type", "application/json"),
)
return StreamingResponse(
stream,
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
)
@router.get("/reviews/{owner}/{repo}/{pr_number}/chat/threads/{thread_id}/state")
async def api_review_chat_state(
owner: str,
repo: str,
pr_number: int,
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
status_code, content, media_type = await proxy_review_chat_state(
owner, repo, pr_number, session["sub"], thread_id
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.post("/reviews/{owner}/{repo}/{pr_number}/chat/threads/{thread_id}/history")
async def api_review_chat_history(
owner: str,
repo: str,
pr_number: int,
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await require_repo_access_for_user(session["sub"], f"{owner}/{repo}")
body = await request.body()
status_code, content, media_type = await proxy_review_chat_history(
owner,
repo,
pr_number,
session["sub"],
thread_id,
body,
content_type=request.headers.get("content-type", "application/json"),
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.post("/review-styles")
async def api_create_review_style(
body: ReviewStyleCreate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], body.full_name)
return await create_review_style(body.full_name, session["sub"])
@router.get("/review-styles/{full_name:path}")
async def api_get_review_style(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_review_style(full_name)
if not record:
raise HTTPException(404, "review style not found")
if record.get("status") == "running":
record = await sync_review_style_run_status(full_name)
return record
@router.put("/review-styles/{full_name:path}")
async def api_update_review_style_prompt(
full_name: str,
body: ReviewStylePromptUpdate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_review_style(full_name)
if not record:
raise HTTPException(404, "review style not found")
return await set_custom_prompt(full_name, body.custom_prompt)
@router.post("/review-styles/{full_name:path}/analyze")
async def api_analyze_review_style(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
token = await require_repo_access_for_user(session["sub"], full_name)
record = await get_review_style(full_name)
if not record:
record = await create_review_style(full_name, session["sub"])
if record.get("status") == "running":
record = await sync_review_style_run_status(full_name)
if record.get("status") == "running":
raise HTTPException(409, "analysis already running")
return await start_bootstrap_analysis(
full_name,
github_token=token,
created_by=session["sub"],
)
@router.post("/review-styles/{full_name:path}/cancel")
async def api_cancel_review_style(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_review_style(full_name)
if not record:
raise HTTPException(404, "review style not found")
return await cancel_review_style_analysis(full_name)
@router.delete("/review-styles/{full_name:path}")
async def api_delete_review_style(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_review_style(full_name)
if not record:
raise HTTPException(404, "review style not found")
if record.get("status") == "running":
await cancel_review_style_analysis(full_name)
await remove_continual_cron(full_name)
await delete_review_style(full_name)
return Response(status_code=204)
@router.get("/agent-instructions")
async def api_list_agent_instructions(
session: dict[str, Any] = _SESSION_DEP,
) -> list[dict[str, Any]]:
return await _filter_repo_records_for_user(session["sub"], await list_agent_instructions())
@router.post("/agent-instructions")
async def api_create_agent_instructions(
body: AgentInstructionsCreate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
await require_repo_access_for_user(session["sub"], body.full_name)
return await create_agent_instructions(body.full_name, session["sub"])
@router.get("/agent-instructions/{full_name:path}")
async def api_get_agent_instructions(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_agent_instructions(full_name)
if not record:
raise HTTPException(404, "agent instructions not found")
return record
@router.put("/agent-instructions/{full_name:path}")
async def api_update_agent_instructions(
full_name: str,
body: AgentInstructionsUpdate,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
return await set_agent_instructions(full_name, body.instructions)
@router.delete("/agent-instructions/{full_name:path}")
async def api_delete_agent_instructions(
full_name: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
full_name = normalize_repo_full_name(full_name)
await require_repo_access_for_user(session["sub"], full_name)
record = await get_agent_instructions(full_name)
if not record:
raise HTTPException(404, "agent instructions not found")
await delete_agent_instructions(full_name)
return Response(status_code=204)
@router.get("/agent-usage-leaderboard")
async def api_agent_usage_leaderboard(
background_tasks: BackgroundTasks,
period: str | None = "30d",
limit: int = 10,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await list_agent_usage_leaderboard(
period=period,
limit=limit,
current_login=session["sub"],
current_email=session.get("email"),
schedule_usage_refresh=lambda cache_period: background_tasks.add_task(
refresh_usage_leaderboard_cache, cache_period
),
schedule_reviewer_refresh=lambda cache_period: background_tasks.add_task(
refresh_reviewer_stats_cache, cache_period
),
)
@router.get("/schedules")
async def api_list_schedules(
session: dict[str, Any] = _SESSION_DEP,
) -> list[dict[str, Any]]:
return await list_agent_schedules(session["sub"], email=session.get("email"))
@router.post("/schedules")
async def api_create_schedule(
body: ScheduleCreateBody,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await create_agent_schedule(session["sub"], body, email=session.get("email"))
@router.patch("/schedules/{schedule_id}")
async def api_update_schedule(
schedule_id: str,
body: ScheduleUpdateBody,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await update_agent_schedule(
schedule_id, session["sub"], body, email=session.get("email")
)
@router.delete("/schedules/{schedule_id}")
async def api_delete_schedule(
schedule_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await delete_agent_schedule(schedule_id, session["sub"], email=session.get("email"))
return Response(status_code=204)
@router.get("/threads")
async def api_list_threads(
all: bool = False,
session: dict[str, Any] = _SESSION_DEP,
) -> list[dict[str, Any]]:
if all and not _session_is_admin(session):
raise HTTPException(403, "admin only")
return await list_dashboard_threads(session["sub"], email=session.get("email"), include_all=all)
@router.get("/threads/sidebar")
async def api_list_threads_sidebar(
active_limit: int = 50,
resolved_limit: int = 20,
all: bool = False,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
if all and not _session_is_admin(session):
raise HTTPException(403, "admin only")
return await list_dashboard_threads_sidebar(
session["sub"],
email=session.get("email"),
active_limit=active_limit,
resolved_limit=resolved_limit,
include_all=all,
)
@router.get("/threads/page")
async def api_list_threads_page(
limit: int = 25,
offset: int = 0,
all: bool = False,
resolved: bool | None = None,
viewed: bool | None = None,
source: str | None = None,
status: str | None = None,
q: str | None = None,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
if all and not _session_is_admin(session):
raise HTTPException(403, "admin only")
return await list_dashboard_threads_page(
session["sub"],
email=session.get("email"),
limit=limit,
offset=offset,
include_all=all,
resolved=resolved,
viewed=viewed,
source=source,
status=status,
query=q,
)
@router.get("/threads/{thread_id}")
async def api_get_thread(
thread_id: str,
mark_viewed: bool = True,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await get_dashboard_thread(
thread_id,
session["sub"],
email=session.get("email"),
mark_viewed=mark_viewed,
)
@router.get("/threads/{thread_id}/recovery.patch")
async def api_get_thread_recovery_patch(
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
content, filename = await get_dashboard_thread_recovery_patch(
thread_id,
session["sub"],
email=session.get("email"),
)
return Response(
content=content,
media_type="text/x-diff",
headers={"Content-Disposition": f'attachment; filename="{filename}"'},
)
@router.get("/threads/{thread_id}/pr-diff")
async def api_get_thread_pr_diff(
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await get_dashboard_thread_pr_diff(
thread_id,
session["sub"],
email=session.get("email"),
)
@router.post("/threads/{thread_id}/messages")
async def api_send_thread_message(
thread_id: str,
body: ThreadMessageBody,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await send_dashboard_message(thread_id, session["sub"], body, email=session.get("email"))
@router.post("/threads/{thread_id}/resolve")
async def api_resolve_thread(
thread_id: str,
body: ThreadResolveBody,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await resolve_dashboard_thread(
thread_id,
session["sub"],
resolved=body.resolved,
email=session.get("email"),
)
@router.post("/threads/{thread_id}/runs/{run_id}/cancel")
async def api_cancel_thread_run(
thread_id: str,
run_id: str,
session: dict[str, Any] = _SESSION_DEP,
wait: str = "0",
action: str = "interrupt",
) -> Response:
status_code, content, media_type = await proxy_dashboard_thread_run_cancel(
thread_id,
run_id,
session["sub"],
wait=wait,
action=action,
email=session.get("email"),
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.post("/threads/{thread_id}/cancel")
async def api_cancel_thread(
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await cancel_dashboard_thread(thread_id, session["sub"], email=session.get("email"))
@router.delete("/threads/{thread_id}")
async def api_delete_thread(
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
await delete_dashboard_thread(thread_id, session["sub"], email=session.get("email"))
return Response(status_code=204)
@router.get("/threads/{thread_id}/state")
async def api_get_thread_state(
thread_id: str,
session: dict[str, Any] = _SESSION_DEP,
) -> dict[str, Any]:
return await get_dashboard_thread_state(thread_id, session["sub"], email=session.get("email"))
@router.post("/threads/{thread_id}/stream/events")
async def api_thread_stream_events(
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> StreamingResponse:
body = await request.body()
stream = await proxy_dashboard_thread_stream_events(
thread_id,
session["sub"],
body,
email=session.get("email"),
content_type=request.headers.get("content-type", "application/json"),
)
return StreamingResponse(
stream,
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
)
@router.post("/threads/{thread_id}/commands")
async def api_thread_commands(
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
body = await request.body()
status_code, content, media_type = await proxy_dashboard_thread_commands(
thread_id,
session["sub"],
body,
email=session.get("email"),
content_type=request.headers.get("content-type", "application/json"),
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.post("/threads/{thread_id}/history")
async def api_thread_history(
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> Response:
body = await request.body()
status_code, content, media_type = await proxy_dashboard_thread_history(
thread_id,
session["sub"],
body,
email=session.get("email"),
content_type=request.headers.get("content-type", "application/json"),
)
return Response(content=content, status_code=status_code, media_type=media_type)
@router.get("/threads/{thread_id}/stream")
async def api_stream_thread(
thread_id: str,
request: Request,
session: dict[str, Any] = _SESSION_DEP,
) -> StreamingResponse:
last_event_id = request.headers.get("last-event-id")
async def event_generator():
async for chunk in stream_dashboard_thread(
thread_id, session["sub"], email=session.get("email"), last_event_id=last_event_id
):
yield chunk
return StreamingResponse(
event_generator(),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
)