agent-office: frame only fragments unfinished at EOF in cold image scans (#559)

The incremental session scanner frames only fragments still unfinished at
EOF, instead of passing every 64 KiB fragment of a complete cross-chunk
record through the character framer. A framed-part index stops a later
tick from walking text it already framed. Adds regressions for the four
mutation gaps named on #551 and a WebKit CSP diagnostic script.

Reviewed at 5f564b034df26e12b60c40f683922ce0389abdd1 on main 7714b61.
Run on the Mac mini test box (mote, Bun 1.4.2):
- packages/agent-office: HOME=$(mktemp -d) bun test: 167 pass, 0 fail;
  bun scripts/stamp-page.mjs --check: exit 0.
- Full repo: HOME=$(mktemp -d) bun test: 4321 pass, 9 skip, 0 fail
  (338 files); bun scripts/check.mjs: exit 0.
- Broken by hand: eager framing restored -> both cold-scan tests red;
  framed index not advanced -> 2 red (cold-scan EOF, unfinished quoted
  brace never reparses); ExtendedTail disabled -> extended-EOF test red.
  Each restored -> 167 pass.
- bench-scan.mjs 100 1 1, initial scan: ~29-32 ms at this head vs
  ~294-319 ms at main.
- Host probe: office.hooks.mjs imported without
  MAGPIE_AGENT_OFFICE_PAGE in a sandbox HOME with one Claude session;
  snapshot() ok and page/live.js written.
Not tried: a real magpie install of the page.
This commit is contained in:
QingJ
2026-10-31 19:09:38 +08:00
committed by GitHub
parent 7714b617c7
commit 0e3562b25f
10 changed files with 261 additions and 25 deletions
+4
View File
@@ -21,6 +21,10 @@
### Fixed
- Follow-up after PR #551 approval/merge: skip per-character framing for complete image-heavy records during initial/reset scans; frame only new fragments of the unfinished EOF record.
- Cover identical-witness inode replacement, invalidated committed EOF records, exact Codex-title append reads and unchanged summary caching with independently mutation-checked regressions.
- Narrow the CSP compatibility note to the reproduced Mac Playwright/WebKit build and add a local diagnostic; Linux build 2336 did not reproduce the refusal.
- Secure the standalone server with per-run capability URLs, validated Host and same-origin JSON writes; reject cross-site data/script access.
- Scrub hidden rail, list, conversation and closed-panel DOM when text is disabled.
- Keep stopped 3D renderers stopped across visibility and context restoration; avoid hidden-canvas DPR growth.
+5 -4
View File
@@ -2,7 +2,7 @@
[![Latest release](https://img.shields.io/github/v/release/QingJ01/magpie-agent-office)](https://github.com/QingJ01/magpie-agent-office/releases)
[![magpie ≥ 0.1.1318](https://img.shields.io/badge/magpie-%E2%89%A5%200.1.1318-4f46e5)](https://usemagpie.ai)
[![Tests](https://img.shields.io/badge/tests-163%20passing-22a35a)](#test)
[![Tests](https://img.shields.io/badge/tests-167%20passing-22a35a)](#test)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
**一个住在 magpie 窗口里的实时 Agent 办公室。** 直接读取各 Agent 自己的会话记录,把正在思考、执行工具、等待批准或已经完成的工作,变成真 3D 办公室里的小人;也可以切到等距画布、俯视 2D 或分组列表。
@@ -172,7 +172,7 @@ bun bin/agent-office.mjs [--port 4545] [--hours 48] [--private] [--json] [--no-o
bun test
```
163 项测试覆盖会话解析(含新客户端)、隐私、路径与朝向、沙发合成、2D 活动点、相机、昼夜、3D API、CLI 与独立服务。3D 回归测试执行随包 THREE 的真实场景、几何、动画和矩阵路径,仅替换 GPU 边界;另有真实 magpie 页面宿主的浏览器回归脚本 `test/browser.mjs`,覆盖 Retina 窄视口、菜单边界、标签碰撞、切换与关闭文本后的 DOM。
167 项测试覆盖会话解析(含新客户端)、隐私、路径与朝向、沙发合成、2D 活动点、相机、昼夜、3D API、CLI 与独立服务。3D 回归测试执行随包 THREE 的真实场景、几何、动画和矩阵路径,仅替换 GPU 边界;另有真实 magpie 页面宿主的浏览器回归脚本 `test/browser.mjs`,覆盖 Retina 窄视口、菜单边界、标签碰撞、切换与关闭文本后的 DOM。
```sh
# 可选浏览器测试(另行安装 Playwright 与浏览器,先启动 magpie web)
@@ -180,7 +180,7 @@ OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs \
OFFICE_HOST_URL="http://127.0.0.1:4571/?k=YOUR_LOCAL_KEY" bun test/browser.mjs
```
magpie 0.1.2305 的 Web 宿主在 CSP 源地址中省略协议;WebKit 会拒绝加载资源,Chromium 则接受。WebKit 集成检查需显式设置 `OFFICE_NORMALIZE_WEBKIT_CSP=1`,仅在测试响应中补全现有地址的协议,不改变域名、目录白名单或 sandbox。未修改宿主的 WebKit 集成仍受此问题阻塞,不能视为已通过。
在 macOS 15.7.9(24G830,arm64)、Playwright 1.56.1 的 WebKit 26.0(build 2215)上,测试的无协议数字主机 CSP 源会阻止脚本加载,补全 `http://` 后同一 sandbox 内可执行。维护者使用 Linux WebKit build 2336 未复现,因此这不是对所有 WebKit / Safari 的结论;原生 Safari / WKWebView 未自动化测试。受影响的 Mac 环境可显式设置 `OFFICE_NORMALIZE_WEBKIT_CSP=1`,仅规范化测试响应里的协议,保持原域名、目录白名单和 sandbox。可用 `OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs bun test/webkit-csp.mjs` 收集本机版本、实际 CSP 和控制台错误;详见 [后续验证](docs/follow-up-validation.md)。
JSONL 首次打开会重放一次,后续轮询保留字节偏移、UTF-8/JSON 分帧和各 reader 的解析状态,只解析追加的完整记录。截断、替换和同尺寸重写会重建状态;每次增长额外检查最多 128 字节的前缀/旧末尾,识别常见的两次轮询间截断再增长。未变化时不读取日志。metadata/usage sidecar 仅在其版本变化时重读;Codex 标题索引也采用追加游标。
@@ -189,9 +189,10 @@ JSONL 首次打开会重放一次,后续轮询保留字节偏移、UTF-8/JSON
```sh
bun scripts/bench-scan.mjs 100 1 # 一份 100 MiB 日志
bun scripts/bench-scan.mjs 100 4 # 四份并发日志
bun scripts/bench-scan.mjs 100 1 1 # 每 30 条文本后包含 1 MiB base64 图片
```
普通 JSONL 按追加日志处理;任意修改中部、同时保留 inode 与两处检查片段又增长的非追加编辑无法在不重读整个文件的前提下完整识别。初次读取或重建仍有 O(文件大小) 成本。完整 JSON 文档、压缩 DSH 和发生变化的 usage sidecar 仍按各自快照格式读取。
普通 JSONL 按追加日志处理;任意修改中部、同时保留 inode 与两处检查片段又增长的非追加编辑无法在不重读整个文件的前提下完整识别。初次读取或重建仍有 O(文件大小) 成本,但完整记录即使跨读取块也直接解析,只有 EOF 未完成的记录需要词法分帧。完整 JSON 文档、压缩 DSH 和发生变化的 usage sidecar 仍按各自快照格式读取。
修改页面资源后运行 `bun scripts/stamp-page.mjs` 更新内容指纹;`--check` 可验证没有旧指纹。画质切换调整像素比和阴影,抗锯齿在 WebGL 上下文创建时固定。人物使用 InstancedMesh 批量绘制,保留四肢动画与各 Agent 颜色。
+55
View File
@@ -0,0 +1,55 @@
import { afterAll, expect, test } from "bun:test"
import { appendFileSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { createScanner } from "./lib/scan.mjs"
const roots=[]
const tmp=()=>{const root=mkdtempSync(join(tmpdir(),"office-cold-"));roots.push(root);return root}
afterAll(()=>{for(const root of roots)rmSync(root,{recursive:true,force:true})})
const now=Date.now(),timestamp=new Date(now).toISOString()
const line=record=>JSON.stringify(record)+"\n"
const user=text=>({type:"user",timestamp,message:{role:"user",content:text}})
const scanner=root=>createScanner({sources:[{root,kind:"claude",agent:"claude",depth:0,match:name=>name.endsWith(".jsonl")}]})
// framePart walks characters with String's iterator. Count actual large
// string traversal, rather than asserting a machine-dependent time limit.
// JSON.parse handles completed lines natively and does not use this hook.
function traversal(run) {
const original=String.prototype[Symbol.iterator]
let chars=0
String.prototype[Symbol.iterator]=function(){const text=String(this);if(text.length>=512)chars+=text.length;return original.call(this)}
try{return {result:run(),get chars(){return chars}}}finally{String.prototype[Symbol.iterator]=original}
}
test("cold image records spanning read chunks skip lexical character traversal",()=>{
const root=tmp(),path=join(root,"cold.jsonl")
const image=line({type:"assistant",timestamp,message:{role:"assistant",content:[{type:"image",source:{type:"base64",data:"A".repeat(1024*1024)}}],stop_reason:"end_turn"}})
writeFileSync(path,line(user("cold image work"))+image.repeat(4))
const sc=scanner(root)
const measured=traversal(()=>sc.scan(now)[0])
expect(measured.result).toMatchObject({query:"cold image work",turns:1,phase:"done"})
expect(measured.chars).toBe(0)
expect(sc.files.get(path).cursor.parts).toHaveLength(0)
expect(sc.files.get(path).cursor.framedParts).toBe(0)
})
test("only the EOF fragment is framed and existing fragments are not walked on later ticks",()=>{
const root=tmp(),path=join(root,"tail.jsonl")
const image=line({type:"padding",data:"A".repeat(1024*1024)})
const tail='{"type":"padding","text":"'+"q".repeat(10000)
writeFileSync(path,image+tail)
const sc=scanner(root)
const first=traversal(()=>sc.scan(now))
expect(first.chars).toBe(tail.length)
const unchanged=traversal(()=>sc.scan(now))
expect(unchanged.chars).toBe(0)
const more="x".repeat(1000)+"}"
appendFileSync(path,more)
const appended=traversal(()=>sc.scan(now))
expect(appended.chars).toBe(more.length)
appendFileSync(path,'"}\n'+line(user("after image")))
const completed=traversal(()=>sc.scan(now)[0])
expect(completed.result).toMatchObject({query:"after image",turns:1})
expect(completed.chars).toBe(0)
expect(sc.files.get(path).cursor.parts).toHaveLength(0)
})
@@ -0,0 +1,70 @@
# Post-merge follow-up for Agent Office 0.2.0
[PR #551 was approved and merged](https://github.com/magpie-community/plugins/pull/551#issuecomment-6542153594). This follow-up addresses its nonblocking cold-scan performance and test-coverage notes. Version remains 0.2.0; no Release/tag or npm publication is performed here. The maintainer notes that the package owner's first npm publication must be manual.
## Image-heavy initial scans
`readAppended` now buffers fragments through each read chunk and sends complete records directly to the reader. Only fragments still unfinished at the captured EOF pass through `framePart`. A fragment index remembers earlier ticks, so unfinished input is not walked again. Newline completion and committed-EOF resets clear both framing state and index.
Reproduce using synthetic logs, without real agent sessions or model calls:
```sh
bun scripts/bench-scan.mjs 100 1 1
```
The third argument adds a 1 MiB base64 image after every 30 approximately 4 KiB text records. Three separate-process comparisons on this Mac, with identical benchmark generation and the pre-fix/current scanner:
| Trial | Before initial scan | After initial scan |
| --- | ---: | ---: |
| 1 | 926.863 ms | 91.509 ms |
| 2 | 769.519 ms | 69.433 ms |
| 3 | 761.180 ms | 68.780 ms |
Initial/reset reads still require O(file size) I/O and JSON parsing. This removes redundant lexical traversal of completed records; it is not a constant-time first scan or a cross-machine speed guarantee. Timings are evidence, not test thresholds.
`cold-scan.test.mjs` counts actual large-string iterator traversal used by the lexical framer. Complete image records spanning multiple read chunks cause zero such traversal. Only the unfinished EOF text is framed, with zero revisits on unchanged ticks and only new fragments on appended ticks. Restoring eager chunk framing makes both tests fail.
## Mutation gaps closed
The targeted scanner suite passes 13 tests. Each isolated broken temporary scanner caused its intended regression to fail:
| Broken behavior | Regression evidence |
| --- | --- |
| Ignore inode/birthtime identity | New inode fixture preserves first 64 bytes and the previous-offset last 64 bytes, alters equal-length middle text and grows. Fresh-reader equivalence fails if identity is ignored. |
| Disable `ExtendedTail` replay | Appending non-whitespace before the newline invalidates a previously committed EOF assistant record. Correct replay removes its usage; disabled replay disagrees with a fresh scanner. |
| Always rebuild Codex title cursor | Long index with exact append/probe offsets: expected 423 bytes, broken scanner reads 311,705. Unchanged ticks must read zero. |
| Re-read unchanged summary on every append | Summary marker is counted independently of usage parsing: expected zero parses, broken scanner performs one. A changed-summary positive control proves the counter is active. |
Full plugin suite: **167 passed, 0 failed**, 14 files. The original incremental byte, partial image/UTF-8, quoted-brace, interrupted-read, daily usage and metadata tests remain enabled. Temporary mutation copies were removed; no real logs were used.
## Mac WebKit CSP evidence
[The maintainer did not reproduce the refusal on Linux WebKit build 2336](https://github.com/magpie-community/plugins/pull/551#issuecomment-6541781777). The earlier README statement was too broad and is narrowed to this observed environment:
- macOS **15.7.9**, build **24G830**, arm64.
- Playwright **1.56.1**, WebKit `browser.version()` **26.0**, installed build **2215**.
- Bun **1.4.4** local HTTP server; parent embeds `sandbox="allow-scripts"`; plugin loads only its own `app.js`.
- Native Safari and native WKWebView were not automated. Platform versus engine-version causality has not been isolated.
Reproduce and collect current versions, actual CSP headers, execution markers and console errors:
```sh
OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs bun test/webkit-csp.mjs
```
The diagnostic accepts either scheme-less outcome; the explicit-source control must execute. It creates an ephemeral localhost server and closes browser/server in `finally`. No account, model, bridge mock or external network is needed.
Captured actual headers at one run's port 50299:
```text
default-src 'none'; script-src 127.0.0.1:50299/_magpie/plugin/tok/;
default-src 'none'; script-src http://127.0.0.1:50299/_magpie/plugin/tok/;
```
The first policy returned HTTP 200 but blocked the script before a request reached the server. Exact console message:
```text
Refused to load http://127.0.0.1:50299/_magpie/plugin/tok/app.js?policy=scheme-less because it does not appear in the script-src directive of the Content Security Policy.
```
The explicit policy returned HTTP 200, requested/executed the script and logged `APP_EXECUTED`. Both frames had opaque document origin `"null"` (their URL origin was the HTTP origin), and neither produced a `pageerror`. This supports the specific Mac test observation and does not contradict the maintainer's Linux result. The existing normalization flag remains opt-in and test-only.
@@ -1,6 +1,6 @@
# 0.2.0 review validation
This is the 0.2.0 repair for [PR #551](https://github.com/magpie-community/plugins/pull/551). No release/tag is created or moved for this repair. CI success is not maintainer approval; the requested-changes review still needs re-review.
[PR #551](https://github.com/magpie-community/plugins/pull/551) was approved at 3bf522f and merged on 2026-10-31. The results below record that repair. Nonblocking post-merge improvements and current validation are recorded in [follow-up validation](follow-up-validation.md). No release/tag is created or moved by these repairs.
## Review blockers
@@ -12,7 +12,7 @@ This is the 0.2.0 repair for [PR #551](https://github.com/magpie-community/plugi
## Other findings
- Today refreshes from private daily buckets at local midnight. Changed JSONL logs replay fully with a UTF-8-safe chunk iterator. Grok usage.json uses the published vendor per-turn schema; sidecar-only edits invalidate cache.
- Today refreshes from private daily buckets at local midnight. Changed JSONL logs retain UTF-8-safe cursors and parse appended records. Grok usage.json uses the published vendor per-turn schema; sidecar-only edits invalidate cache.
- No-progress/idle labels update without new writes. No-progress sessions can be cleared until their next write. Rail/list labels agree; filters do not replay old error toasts.
- Bun requirement, occupied-port behavior, --port 0, Grok skill support and capability URL documentation are accurate.
- Nine-language scene/quality/fallback/role/venue text; focused camera shortcuts; wheel handling only consumes a zoom change; notification dots.
@@ -29,7 +29,7 @@ Browser tests use actual magpie Web UI navigation, options bridge, theme and san
DPR-2 window sizes 600×620, 820×650 and 1440×1000 give plugin CSS viewports 576×500, 788×594 and 1196×944. Checks cover menus, tag collisions, modes, hidden buffers, the No-progress clock, alert history and text-off scrubbing. The largest size also exercises six scenes and three quality settings.
**Chromium passes unchanged. WebKit limitation:** magpie 0.1.2305's Web host emits scheme-less numeric-host CSP sources, which WebKit rejects. WebKit UI checks pass only with explicit `OFFICE_NORMALIZE_WEBKIT_CSP=1`, adding the existing URL scheme while preserving the same host/path allowlist and sandbox. Unmodified WebKit Web-host integration remains blocked by that host CSP behavior. Native WKWebView was not automated.
**Chromium passed unchanged. Mac WebKit qualification:** the observed refusal is limited to Playwright 1.56.1 WebKit 26.0 build 2215 on macOS 15.7.9 (24G830, arm64). Its UI checks used explicit `OFFICE_NORMALIZE_WEBKIT_CSP=1`; host/path/sandbox were preserved. The maintainer reports no reproduction on Linux build 2336. This is not a general WebKit or native Safari/WKWebView result; see the [minimal repro and exact console error](follow-up-validation.md#mac-webkit-csp-evidence).
Synthetic narrow-frame evidence: [settings](qa-retina-settings.png), [text disabled](qa-retina-privacy.png).
@@ -56,4 +56,4 @@ Reproducible synthetic benchmark: `bun scripts/bench-scan.mjs 100 1` and `bun sc
These are measurements on this machine, not CI speed thresholds. Deterministic tests assert byte and parse counts instead. Complete usage sidecars are not retained or re-aggregated on each append; only current day totals are retained by the reader. Gemini JSON documents and compressed DSH snapshots remain full-document reads when changed.
Follow-up validation at the incremental repair: full marketplace `HOME=$(mktemp -d) bun test` completed with **4115 passed, 4 skipped, 0 failed**, across 327 files. Package tests pass 163 tests across 13 files. The installed 0.2.0 scanner/readers were checked against the source SHA-256 hashes. CI passed for the incremental code commit; maintainer re-review is still required.
Follow-up validation at the incremental repair: full marketplace `HOME=$(mktemp -d) bun test` completed with **4115 passed, 4 skipped, 0 failed**, across 327 files. Package tests pass 163 tests across 13 files. The installed 0.2.0 scanner/readers were checked against the source SHA-256 hashes. CI passed for the incremental code commit; maintainer approval and merge followed at 3bf522f.
@@ -69,6 +69,47 @@ test("a complete record flushed before its newline is applied exactly once",()=>
expect(scanner.scan(time)[0]).toMatchObject({turns:1,tokensToday:130})
})
test("non-whitespace extending an EOF-committed record replays the invalidated line",()=>{
const root=tmp(),path=join(root,"extended-eof.jsonl")
writeFileSync(path,line(user("before"))+JSON.stringify(done("speculative",30)))
const {scanner,reads,reset}=tracked([source(root)])
expect(scanner.scan(time)[0]).toMatchObject({turns:1,tokensToday:130,phase:"done"})
const reader=scanner.files.get(path).reader
// The previously valid JSON now has trailing junk before its first newline.
// Fresh parsing must discard that entire line, including its usage/phase.
appendFileSync(path,"invalid extension\n"+line(user("after")))
reset()
const actual=scanner.scan(time)[0]
expect(actual).toEqual(createScanner({sources:[source(root)]}).scan(time)[0])
expect(actual).toMatchObject({turns:2,tokensToday:0,query:"after",phase:"thinking"})
expect(scanner.files.get(path).reader).not.toBe(reader)
expect(reads.filter(r=>r.position===0)).toHaveLength(2) // prefix probe, then fresh replay
})
test("inode replacement resets even when both append witnesses are identical",()=>{
const root=tmp(),path=join(root,"identity.jsonl"),replacement=join(root,"replacement.tmp")
const prefix=line({type:"padding",text:"p".repeat(256)})
const suffix=line({type:"padding",text:"s".repeat(256)})
const initial=Buffer.from(prefix+line(user("OLD middle"))+suffix)
const replaced=Buffer.from(prefix+line(user("NEW middle"))+suffix+line(done("replacement",20)))
writeFileSync(path,initial)
const {scanner,reads,reset}=tracked([source(root)])
expect(scanner.scan(time)[0]).toMatchObject({query:"OLD middle",turns:1})
const reader=scanner.files.get(path).reader,identity=statSync(path)
expect(replaced.length).toBeGreaterThan(initial.length)
expect(replaced.subarray(0,64)).toEqual(initial.subarray(0,64))
expect(replaced.subarray(initial.length-64,initial.length)).toEqual(initial.subarray(-64))
writeFileSync(replacement,replaced);renameSync(replacement,path)
expect(statSync(path).ino).not.toBe(identity.ino)
reset()
const actual=scanner.scan(time)[0]
expect(actual).toEqual(createScanner({sources:[source(root)]}).scan(time)[0])
expect(actual).toMatchObject({query:"NEW middle",turns:1,tokensToday:120})
expect(scanner.files.get(path).reader).not.toBe(reader)
expect(reads[0].position).toBe(0)
expect(reads.reduce((sum,r)=>sum+r.n,0)).toBe(replaced.length)
})
test("a partially written large image record reads new bytes plus bounded guards",()=>{
const root=tmp(),path=join(root,"image.jsonl")
writeFileSync(path,line(user("before image")))
@@ -117,17 +158,27 @@ test("midnight and metadata-only changes do not read JSONL again",()=>{
expect(scanner.scan(before)[0]).toMatchObject({title:"old title",tokensToday:110,turnsToday:1})
reset();expect(scanner.scan(after)[0]).toMatchObject({tokensToday:0,turnsToday:0})
expect(bytes()).toBe(0)
writeFileSync(meta,JSON.stringify({title:"new title"}));writeFileSync(usage,JSON.stringify(use(200)))
writeFileSync(meta,JSON.stringify({title:"new title",summaryCacheProbe:"summary-cache-marker"}));writeFileSync(usage,JSON.stringify(use(200)))
reset();expect(scanner.scan(before)[0]).toMatchObject({title:"new title",tokensToday:210,turnsToday:1})
expect(bytes()).toBe(0)
const original=JSON.parse
let sidecarParses=0
JSON.parse=function(text,...args){if(String(text).includes('"endedAt"'))sidecarParses++;return original.call(this,text,...args)}
let usageParses=0,summaryParses=0
JSON.parse=function(text,...args){
if(String(text).includes('"endedAt"'))usageParses++
if(String(text).includes('"summaryCacheProbe"'))summaryParses++
return original.call(this,text,...args)
}
try {
appendFileSync(path,line({timestamp:before/1000,params:{update:{sessionUpdate:"agent_message_chunk",content:{text:"hello"}}}}))
expect(scanner.scan(before)[0]).toMatchObject({tokensToday:210,title:"new title"})
expect(sidecarParses).toBe(0)
expect(usageParses).toBe(0)
expect(summaryParses).toBe(0)
expect(scanner.files.get(path)).not.toHaveProperty("usageValue")
writeFileSync(meta,JSON.stringify({title:"changed summary title",summaryCacheProbe:"summary-cache-marker"}))
reset();expect(scanner.scan(before)[0].title).toBe("changed summary title")
expect(summaryParses).toBe(1)
expect(usageParses).toBe(0)
expect(bytes()).toBe(0)
}finally{JSON.parse=original}
rmSync(meta)
reset();expect(scanner.scan(before)[0]).toMatchObject({title:"work",cwd:"",model:"",subagent:false,tokensToday:210})
@@ -188,17 +239,25 @@ test("Codex thread titles also reuse an append cursor",()=>{
mkdirSync(sessions)
const id="019a0000-0000-7000-8000-000000000001",path=join(sessions,`rollout-${id}.jsonl`)
writeFileSync(path,line({timestamp:stamp,type:"session_meta",payload:{id,cwd:"/fixture"}}))
writeFileSync(index,line({id,thread_name:"old title"}))
writeFileSync(index,line({id,thread_name:"old title"})+Array.from({length:1024},(_,i)=>line({id:`unrelated-${i}`,thread_name:"padding "+"x".repeat(256)})).join(""))
const indexSize=statSync(index).size
const previous=process.env.CODEX_HOME;process.env.CODEX_HOME=root
try {
const {scanner,bytes,reset}=tracked([source(sessions,"codex")])
const {scanner,reads,bytes,reset}=tracked([source(sessions,"codex")])
const sessionSize=statSync(path).size
expect(scanner.scan(time)[0].title).toBe("old title")
expect(bytes()).toBe(sessionSize+indexSize)
reset();scanner.scan(time);expect(bytes()).toBe(0)
const more=line({timestamp:stamp,type:"event_msg",payload:{type:"task_complete"}})
const title=line({id,thread_name:"new title"})
appendFileSync(path,more);appendFileSync(index,title);reset()
expect(scanner.scan(time)[0].title).toBe("new title")
expect(bytes()).toBeLessThanOrEqual(Buffer.byteLength(more+title)+256)
expect(bytes()).toBe(Buffer.byteLength(more+title)+256)
expect(reads.map(r=>({position:r.position,n:r.n}))).toEqual([
{position:0,n:64},{position:sessionSize-64,n:64},{position:sessionSize,n:Buffer.byteLength(more)},
{position:0,n:64},{position:indexSize-64,n:64},{position:indexSize,n:Buffer.byteLength(title)},
])
reset();expect(scanner.scan(time)[0].title).toBe("new title");expect(bytes()).toBe(0)
writeFileSync(index,line({id,thread_name:"alt title"}))
utimesSync(index,(time+1000)/1000,(time+1000)/1000)
expect(scanner.scan(time)[0].title).toBe("alt title")
+7 -2
View File
@@ -126,7 +126,7 @@ function framePart(state, text) {
}
}
function cursor() {
return { offset: 0, decoder: new StringDecoder("utf8"), parts: [], frame: framing(), committedTail: false, prefix: Buffer.alloc(0), tail: Buffer.alloc(0) }
return { offset: 0, decoder: new StringDecoder("utf8"), parts: [], framedParts: 0, frame: framing(), committedTail: false, prefix: Buffer.alloc(0), tail: Buffer.alloc(0) }
}
// Size growth alone cannot distinguish append from truncate-and-regrow
// between ticks. Verify at most 128 old bytes without parsing any history.
@@ -176,16 +176,20 @@ function* readAppended(f, c, read) {
c.parts.push(part)
const line = c.parts.join("")
c.parts = []
c.framedParts = 0
c.frame = framing()
yield line
} else if (part) {
c.parts.push(part)
framePart(c.frame, part)
}
if (end < 0) break
start = end + 1
}
}
// Completed lines already went straight to the reader, even when they
// span many read chunks. Only the unfinished EOF record needs lexical
// framing; remember which fragments were framed on earlier ticks.
for (; c.framedParts < c.parts.length; c.framedParts++) framePart(c.frame, c.parts[c.framedParts])
// Some clients flush a complete JSON record before its newline. Accept
// it once, but never repeatedly parse a growing base64/text fragment.
if (!c.committedTail && c.frame.complete && !c.frame.invalid && !c.frame.quoted) {
@@ -194,6 +198,7 @@ function* readAppended(f, c, read) {
try { const record = JSON.parse(tail); complete = !!record && typeof record === "object" && !Array.isArray(record) } catch { c.frame.invalid = true }
if (complete) {
c.parts = []
c.framedParts = 0
c.frame = framing()
c.committedTail = true
yield tail
+6 -5
View File
@@ -1,17 +1,18 @@
// Synthetic, local-only scan benchmark; no real agent logs or model calls.
// bun scripts/bench-scan.mjs [size-in-MiB=100] [session-count=1]
// bun scripts/bench-scan.mjs [size-in-MiB=100] [session-count=1] [image-MiB-per-30-lines=0]
import { appendFileSync, closeSync, mkdtempSync, openSync, readSync, rmSync, statSync, writeSync } from "node:fs"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import { performance } from "node:perf_hooks"
import { createScanner } from "../lib/scan.mjs"
const mib=Number(process.argv[2]||100),count=Number(process.argv[3]||1)
if(!Number.isInteger(mib)||mib<1||mib>512||!Number.isInteger(count)||count<1||count>8)throw new Error("Use 1..512 MiB and 1..8 sessions")
const mib=Number(process.argv[2]||100),count=Number(process.argv[3]||1),imageMiB=Number(process.argv[4]||0)
if(!Number.isInteger(mib)||mib<1||mib>512||!Number.isInteger(count)||count<1||count>8||!Number.isInteger(imageMiB)||imageMiB<0||imageMiB>16)throw new Error("Use 1..512 MiB, 1..8 sessions and 0..16 MiB images")
const root=mkdtempSync(join(tmpdir(),"office-scan-bench-")),paths=[]
let bytes=0,calls=0
const iso=new Date().toISOString(),json=x=>JSON.stringify(x)+"\n"
const body=json({type:"assistant",timestamp:iso,message:{role:"assistant",content:[{type:"text",text:"x".repeat(3950)}],stop_reason:"end_turn"}})
const block=Buffer.from(body.repeat(64))
const image=imageMiB?json({type:"assistant",timestamp:iso,message:{role:"assistant",content:[{type:"image",source:{type:"base64",data:"A".repeat(imageMiB*1024*1024)}}],stop_reason:"end_turn"}}):""
const block=Buffer.from(imageMiB?body.repeat(30)+image:body.repeat(64))
try {
for(let i=0;i<count;i++) {
const path=join(root,`session-${i}.jsonl`),fd=openSync(path,"w")
@@ -27,7 +28,7 @@ try {
const observed=sample();if(observed.bytes<expectedBytes||observed.bytes>expectedBytes+128*count)throw new Error(`Append read ${observed.bytes}, expected ${expectedBytes} + bounded guards`)
appends.push({...observed,appendedBytes:expectedBytes,guardBytes:observed.bytes-expectedBytes})
}
console.log(JSON.stringify({sizeMiB:mib,sessionCount:count,totalBytes:paths.reduce((n,p)=>n+statSync(p).size,0),initial,unchanged,appends},null,2))
console.log(JSON.stringify({sizeMiB:mib,sessionCount:count,imageMiB,totalBytes:paths.reduce((n,p)=>n+statSync(p).size,0),initial,unchanged,appends},null,2))
} finally {
const target=resolve(root),prefix=resolve(tmpdir())+"/office-scan-bench-"
if(!target.startsWith(prefix))throw new Error("Unexpected benchmark cleanup path")
+4 -3
View File
@@ -27,9 +27,10 @@ for(const engine of (process.env.OFFICE_BROWSERS||'chromium,webkit').split(','))
const errors=[];page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text())})
await page.route('**/live.js*',route=>route.fulfill({contentType:'text/javascript',body:`globalThis.AgentOfficeLive=${JSON.stringify(snapshot)};`}))
// magpie 0.1.2305 web emits scheme-less numeric-host CSP sources.
// Chromium accepts them; WebKit rejects every resource. Optional test-only
// normalization adds the existing response URL's scheme, keeping the same
// exact host/path allowlist. It does not change the bridge or sandbox.
// Observed refusal: Playwright 1.56.1 / WebKit 26.0 build 2215 on
// macOS 15.7.9 arm64. Maintainer could not reproduce on Linux build 2336.
// Explicit opt-in normalization keeps the same host/path and sandbox;
// it is not evidence that every WebKit/Safari release needs this workaround.
if(engine==='webkit' && process.env.OFFICE_NORMALIZE_WEBKIT_CSP==='1') {
await page.route('**/_magpie/plugin/**/index.html',async route=>{
const response=await route.fetch()
+40
View File
@@ -0,0 +1,40 @@
// Minimal local-only diagnostic for the platform-specific WebKit CSP report.
// OFFICE_PLAYWRIGHT=/path/to/playwright/index.mjs bun test/webkit-csp.mjs
// Reports both outcomes: a working scheme-less source is not a failure.
import { pathToFileURL } from "node:url"
const modulePath=process.env.OFFICE_PLAYWRIGHT
if(!modulePath)throw new Error("Set OFFICE_PLAYWRIGHT to an installed Playwright module")
const {webkit}=await import(modulePath)
const playwrightInfo=await Bun.file(new URL("./package.json",modulePath.startsWith("file:")?modulePath:pathToFileURL(modulePath))).json().catch(()=>null)
const hits=[]
let origin
const server=Bun.serve({hostname:"127.0.0.1",port:0,fetch(request){
const url=new URL(request.url),policy=url.searchParams.get("policy")||"scheme-less"
if(url.pathname==="/")return new Response(`<iframe sandbox="allow-scripts" src="/_magpie/plugin/tok/index.html?policy=${policy}"></iframe>`,{headers:{"content-type":"text/html"}})
if(url.pathname.endsWith("/index.html")) {
const source=policy==="explicit"?`${origin}/_magpie/plugin/tok/`:`127.0.0.1:${server.port}/_magpie/plugin/tok/`
return new Response(`<p id="result">not executed</p><script src="./app.js?policy=${policy}"></script>`,{headers:{"content-type":"text/html","content-security-policy":`default-src 'none'; script-src ${source};`}})
}
if(url.pathname.endsWith("/app.js")){hits.push(policy);return new Response('globalThis.APP_EXECUTED=true;document.querySelector("#result").textContent="executed";console.log("APP_EXECUTED")',{headers:{"content-type":"text/javascript"}})}
return new Response("not found",{status:404})
}})
origin=`http://127.0.0.1:${server.port}`
let browser
try {
browser=await webkit.launch()
const results=[]
for(const policy of ["scheme-less","explicit"]) {
const page=await browser.newPage(),consoleMessages=[],pageErrors=[]
page.on("console",message=>consoleMessages.push({type:message.type(),text:message.text()}))
page.on("pageerror",error=>pageErrors.push(error.message))
const responsePromise=page.waitForResponse(response=>response.url().includes("/index.html"))
await page.goto(`${origin}/?policy=${policy}`)
const response=await responsePromise,frame=page.frames().find(frame=>frame.url().includes("/index.html"))
const observed=await frame.evaluate(()=>({executed:globalThis.APP_EXECUTED===true,text:document.querySelector("#result").textContent,documentOrigin:globalThis.origin,urlOrigin:location.origin}))
results.push({policy,status:response.status(),csp:response.headers()["content-security-policy"],...observed,scriptRequested:hits.includes(policy),consoleMessages,pageErrors})
await page.close()
}
const mac=process.platform==="darwin"?new TextDecoder().decode(Bun.spawnSync({cmd:["/usr/bin/sw_vers"]}).stdout).trim():null
console.log(JSON.stringify({platform:process.platform,arch:process.arch,macOS:mac,bun:Bun.version,playwrightVersion:playwrightInfo?.version||null,webkitVersion:browser.version(),webkitBuild:webkit.executablePath().match(/webkit-(\d+)/)?.[1]||null,results},null,2))
if(!results.find(r=>r.policy==="explicit").executed)throw new Error("Explicit source control did not execute")
}finally{if(browser)await browser.close();server.stop(true)}