Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 45 additions & 9 deletions apps/api/src/opendirector_api/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from dataclasses import dataclass, replace
import json
import logging
from os import fstat
from os.path import join, normpath
from pathlib import Path
import threading
import time
Expand All @@ -12,8 +14,8 @@
from uuid import UUID, uuid4, uuid5

from anyio import CancelScope
from fastapi import APIRouter, Header
from fastapi.responses import FileResponse, JSONResponse, StreamingResponse
from fastapi import APIRouter, Header, Query
from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse
from pydantic import BaseModel, ConfigDict, Field, JsonValue

from opendirector.agent.catalog import model_choices
Expand All @@ -35,6 +37,7 @@


Runtime = RuntimeId
TRACE_CHUNK_BYTES = 512 * 1024

def _assistant_request(config):
"""Admission uses the same output ceiling as the configured model gateway."""
Expand Down Expand Up @@ -486,11 +489,13 @@ def agent_routes(projects, generation, configs, provider=None, *, active=None) -
conversations = Conversations(projects)
runtimes = AgentRuntimes(projects, generation, configs, provider)

def running_turn(project_id: UUID) -> UUID | None:
running = active.get(project_id)
return running.turn if running is not None and running.task is not None and not running.task.done() else None

@router.get('/conversations/{conversation_id}/trace')
def conversation_trace(project_id: UUID, conversation_id: UUID):
running = active.get(project_id)
live = running.turn if running is not None and running.task is not None and not running.task.done() else None
return conversations.trace(project_id, conversation_id, live)
return conversations.trace(project_id, conversation_id, running_turn(project_id))

@router.get('/traces/{turn_id}/conversation')
def trace_conversation(project_id: UUID, turn_id: UUID):
Expand All @@ -509,12 +514,43 @@ def trace_input(project_id: UUID, turn_id: UUID):

@router.get('/traces/{turn_id}/{source}')
def trace(project_id: UUID, turn_id: UUID,
source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'model']):
source: Literal['opencode', 'codex', 'claude', 'jiuwenswarm', 'deepseek', 'pi', 'model'],
cursor: Annotated[str | None, Query(pattern=r'^(?:[0-9]+:[0-9]+:[0-9]+)?$', max_length=64)] = None):
folder = child(conversations.path(project_id), 'agent-runs')
file = child(folder, f'{turn_id}.{source}.jsonl')
if not file.is_file():
filename = normpath(join(folder, f'{turn_id}.{source}.jsonl'))
if not filename.startswith(join(folder, '')):
raise ProjectError('轨迹文件不存在。', 404)
return FileResponse(file, media_type='text/plain', headers={'Cache-Control': 'no-store'})
file = Path(filename)
if file.is_symlink():
raise ProjectError('项目内部文件不能是符号链接。', 409)
headers = {'Cache-Control': 'no-store'}
if cursor is None:
if not file.is_file():
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
raise ProjectError('轨迹文件不存在。', 404)
return FileResponse(file, media_type='text/plain', headers=headers)
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed

# Sample liveness before reading. If a turn finishes during this read,
# the client will still check again and receive every final byte.
headers['X-Trace-Running'] = '1' if running_turn(project_id) == turn_id else '0'
if not file.is_file():
return Response(status_code=404, headers=headers)
try:
with file.open('rb') as stream:
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
stat = fstat(stream.fileno())
identity = f'{stat.st_dev}:{stat.st_ino}'
previous, _, position = cursor.rpartition(':')
offset = int(position) if position else 0
if cursor and (previous != identity or offset > stat.st_size):
headers['X-Trace-Reset'] = '1'
offset = 0
stream.seek(offset)
data = stream.read(min(TRACE_CHUNK_BYTES, stat.st_size - offset))
except FileNotFoundError:
return Response(status_code=404, headers=headers)
next_offset = offset + len(data)
headers['X-Trace-Cursor'] = f'{identity}:{next_offset}'
headers['X-Trace-More'] = '1' if next_offset < stat.st_size else '0'
return Response(content=data, media_type='text/plain', headers=headers)

@router.get('/turns/{turn_id}/jobs')
def turn_jobs(project_id: UUID, turn_id: UUID):
Expand Down
8 changes: 6 additions & 2 deletions docs/architecture/agent-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,12 @@ CLI 通过环境变量中的本轮本地 Socket 地址连接业务网关,不

English summary: the trace page lists every executed turn of a conversation, expanded one at a time, and reads a turn's logs and linked Jobs only when it is opened; the user-triggered original trace download is the one exception (below). The turn index comes from the read-only `GET .../assistant/conversations/{conversation_id}/trace`, which resolves current, archived and aliased (`reusedCreateIds`) conversation ids and returns metadata only (number, input summary, runtime, status). It never reads log bodies, activates a conversation or takes a lease. A turn is a user message paired with the assistant message whose id is `uuid5(user id, 'assistant')`, so queued or never executed user messages are not listed. Each turn uses its own recorded runtime for the log source and parser, and raw model requests are offered for the Default (opencode) runtime only. `GET .../traces/{turn_id}/conversation` lets old single-turn links find their conversation; when none is found the single-turn page remains.

轨迹浏览使用 `GET .../traces/{turn_id}/{source}?cursor=…` 按字节读取追加日志。空游标从头开始,之后使用响应返回的游标;每个响应最多读取 512 KiB。浏览器跨响应保留未完成的 UTF-8 和 JSONL 记录,并增量合并同一消息或工具调用。回合结束后,浏览器读完剩余字节即停止轮询。无游标的同一路径继续提供原始文件。

The trace viewer reads append-only log bytes from `GET .../traces/{turn_id}/{source}?cursor=…`. An empty cursor starts at the beginning, and each response returns the next cursor and at most 512 KiB. The browser carries incomplete UTF-8 and JSONL records across responses and merges updates to the same message or tool call. It stops polling after the turn ends and the remaining bytes have been read. The same route serves the original file when the cursor is omitted.

### 原始轨迹归档 / Original trace archive

“下载原始轨迹”由前端完成,不新增或修改后端接口,复用 `src/canvas/zipArchive.ts` 的 `createZip()`(`compress: false`,保留原始字节)与 `downloadFile()`。流程:先重新请求 `GET .../conversations/{conversation_id}/trace`,任何轮次为 `streaming` 即拒绝;随后对每轮按其运行时逐个请求 `GET .../traces/{turn_id}/{source}`(404 记为 `missing`,其他非 2xx、超时、响应提前结束、超限一律失败),读完后再次校验轮次状态,不一致则失败。任何失败都不产出 ZIP。因此归档是逐来源读取的结果,不是跨文件原子快照,`manifest.json` 的 `snapshot` 字段如实说明。容量上限为 64 MiB,含每个条目的本地头、中央目录项、结束记录和 manifest,没有单文件上限,超限时错误指出轮次与来源。每个请求和整个导出都有超时,用户可取消,读取流在失败、超限、取消时被取消并释放。内容不脱敏,`model.jsonl` 原样包含;`manifest.json` 区分 Job 为空(`jobs: []`)与查询失败(`jobs: null`、`jobsStatus: "unavailable"`)。
“下载原始轨迹”由前端读取原始文件并生成,复用 `src/canvas/zipArchive.ts` 的 `createZip()`(`compress: false`,保留原始字节)与 `downloadFile()`。流程:先重新请求 `GET .../conversations/{conversation_id}/trace`,任何轮次为 `streaming` 即拒绝;随后对每轮按其运行时逐个请求 `GET .../traces/{turn_id}/{source}`(404 记为 `missing`,其他非 2xx、超时、响应提前结束、超限一律失败),读完后再次校验轮次状态,不一致则失败。任何失败都不产出 ZIP。因此归档是逐来源读取的结果,不是跨文件原子快照,`manifest.json` 的 `snapshot` 字段如实说明。容量上限为 64 MiB,含每个条目的本地头、中央目录项、结束记录和 manifest,没有单文件上限,超限时错误指出轮次与来源。每个请求和整个导出都有超时,用户可取消,读取流在失败、超限、取消时被取消并释放。内容不脱敏,`model.jsonl` 原样包含;`manifest.json` 区分 Job 为空(`jobs: []`)与查询失败(`jobs: null`、`jobsStatus: "unavailable"`)。

English summary: the download is built in the frontend with no backend change, reusing `createZip()` (`compress: false`, original bytes) and `downloadFile()`. It re-fetches the conversation trace index and refuses when any turn is `streaming`, reads each source sequentially (404 becomes `missing`; any other non-2xx, timeout, early end or cap overrun fails), then re-checks turn status and fails on any difference. No failure produces a ZIP, and the archive is explicitly a per-source read, not an atomic snapshot across files (`manifest.json` says so). The 64 MiB cap covers raw bytes plus ZIP headers, central directory, end record and manifest; there is no per-file cap, and an overrun names the turn and source. Requests and the whole export are time-bounded, the user can cancel, and streams are cancelled and released on failure, overrun or cancel. Content is not redacted (`model.jsonl` included). The manifest separates no linked Jobs (`jobs: []`) from a failed lookup (`jobs: null`, `jobsStatus: "unavailable"`).
English summary: the download reads original files and builds the archive in the frontend, reusing `createZip()` (`compress: false`, original bytes) and `downloadFile()`. It re-fetches the conversation trace index and refuses when any turn is `streaming`, reads each source sequentially (404 becomes `missing`; any other non-2xx, timeout, early end or cap overrun fails), then re-checks turn status and fails on any difference. No failure produces a ZIP, and the archive is explicitly a per-source read, not an atomic snapshot across files (`manifest.json` says so). The 64 MiB cap covers raw bytes plus ZIP headers, central directory, end record and manifest; there is no per-file cap, and an overrun names the turn and source. Requests and the whole export are time-bounded, the user can cancel, and streams are cancelled and released on failure, overrun or cancel. Content is not redacted (`model.jsonl` included). The manifest separates no linked Jobs (`jobs: []`) from a failed lookup (`jobs: null`, `jobsStatus: "unavailable"`).
1 change: 1 addition & 0 deletions docs/development/lessons.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u
- **Check:** As relevant to the change, inspect persisted object identities, references, and execution inputs after conversion or recovery. Reopen the project or reconnect to the run when needed, and verify the actual result.
- **Preview follow-up:** [PR #465](https://github.com/ThinkFlowLab/OpenDirector/pull/465) initially opened the project for a prompt rewrite, which could contend with the browser's edit lease. A rewrite reads the saved snapshot and has no durable job to recover. Verify it can finish under a separate session and that a browser disconnect closes the server-side request.
- **Async projection follow-up:** PR #193's structured-editor CI failure prompted a real-browser delayed-read regression. An older background projection could finish after an acknowledged editor save and restore an obsolete CAS basis, making the next save/publication fail. Recheck the editor transaction and captured snapshot at completion before installing either changed or apparently identical content. Keep publication versions fixed, test the actual save/retry/provenance path with a deterministic interleaving, and retain the original CI failure rather than treating a longer timeout or a rerun as its explanation.
- **Publication lock follow-up:** [#562](https://github.com/ThinkFlowLab/OpenDirector/pull/562) exposed task polling failing during publication. [#539](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/46222060697/job/141218914874) exposed the same contention in upload staging before a timeline save. While a same-project publication is paused after journaling, exercise task reads and upload staging through HTTP. Staging uses its own handle lock and still validates the edit lease. Asset registration and timeline saves continue to use the project write rules. / **发布锁补充:** 在同一工程写入日志后暂停发布,经 HTTP 检查工具任务读取与素材暂存。暂存使用独立的句柄锁并验证编辑租约,素材登记和时间线保存仍走工程写入规则。
- **Media representation follow-up:** [Issue #282](https://github.com/ThinkFlowLab/OpenDirector/issues/282) exposed copy/export paths that read displayed pixels and archive imports that displayed unsupported original bytes. A browser preview and an original asset need distinct read paths while retaining the same asset identity. Verify original bytes through download, fresh publication, cross-project paste fallback and archive round trips, including the first display after import. [PR #287 review](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5857373679) also exposed missing MIME-extension mappings and a fallback that could name preview PNG bytes as HEIC. Carry the expected original type into readers, reject a missing original, and check timeline/FCPXML packages as well as canvas archives.

- **Upload acknowledgement follow-up:** Investigating [PR #287's camera sample](https://github.com/ThinkFlowLab/OpenDirector/pull/287#pullrequestreview-5868923062) reproduced a failed preview being swallowed into a successfully saved empty generation item. Require a usable preview before completing a HEIF import, and assert the failure leaves the original registered without creating an empty item. Slow uploads also crossed the first save acknowledgement: default expansion and model display labels were mistaken for user edits. Compare effective settings while retaining actual content, model, frame-selection and lock conflicts; exercise upload into a newly created node and its reference composer before the first save finishes.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,10 @@ def lock(self, project_id, handle):

def _scope(self, db, project_id, session, trusted=False):
self.projects._recover()
path, manifest = self.projects._find(db, project_id)
# Staging writes to a separately locked upload handle. The catalog
# transaction protects project moves and the lease, while a live
# publication can leave us on the last complete manifest.
path, manifest = self.projects._find(None, project_id)
if not trusted:
self.projects._lease(db, project_id, path, session)
return self.projects._current(db, project_id, path, manifest).snapshot
Expand Down
Loading
Loading