Skip to content

Commit af4108f

Browse files
roberttwangclaude
andcommitted
Merge main 832e2be into codex/sop-conversation-review
Resolve conflicts with #1301 (artifact streaming): - internal/httpapi/runs.go: stream the artifact body from OpenArtifactContent with charset only for text/*, keep this branch's CSP sandbox header and RFC 2231 Content-Disposition via runArtifactFilename (artifact name + source extension). Main's artifactFileName test now exercises runArtifactFilename; every main case keeps the same expected file name. - chatbot/src/RichContent.jsx: keep this branch's loaded-state preview and add main's 5 MiB oversized guard and binary detection. Co-Authored-By: Claude Code <noreply@anthropic.com>
2 parents afa8604 + 832e2be commit af4108f

110 files changed

Lines changed: 4469 additions & 533 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎chatbot/src/RichContent.jsx‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -538,6 +538,15 @@ export function Attachment({ attachment, sessionId, onOpen }) {
538538
</>
539539
);
540540
}
541+
// Larger files are offered for download instead of being read into the page.
542+
const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
543+
// Deliverables without a declared type are stored as Markdown, so the body
544+
// decides: NUL bytes or a mostly undecodable start mean binary content.
545+
function looksBinary(content) {
546+
if (content.includes("\u0000")) return true;
547+
const head = content.slice(0, 65536);
548+
return (head.match(/\uFFFD/g) || []).length > head.length * 0.1;
549+
}
541550
export function ArtifactPreview({ artifact }) {
542551
const [loaded, setLoaded] = useState(null);
543552
const [sourceView, setSourceView] = useState(false);
@@ -555,6 +564,7 @@ export function ArtifactPreview({ artifact }) {
555564
/^(text\/|application\/(json|javascript|xml)|image\/svg\+xml)/i.test(
556565
artifact.mimeType,
557566
);
567+
const oversized = Boolean(url) && (artifact?.size || 0) > PREVIEW_MAX_BYTES;
558568
// An attached HTML file (e.g. a demo from the workspace) previews in the same
559569
// script-only sandbox as an html code block.
560570
const kind =
@@ -582,7 +592,7 @@ export function ArtifactPreview({ artifact }) {
582592
} catch {
583593
finish("", "文件读取失败");
584594
}
585-
} else if (url && readable) {
595+
} else if (url && readable && !oversized) {
586596
fetch(url)
587597
.then((r) => {
588598
if (!r.ok) throw Error("文件读取失败");
@@ -597,11 +607,13 @@ export function ArtifactPreview({ artifact }) {
597607
return () => {
598608
active = false;
599609
};
600-
}, [id, url, localDataUrl, readable]);
610+
}, [id, url, localDataUrl, readable, oversized]);
601611
if (!artifact) return null;
602612
const source =
603613
(url ? current?.text : (artifact.content ?? current?.text)) ?? "";
604-
const hasSource = typeof source === "string" && source.length > 0 && !error;
614+
const binary = Boolean(url) && looksBinary(current?.text || "");
615+
const hasSource =
616+
typeof source === "string" && source.length > 0 && !error && !binary;
605617
const isMarkdown =
606618
artifact.mimeType?.startsWith("text/markdown") ||
607619
["markdown", "md"].includes(artifact.language?.toLowerCase()) ||
@@ -715,10 +727,14 @@ export function ArtifactPreview({ artifact }) {
715727
src={artifact.url}
716728
alt={artifact.name}
717729
/>
730+
) : oversized ? (
731+
<p className="muted">文件较大,不在页面内预览,可通过右上角下载查看。</p>
718732
) : (url || localDataUrl) && readable && !current ? (
719733
<p className="muted" role="status">
720734
正在读取文件…
721735
</p>
736+
) : binary ? (
737+
<p className="muted">此类型文件可通过右上角下载查看。</p>
722738
) : !hasSource && readable ? (
723739
<p className="muted">文件为空</p>
724740
) : artifact.kind === "svg" ? (

‎chatbot/tests/components.test.jsx‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,51 @@ describe("content and panels", () => {
216216
globalThis.fetch = originalFetch;
217217
});
218218

219+
test("offers oversized text artifacts for download instead of loading them", async () => {
220+
const originalFetch = globalThis.fetch;
221+
globalThis.fetch = vi.fn(async () => ({ ok: true, text: async () => "body" }));
222+
render(
223+
<>
224+
<ArtifactPreview artifact={{
225+
id: "big",
226+
name: "big.log",
227+
mimeType: "text/plain",
228+
url: "/big.log",
229+
size: 6 * 1024 * 1024,
230+
}} />
231+
<ArtifactPreview artifact={{
232+
id: "small",
233+
name: "small.log",
234+
mimeType: "text/plain",
235+
url: "/small.log",
236+
size: 1024,
237+
}} />
238+
</>,
239+
);
240+
expect(await screen.findByText("body")).toBeInTheDocument();
241+
expect(screen.getByText("文件较大,不在页面内预览,可通过右上角下载查看。")).toBeInTheDocument();
242+
expect(globalThis.fetch).toHaveBeenCalledTimes(1);
243+
expect(globalThis.fetch).toHaveBeenCalledWith("/small.log");
244+
globalThis.fetch = originalFetch;
245+
});
246+
247+
test("offers binary content declared as Markdown for download", async () => {
248+
const originalFetch = globalThis.fetch;
249+
globalThis.fetch = vi.fn(async () => ({ ok: true, text: async () => "PK\u0003\u0004\u0000\u0000garbage" }));
250+
render(
251+
<ArtifactPreview artifact={{
252+
id: "zip",
253+
name: "pkg.zip",
254+
mimeType: "text/markdown",
255+
url: "/pkg.zip",
256+
size: 2048,
257+
}} />,
258+
);
259+
expect(await screen.findByText("此类型文件可通过右上角下载查看。")).toBeInTheDocument();
260+
expect(screen.queryByText(/garbage/)).not.toBeInTheDocument();
261+
globalThis.fetch = originalFetch;
262+
});
263+
219264
test("previews an attached HTML file in the script-only sandbox", async () => {
220265
const user = userEvent.setup();
221266
const originalFetch = globalThis.fetch;

‎cmd/agentflow/main.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ func main() {
218218
readyStatus := "serving"
219219
switch role {
220220
case "worker":
221-
httpapi.ConfigureWorkerSOPSandboxSelection(s, e)
221+
httpapi.ConfigureWorkerSOPHelpers(s, e)
222222
e.ConfigureControl(engine.ControlConfig{Role: role, URL: endpoints.ControlURL, Token: endpoints.ControlToken, APIURL: endpoints.APIBase})
223223
e.StartInstanceHeartbeat(claimCtx)
224224
srv = &http.Server{Addr: endpoints.ListenAddr, Handler: workerHandler(e), ReadHeaderTimeout: 10 * time.Second}

‎compose.yaml‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,25 @@ services:
1717
interval: 2s
1818
timeout: 3s
1919
retries: 60
20+
artifact-migration:
21+
profiles: [platform]
22+
# Upgrade existing volumes before the platform starts. Fresh schemas are created by the platform.
23+
image: mysql:8.4
24+
entrypoint: ["sh", "-ec"]
25+
command:
26+
- exec mysql -h mysql -u loopforge loopforge < /migrations/042_run_artifacts_content_mediumtext.sql
27+
environment:
28+
MYSQL_PWD: ${LOOPFORGE_DB_PASSWORD:?Run scripts/configure.sh first}
29+
volumes:
30+
- type: bind
31+
source: ./migrations/042_run_artifacts_content_mediumtext.sql
32+
target: /migrations/042_run_artifacts_content_mediumtext.sql
33+
read_only: true
34+
bind:
35+
create_host_path: false
36+
depends_on:
37+
mysql:
38+
condition: service_healthy
2039
platform:
2140
profiles: [platform]
2241
# Published release stack: never builds. Bump the pinned tag (here and in
@@ -76,6 +95,8 @@ services:
7695
depends_on:
7796
mysql:
7897
condition: service_healthy
98+
artifact-migration:
99+
condition: service_completed_successfully
79100
healthcheck:
80101
test: ["CMD", "python3", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/api/health', timeout=2).close()"]
81102
interval: 3s

‎design.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -338,9 +338,10 @@ Logo 默认 64px,小屏或短屏为 52px;标题为 36px,小屏为 30px。
338338

339339
## 执行机器
340340

341-
- `#runnersList` 首张卡展示「平台执行机器(云端)」,沿用执行机器卡片、Harness `monitor` 图标和在线状态。平台卡包含「平台自带」标签、运行负载、并发上限和项目默认操作。平台管理员可编辑上限,其他成员看到只读上限。CLI、检查更新、共享项目和移除操作属于可绑定机器。
342-
- 项目可写成员可在「可用机器」标题旁切换「自动分配」。按钮使用 `aria-pressed` 表达状态,状态行显示在线可用机器数。开启后,新建的顶层项目 SOP 可分配至兼容的共享机器或平台执行机器。项目默认选为平台时,卡片展示「此项目默认」。两种设置下新对话默认使用云端,仍可在会话草稿选择共享机器。
343-
- 卡片显示「运行中 X · 已占 Y / Z」。上限为 0 时显示「运行中 X · 不限」。有固定排队或已配置云端池时显示对应数量。平台默认上限为 10 条,所有项目共用。失败、暂停或待确认的 SOP 空闲 1 小时后归档工作区并释放名额。
341+
- `接入新机器`下方独立展示`平台机器`分区(`#platformRunnerSection` / `#platformRunnerHost`),以整行横条卡片展示「平台执行机器(云端)」,使用 Harness `server` 图标、在线状态、「平台自带」标签、运行负载、并发上限与「设为项目默认 / 清除项目默认」操作;平台管理员可编辑上限,其他成员看到只读上限。
342+
- `可用机器`(`#runnersList`)与 `#runnerCount` 仅列出并统计已绑定或共享的执行机器,底部操作栏对齐到卡片底部;CLI、检查更新、共享项目和移除操作属于可绑定机器。
343+
- 项目可写成员可在「可用机器」标题旁切换「自动分配」。按钮使用 `aria-pressed` 表达状态,状态行显示在线可用机器数。开启后,新建的顶层项目 SOP 可分配至兼容的共享机器或平台执行机器。项目默认选为平台时,平台横条展示「此项目默认」。两种设置下新对话默认使用云端,仍可在会话草稿选择共享机器。
344+
- 卡片与平台横条显示「运行中 X · 已占 Y / Z」。上限为 0 时显示「运行中 X · 不限」。有固定排队或已配置云端池时显示对应数量。平台默认上限为 10 条,所有项目共用。失败、暂停或待确认的 SOP 空闲 1 小时后归档工作区并释放名额。
344345

345346
## 运行记录列表
346347

‎docs/api/collaboration.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ curl -u "$AGENTFLOW_USER:$AGENTFLOW_PASS" -X POST \
6666
"$AGENTFLOW_URL/api/repositories"
6767
```
6868

69+
可用 `workBranchNaming` 设置 SOP 自动新建工作分支的命名方式。更新时省略该字段会保留已保存的配置,新仓库缺省使用 `feature/`。
70+
71+
- `{"mode":"prefix","prefix":"feat/"}` 为原有分支名主体加上指定前缀。`prefix` 留空时直接使用分支名主体。
72+
- `{"mode":"ai","executorId":"codebuddy","model":"hy4std","prompt":"用小写英文概括改动,带上需求编号"}` 使用指定的 CLI 和模型生成完整分支名。`executorId` 和 `model` 必填,`prompt` 可留空。调用使用 SOP 责任人的凭据或已授权执行机器的登录。平台能访问远端仓库时,会在遇到同名分支后按原命名要求重新生成。节点重试沿用已保存的分支名。
73+
6974
### `DELETE /api/repositories?id={id}`
7075

7176
`id` 必填。成功删除仓库,并清除引用它的项目默认仓库设置,返回 `200 {"status":"deleted"}`;缺少 `id` 或存储错误为 `400`。

‎docs/api/openapi.yaml‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5137,6 +5137,8 @@ components:
51375137
type: string
51385138
integrateBranch:
51395139
type: string
5140+
workBranchNaming:
5141+
$ref: "#/components/schemas/WorkBranchNaming"
51405142
createdAt:
51415143
type: string
51425144
format: date-time
@@ -5145,6 +5147,30 @@ components:
51455147
type: string
51465148
format: date-time
51475149
readOnly: true
5150+
WorkBranchNaming:
5151+
type: object
5152+
description: Naming settings for newly created SOP work branches. Repositories without settings use the feature/ prefix.
5153+
required: [mode]
5154+
properties:
5155+
mode:
5156+
type: string
5157+
enum: [prefix, ai]
5158+
prefix:
5159+
type: string
5160+
description: Literal prefix in prefix mode. An empty or omitted prefix within this mode produces a name without a prefix.
5161+
example: feat/
5162+
executorId:
5163+
type: string
5164+
description: Built-in CLI executor ID. Required in AI mode.
5165+
example: codebuddy
5166+
model:
5167+
type: string
5168+
description: Concrete model ID. Required in AI mode.
5169+
example: hy4std
5170+
prompt:
5171+
type: string
5172+
maxLength: 2000
5173+
description: Optional repository naming instructions for AI mode.
51485174
IssueListPage:
51495175
type: object
51505176
required: [items, total, offset, limit, hasMore]

‎docs/deployment.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,12 @@ The upstream process roles remain `-role api`, `-role worker` and `-role all`. A
242242

243243
Personal runners are connected from the execution-machine page with a short-lived binding code. The installer is served at `/runners/install.sh`. `AGENTFLOW_RUNNER_BINARY` can point to binaries with `{os}` and `{arch}` substitutions. Container images bundle Linux/macOS amd64/arm64 runner and gate binaries. Native source installations can build on demand with Go.
244244

245+
SOP deliverables support up to 20 MiB per file. Runner 0.13.0 and later transfer
246+
declared files separately from the task completion report, so several files
247+
can be handed off together. Installations with automatic Runner updates
248+
enabled receive the bundled version after the platform release. Older Runners
249+
keep their 1 MiB inline upload limit until they update.
250+
245251
The machine owner can use **Settings → Execution machines → Shared projects** to grant access to one or more projects where they are the owner or a member with write access. Members with write access can select a compatible shared machine for a new conversation. **Use in this project** sets a default for that user and project. Each new turn on a shared machine requires a current grant and project write access for both the machine owner and the sender. Removing a grant clears the saved project defaults that pointed to the machine.
246252

247253
Docker workspaces on macOS use a Linux Runner executable for Git credentials and MCP calls. The installer chooses the architecture of the installed macOS Runner, including Intel binaries running under Rosetta. For a universal Runner on Apple Silicon it installs the arm64 helpers and adds the amd64 helpers when available. Foreground starts and the command printed by `--no-start` select the native arm64 slice, including from a Rosetta shell. On Intel Macs the installer installs the amd64 helpers. By default, it places the helpers next to the host binary. A Runner-side `AGENTFLOW_RUNNER_BINARY` template with `{os}` selects the installation and runtime path. To install both helpers, use `{arch}` and give each architecture a distinct destination. The installer saves the template for upgrades and includes it in launchd and in the startup command printed by `--no-start`. Helper paths must resolve to files separate from the macOS Runner.
@@ -275,6 +281,17 @@ For an external MySQL deployment, review that migration and check column existen
275281
| Required manual upgrade migrations | `009_bot_interactions_utf8mb4.sql`, `036_git_http_credentials.sql` | Follow each migration's timing and prerequisites. [Migrating existing GitHub credentials](#migrating-existing-github-credentials) |
276282
| Optional backfills and rewrites of existing rows | `016_public_optional_repositories.sql`, `021_assistant_session_sources.sql` | Run them if the installation needs the converted rows |
277283

284+
Compose runs `migrations/042_run_artifacts_content_mediumtext.sql` before the
285+
platform starts, including during `./start.sh pull`. The native development
286+
script runs the same migration against its Compose database. It widens an existing
287+
`run_artifacts.content` column from `TEXT` to `MEDIUMTEXT` for inline artifacts
288+
and preserves existing data, character set, collation and nullability. Larger
289+
files use separate chunk tables added at platform startup.
290+
For a deployment using an external MySQL server and no Compose startup, run this
291+
SQL file in the deployment's database upgrade step before starting the new binary.
292+
If the Compose migration fails, review `docker compose --profile platform logs
293+
artifact-migration`, resolve the database error and rerun the upgrade.
294+
278295
### Migrating existing sandboxes to inline assets
279296

280297
For a published Compose release, check out the target release and run `./start.sh pull`. If other API or worker processes share the Compose database, stop them first. After pulling the images, the command checks that the target image supports inline Dockerfiles and that the database still has a legacy asset table. When both conditions hold, it stops the platform, saves a database dump in `.local/loopforge-before-041.*/loopforge.sql`, and runs 041 before starting the new platform. An empty database or one whose legacy tables are already gone skips 041.

‎e2e/api/20-issues.test.mjs‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import { test, before, after } from 'node:test';
55
import assert from 'node:assert/strict';
66
import { api, get, post, put, list, track, cleanup, ensureProject, waitFor, waitRun } from '../lib/api.mjs';
7-
import { cfg } from '../lib/env.mjs';
7+
import { cfg, requireToken } from '../lib/env.mjs';
88
import { createWorkflow, script, approval, trackRun } from '../lib/fixtures.mjs';
99

1010
const P = cfg.projectId;
@@ -52,6 +52,33 @@ test('list supports project filter, search and pagination', async () => {
5252

5353
const detailOf = async id => get(`/api/issues/${id}`);
5454

55+
test('creates a Markdown requirement and serves its attached image to authenticated users', async () => {
56+
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGPQc/8PAAIbAXVXkdKiAAAAAElFTkSuQmCC', 'base64');
57+
const description = '## Reproduction\n\nSee the **attached image**.';
58+
const form = new FormData();
59+
form.set('issue', JSON.stringify({ projectId: P, kind: 'requirement', title: `E2E requirement image ${cfg.runTag}`, description }));
60+
form.append('images', new Blob([png], { type: 'image/png' }), 'reproduction.png');
61+
62+
const created = await post('/api/issues', form);
63+
removeLater(created.id);
64+
const detail = await detailOf(created.id);
65+
assert.equal(detail.issue.description, description);
66+
assert.equal(detail.images.length, 1);
67+
const [image] = detail.images;
68+
assert.ok(image.id);
69+
assert.equal(image.name, 'reproduction.png');
70+
71+
const path = `/api/issues/${created.id}/images/${image.id}`;
72+
await get(path, { auth: false, expect: 401 });
73+
const response = await fetch(cfg.base + path, {
74+
headers: { Authorization: `Bearer ${requireToken()}` },
75+
signal: AbortSignal.timeout(15_000),
76+
});
77+
assert.equal(response.status, 200);
78+
assert.equal(response.headers.get('content-type'), 'image/png');
79+
assert.deepEqual(Buffer.from(await response.arrayBuffer()), png);
80+
});
81+
5582
test('edit keeps identity and records an operation', async () => {
5683
const { issue: current } = await detailOf(issue.id);
5784
const saved = await put('/api/issues', { ...current, title: `${current.title}(已编辑)`, priority: 'high' });

‎e2e/api/30-runs.test.mjs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,22 @@ test('approval gate: reject reworks upstream in the same workspace, approve comp
9999
assert.equal(summary?.status, 'succeeded');
100100
});
101101

102+
test('evaluation waits for the run to finish and leaves no partial history', async () => {
103+
const workflow = await createWorkflow('eval-approval', [script('prepare', 'echo ready'), approval('gate', 'prepare')]);
104+
const { id } = await startRun(workflow);
105+
await waitRun(id, run => nodeStatus(run, 'gate') === 'waiting_approval');
106+
107+
const path = `/api/runs/${id}`;
108+
await post(`${path}/eval`, {}, { expect: 409 });
109+
assert.deepEqual(await get(`${path}/eval`), { runId: id, status: '' });
110+
assert.deepEqual(await get(`${path}/evals`), []);
111+
await get(`${path}/eval/stream`, { expect: 404 });
112+
await post(`${path}/eval/apply`, { recommendationIds: ['missing'] }, { expect: 404 });
113+
114+
await post(`${path}/approve`, { nodeId: 'gate' });
115+
await waitRun(id, run => run.status === 'succeeded');
116+
});
117+
102118
test('failed script: retry from the node succeeds on the second attempt', {
103119
todo: 'POST /api/runs/:id/retry tears the failed attempt\'s sandbox down inside the request (docker rm -f of the agentflow-run-*-scripts sidecar, up to dockerTeardownTimeout=60s); under nested Docker that rm hangs, so the call outlives the 60s client timeout',
104120
}, async () => {

0 commit comments

Comments
 (0)